1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "oat.h"
18 
19 #include <string.h>
20 
21 #include "android-base/stringprintf.h"
22 
23 #include "arch/instruction_set.h"
24 #include "arch/instruction_set_features.h"
25 #include "base/bit_utils.h"
26 #include "base/strlcpy.h"
27 
28 namespace art {
29 
30 using android::base::StringPrintf;
31 
32 constexpr const char OatHeader::kTrueValue[];
33 constexpr const char OatHeader::kFalseValue[];
34 
ComputeOatHeaderSize(const SafeMap<std::string,std::string> * variable_data)35 static size_t ComputeOatHeaderSize(const SafeMap<std::string, std::string>* variable_data) {
36   size_t estimate = 0U;
37   if (variable_data != nullptr) {
38     SafeMap<std::string, std::string>::const_iterator it = variable_data->begin();
39     SafeMap<std::string, std::string>::const_iterator end = variable_data->end();
40     for ( ; it != end; ++it) {
41       estimate += it->first.length() + 1;
42       estimate += it->second.length() + 1;
43     }
44   }
45   return sizeof(OatHeader) + estimate;
46 }
47 
Create(InstructionSet instruction_set,const InstructionSetFeatures * instruction_set_features,uint32_t dex_file_count,const SafeMap<std::string,std::string> * variable_data)48 OatHeader* OatHeader::Create(InstructionSet instruction_set,
49                              const InstructionSetFeatures* instruction_set_features,
50                              uint32_t dex_file_count,
51                              const SafeMap<std::string, std::string>* variable_data) {
52   // Estimate size of optional data.
53   size_t needed_size = ComputeOatHeaderSize(variable_data);
54 
55   // Reserve enough memory.
56   void* memory = operator new (needed_size);
57 
58   // Create the OatHeader in-place.
59   return new (memory) OatHeader(instruction_set,
60                                 instruction_set_features,
61                                 dex_file_count,
62                                 variable_data);
63 }
64 
OatHeader(InstructionSet instruction_set,const InstructionSetFeatures * instruction_set_features,uint32_t dex_file_count,const SafeMap<std::string,std::string> * variable_data)65 OatHeader::OatHeader(InstructionSet instruction_set,
66                      const InstructionSetFeatures* instruction_set_features,
67                      uint32_t dex_file_count,
68                      const SafeMap<std::string, std::string>* variable_data)
69     : oat_checksum_(0u),
70       instruction_set_(instruction_set),
71       instruction_set_features_bitmap_(instruction_set_features->AsBitmap()),
72       dex_file_count_(dex_file_count),
73       oat_dex_files_offset_(0),
74       executable_offset_(0),
75       jni_dlsym_lookup_trampoline_offset_(0),
76       jni_dlsym_lookup_critical_trampoline_offset_(0),
77       quick_generic_jni_trampoline_offset_(0),
78       quick_imt_conflict_trampoline_offset_(0),
79       quick_resolution_trampoline_offset_(0),
80       quick_to_interpreter_bridge_offset_(0),
81       nterp_trampoline_offset_(0) {
82   // Don't want asserts in header as they would be checked in each file that includes it. But the
83   // fields are private, so we check inside a method.
84   static_assert(decltype(magic_)().size() == kOatMagic.size(),
85                 "Oat magic and magic_ have different lengths.");
86   static_assert(decltype(version_)().size() == kOatVersion.size(),
87                 "Oat version and version_ have different lengths.");
88 
89   magic_ = kOatMagic;
90   version_ = kOatVersion;
91 
92   CHECK_NE(instruction_set, InstructionSet::kNone);
93 
94   // Flatten the map. Will also update variable_size_data_size_.
95   Flatten(variable_data);
96 }
97 
IsValid() const98 bool OatHeader::IsValid() const {
99   if (magic_ != kOatMagic) {
100     return false;
101   }
102   if (version_ != kOatVersion) {
103     return false;
104   }
105   if (!IsAligned<kPageSize>(executable_offset_)) {
106     return false;
107   }
108   if (!IsValidInstructionSet(instruction_set_)) {
109     return false;
110   }
111   return true;
112 }
113 
GetValidationErrorMessage() const114 std::string OatHeader::GetValidationErrorMessage() const {
115   if (magic_ != kOatMagic) {
116     static_assert(kOatMagic.size() == 4, "kOatMagic has unexpected length");
117     return StringPrintf("Invalid oat magic, expected 0x%02x%02x%02x%02x, got 0x%02x%02x%02x%02x.",
118                         kOatMagic[0], kOatMagic[1], kOatMagic[2], kOatMagic[3],
119                         magic_[0], magic_[1], magic_[2], magic_[3]);
120   }
121   if (version_ != kOatVersion) {
122     static_assert(kOatVersion.size() == 4, "kOatVersion has unexpected length");
123     return StringPrintf("Invalid oat version, expected 0x%02x%02x%02x%02x, got 0x%02x%02x%02x%02x.",
124                         kOatVersion[0], kOatVersion[1], kOatVersion[2], kOatVersion[3],
125                         version_[0], version_[1], version_[2], version_[3]);
126   }
127   if (!IsAligned<kPageSize>(executable_offset_)) {
128     return "Executable offset not page-aligned.";
129   }
130   if (!IsValidInstructionSet(instruction_set_)) {
131     return StringPrintf("Invalid instruction set, %d.", static_cast<int>(instruction_set_));
132   }
133   return "";
134 }
135 
136 // Do not move this into the header.  The method must be compiled in the runtime library,
137 // so that we can check that the compile-time oat version matches the version in the caller.
CheckOatVersion(std::array<uint8_t,4> version)138 void OatHeader::CheckOatVersion(std::array<uint8_t, 4> version) {
139   constexpr std::array<uint8_t, 4> expected = kOatVersion;  // Runtime oat version.
140   if (version != kOatVersion) {
141     LOG(FATAL) << StringPrintf("Invalid oat version, expected 0x%02x%02x%02x%02x, "
142                                    "got 0x%02x%02x%02x%02x.",
143                                expected[0], expected[1], expected[2], expected[3],
144                                version[0], version[1], version[2], version[3]);
145   }
146 }
147 
GetMagic() const148 const char* OatHeader::GetMagic() const {
149   CHECK(IsValid());
150   return reinterpret_cast<const char*>(magic_.data());
151 }
152 
GetChecksum() const153 uint32_t OatHeader::GetChecksum() const {
154   CHECK(IsValid());
155   return oat_checksum_;
156 }
157 
SetChecksum(uint32_t oat_checksum)158 void OatHeader::SetChecksum(uint32_t oat_checksum) {
159   oat_checksum_ = oat_checksum;
160 }
161 
GetInstructionSet() const162 InstructionSet OatHeader::GetInstructionSet() const {
163   CHECK(IsValid());
164   return instruction_set_;
165 }
166 
GetInstructionSetFeaturesBitmap() const167 uint32_t OatHeader::GetInstructionSetFeaturesBitmap() const {
168   CHECK(IsValid());
169   return instruction_set_features_bitmap_;
170 }
171 
GetOatDexFilesOffset() const172 uint32_t OatHeader::GetOatDexFilesOffset() const {
173   DCHECK(IsValid());
174   DCHECK_GT(oat_dex_files_offset_, sizeof(OatHeader));
175   return oat_dex_files_offset_;
176 }
177 
SetOatDexFilesOffset(uint32_t oat_dex_files_offset)178 void OatHeader::SetOatDexFilesOffset(uint32_t oat_dex_files_offset) {
179   DCHECK_GT(oat_dex_files_offset, sizeof(OatHeader));
180   DCHECK(IsValid());
181   DCHECK_EQ(oat_dex_files_offset_, 0u);
182 
183   oat_dex_files_offset_ = oat_dex_files_offset;
184 }
185 
GetExecutableOffset() const186 uint32_t OatHeader::GetExecutableOffset() const {
187   DCHECK(IsValid());
188   DCHECK_ALIGNED(executable_offset_, kPageSize);
189   CHECK_GT(executable_offset_, sizeof(OatHeader));
190   return executable_offset_;
191 }
192 
SetExecutableOffset(uint32_t executable_offset)193 void OatHeader::SetExecutableOffset(uint32_t executable_offset) {
194   DCHECK_ALIGNED(executable_offset, kPageSize);
195   CHECK_GT(executable_offset, sizeof(OatHeader));
196   DCHECK(IsValid());
197   DCHECK_EQ(executable_offset_, 0U);
198 
199   executable_offset_ = executable_offset;
200 }
201 
GetTrampoline(const OatHeader & header,uint32_t offset)202 static const void* GetTrampoline(const OatHeader& header, uint32_t offset) {
203   return (offset != 0u) ? reinterpret_cast<const uint8_t*>(&header) + offset : nullptr;
204 }
205 
GetJniDlsymLookupTrampoline() const206 const void* OatHeader::GetJniDlsymLookupTrampoline() const {
207   return GetTrampoline(*this, GetJniDlsymLookupTrampolineOffset());
208 }
209 
GetJniDlsymLookupTrampolineOffset() const210 uint32_t OatHeader::GetJniDlsymLookupTrampolineOffset() const {
211   DCHECK(IsValid());
212   return jni_dlsym_lookup_trampoline_offset_;
213 }
214 
SetJniDlsymLookupTrampolineOffset(uint32_t offset)215 void OatHeader::SetJniDlsymLookupTrampolineOffset(uint32_t offset) {
216   DCHECK(IsValid());
217   DCHECK_EQ(jni_dlsym_lookup_trampoline_offset_, 0U) << offset;
218 
219   jni_dlsym_lookup_trampoline_offset_ = offset;
220 }
221 
GetJniDlsymLookupCriticalTrampoline() const222 const void* OatHeader::GetJniDlsymLookupCriticalTrampoline() const {
223   return GetTrampoline(*this, GetJniDlsymLookupCriticalTrampolineOffset());
224 }
225 
GetJniDlsymLookupCriticalTrampolineOffset() const226 uint32_t OatHeader::GetJniDlsymLookupCriticalTrampolineOffset() const {
227   DCHECK(IsValid());
228   return jni_dlsym_lookup_critical_trampoline_offset_;
229 }
230 
SetJniDlsymLookupCriticalTrampolineOffset(uint32_t offset)231 void OatHeader::SetJniDlsymLookupCriticalTrampolineOffset(uint32_t offset) {
232   DCHECK(IsValid());
233   DCHECK_EQ(jni_dlsym_lookup_critical_trampoline_offset_, 0U) << offset;
234 
235   jni_dlsym_lookup_critical_trampoline_offset_ = offset;
236 }
237 
GetQuickGenericJniTrampoline() const238 const void* OatHeader::GetQuickGenericJniTrampoline() const {
239   return GetTrampoline(*this, GetQuickGenericJniTrampolineOffset());
240 }
241 
GetQuickGenericJniTrampolineOffset() const242 uint32_t OatHeader::GetQuickGenericJniTrampolineOffset() const {
243   DCHECK(IsValid());
244   CHECK_GE(quick_generic_jni_trampoline_offset_, jni_dlsym_lookup_trampoline_offset_);
245   return quick_generic_jni_trampoline_offset_;
246 }
247 
SetQuickGenericJniTrampolineOffset(uint32_t offset)248 void OatHeader::SetQuickGenericJniTrampolineOffset(uint32_t offset) {
249   CHECK(offset == 0 || offset >= jni_dlsym_lookup_trampoline_offset_);
250   DCHECK(IsValid());
251   DCHECK_EQ(quick_generic_jni_trampoline_offset_, 0U) << offset;
252 
253   quick_generic_jni_trampoline_offset_ = offset;
254 }
255 
GetQuickImtConflictTrampoline() const256 const void* OatHeader::GetQuickImtConflictTrampoline() const {
257   return GetTrampoline(*this, GetQuickImtConflictTrampolineOffset());
258 }
259 
GetQuickImtConflictTrampolineOffset() const260 uint32_t OatHeader::GetQuickImtConflictTrampolineOffset() const {
261   DCHECK(IsValid());
262   CHECK_GE(quick_imt_conflict_trampoline_offset_, quick_generic_jni_trampoline_offset_);
263   return quick_imt_conflict_trampoline_offset_;
264 }
265 
SetQuickImtConflictTrampolineOffset(uint32_t offset)266 void OatHeader::SetQuickImtConflictTrampolineOffset(uint32_t offset) {
267   CHECK(offset == 0 || offset >= quick_generic_jni_trampoline_offset_);
268   DCHECK(IsValid());
269   DCHECK_EQ(quick_imt_conflict_trampoline_offset_, 0U) << offset;
270 
271   quick_imt_conflict_trampoline_offset_ = offset;
272 }
273 
GetQuickResolutionTrampoline() const274 const void* OatHeader::GetQuickResolutionTrampoline() const {
275   return GetTrampoline(*this, GetQuickResolutionTrampolineOffset());
276 }
277 
GetQuickResolutionTrampolineOffset() const278 uint32_t OatHeader::GetQuickResolutionTrampolineOffset() const {
279   DCHECK(IsValid());
280   CHECK_GE(quick_resolution_trampoline_offset_, quick_imt_conflict_trampoline_offset_);
281   return quick_resolution_trampoline_offset_;
282 }
283 
SetQuickResolutionTrampolineOffset(uint32_t offset)284 void OatHeader::SetQuickResolutionTrampolineOffset(uint32_t offset) {
285   CHECK(offset == 0 || offset >= quick_imt_conflict_trampoline_offset_);
286   DCHECK(IsValid());
287   DCHECK_EQ(quick_resolution_trampoline_offset_, 0U) << offset;
288 
289   quick_resolution_trampoline_offset_ = offset;
290 }
291 
GetQuickToInterpreterBridge() const292 const void* OatHeader::GetQuickToInterpreterBridge() const {
293   return GetTrampoline(*this, GetQuickToInterpreterBridgeOffset());
294 }
295 
GetQuickToInterpreterBridgeOffset() const296 uint32_t OatHeader::GetQuickToInterpreterBridgeOffset() const {
297   DCHECK(IsValid());
298   CHECK_GE(quick_to_interpreter_bridge_offset_, quick_resolution_trampoline_offset_);
299   return quick_to_interpreter_bridge_offset_;
300 }
301 
SetQuickToInterpreterBridgeOffset(uint32_t offset)302 void OatHeader::SetQuickToInterpreterBridgeOffset(uint32_t offset) {
303   CHECK(offset == 0 || offset >= quick_resolution_trampoline_offset_);
304   DCHECK(IsValid());
305   DCHECK_EQ(quick_to_interpreter_bridge_offset_, 0U) << offset;
306 
307   quick_to_interpreter_bridge_offset_ = offset;
308 }
309 
GetNterpTrampoline() const310 const void* OatHeader::GetNterpTrampoline() const {
311   return GetTrampoline(*this, GetNterpTrampolineOffset());
312 }
313 
GetNterpTrampolineOffset() const314 uint32_t OatHeader::GetNterpTrampolineOffset() const {
315   DCHECK(IsValid());
316   CHECK_GE(nterp_trampoline_offset_, quick_to_interpreter_bridge_offset_);
317   return nterp_trampoline_offset_;
318 }
319 
SetNterpTrampolineOffset(uint32_t offset)320 void OatHeader::SetNterpTrampolineOffset(uint32_t offset) {
321   CHECK(offset == 0 || offset >= quick_to_interpreter_bridge_offset_);
322   DCHECK(IsValid());
323   DCHECK_EQ(nterp_trampoline_offset_, 0U) << offset;
324 
325   nterp_trampoline_offset_ = offset;
326 }
327 
GetKeyValueStoreSize() const328 uint32_t OatHeader::GetKeyValueStoreSize() const {
329   CHECK(IsValid());
330   return key_value_store_size_;
331 }
332 
GetKeyValueStore() const333 const uint8_t* OatHeader::GetKeyValueStore() const {
334   CHECK(IsValid());
335   return key_value_store_;
336 }
337 
GetStoreValueByKey(const char * key) const338 const char* OatHeader::GetStoreValueByKey(const char* key) const {
339   std::string_view key_view(key);
340   const char* ptr = reinterpret_cast<const char*>(&key_value_store_);
341   const char* end = ptr + key_value_store_size_;
342 
343   while (ptr < end) {
344     // Scan for a closing zero.
345     const char* str_end = reinterpret_cast<const char*>(memchr(ptr, 0, end - ptr));
346     if (UNLIKELY(str_end == nullptr)) {
347       LOG(WARNING) << "OatHeader: Unterminated key in key value store.";
348       return nullptr;
349     }
350     const char* value_start = str_end + 1;
351     const char* value_end =
352         reinterpret_cast<const char*>(memchr(value_start, 0, end - value_start));
353     if (UNLIKELY(value_end == nullptr)) {
354       LOG(WARNING) << "OatHeader: Unterminated value in key value store.";
355       return nullptr;
356     }
357     if (key_view == std::string_view(ptr, str_end - ptr)) {
358       // Same as key.
359       return value_start;
360     }
361     // Different from key. Advance over the value.
362     ptr = value_end + 1;
363   }
364   // Not found.
365   return nullptr;
366 }
367 
GetStoreKeyValuePairByIndex(size_t index,const char ** key,const char ** value) const368 bool OatHeader::GetStoreKeyValuePairByIndex(size_t index,
369                                             const char** key,
370                                             const char** value) const {
371   const char* ptr = reinterpret_cast<const char*>(&key_value_store_);
372   const char* end = ptr + key_value_store_size_;
373   size_t counter = index;
374 
375   while (ptr < end) {
376     // Scan for a closing zero.
377     const char* str_end = reinterpret_cast<const char*>(memchr(ptr, 0, end - ptr));
378     if (UNLIKELY(str_end == nullptr)) {
379       LOG(WARNING) << "OatHeader: Unterminated key in key value store.";
380       return false;
381     }
382     const char* value_start = str_end + 1;
383     const char* value_end =
384         reinterpret_cast<const char*>(memchr(value_start, 0, end - value_start));
385     if (UNLIKELY(value_end == nullptr)) {
386       LOG(WARNING) << "OatHeader: Unterminated value in key value store.";
387       return false;
388     }
389     if (counter == 0) {
390       *key = ptr;
391       *value = value_start;
392       return true;
393     } else {
394       --counter;
395     }
396     // Advance over the value.
397     ptr = value_end + 1;
398   }
399   // Not found.
400   return false;
401 }
402 
GetHeaderSize() const403 size_t OatHeader::GetHeaderSize() const {
404   return sizeof(OatHeader) + key_value_store_size_;
405 }
406 
IsDebuggable() const407 bool OatHeader::IsDebuggable() const {
408   return IsKeyEnabled(OatHeader::kDebuggableKey);
409 }
410 
IsConcurrentCopying() const411 bool OatHeader::IsConcurrentCopying() const {
412   return IsKeyEnabled(OatHeader::kConcurrentCopying);
413 }
414 
IsNativeDebuggable() const415 bool OatHeader::IsNativeDebuggable() const {
416   return IsKeyEnabled(OatHeader::kNativeDebuggableKey);
417 }
418 
RequiresImage() const419 bool OatHeader::RequiresImage() const {
420   return IsKeyEnabled(OatHeader::kRequiresImage);
421 }
422 
GetCompilerFilter() const423 CompilerFilter::Filter OatHeader::GetCompilerFilter() const {
424   CompilerFilter::Filter filter;
425   const char* key_value = GetStoreValueByKey(kCompilerFilter);
426   CHECK(key_value != nullptr) << "compiler-filter not found in oat header";
427   CHECK(CompilerFilter::ParseCompilerFilter(key_value, &filter))
428       << "Invalid compiler-filter in oat header: " << key_value;
429   return filter;
430 }
431 
KeyHasValue(const char * key,const char * value,size_t value_size) const432 bool OatHeader::KeyHasValue(const char* key, const char* value, size_t value_size) const {
433   const char* key_value = GetStoreValueByKey(key);
434   return (key_value != nullptr && strncmp(key_value, value, value_size) == 0);
435 }
436 
IsKeyEnabled(const char * key) const437 bool OatHeader::IsKeyEnabled(const char* key) const {
438   return KeyHasValue(key, kTrueValue, sizeof(kTrueValue));
439 }
440 
Flatten(const SafeMap<std::string,std::string> * key_value_store)441 void OatHeader::Flatten(const SafeMap<std::string, std::string>* key_value_store) {
442   char* data_ptr = reinterpret_cast<char*>(&key_value_store_);
443   if (key_value_store != nullptr) {
444     SafeMap<std::string, std::string>::const_iterator it = key_value_store->begin();
445     SafeMap<std::string, std::string>::const_iterator end = key_value_store->end();
446     for ( ; it != end; ++it) {
447       strlcpy(data_ptr, it->first.c_str(), it->first.length() + 1);
448       data_ptr += it->first.length() + 1;
449       strlcpy(data_ptr, it->second.c_str(), it->second.length() + 1);
450       data_ptr += it->second.length() + 1;
451     }
452   }
453   key_value_store_size_ = data_ptr - reinterpret_cast<char*>(&key_value_store_);
454 }
455 
456 }  // namespace art
457