blob: 6112fbb5c0212656682b7f552be37f6b65e87584 [file] [log] [blame]
Alex Lighta59dd802014-07-02 16:28:08 -07001/*
2 * Copyright (C) 2014 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 "elf_patcher.h"
18
19#include <vector>
20#include <set>
21
22#include "elf_file.h"
23#include "elf_utils.h"
24#include "mirror/art_field-inl.h"
25#include "mirror/art_method-inl.h"
26#include "mirror/array-inl.h"
27#include "mirror/class-inl.h"
28#include "mirror/class_loader.h"
29#include "mirror/dex_cache-inl.h"
30#include "mirror/object-inl.h"
31#include "mirror/object_array-inl.h"
32#include "mirror/string-inl.h"
33#include "oat.h"
34#include "os.h"
35#include "utils.h"
36
37namespace art {
38
39bool ElfPatcher::Patch(const CompilerDriver* driver, ElfFile* elf_file,
40 const std::string& oat_location,
41 ImageAddressCallback cb, void* cb_data,
42 std::string* error_msg) {
43 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
44 const OatFile* oat_file = class_linker->FindOpenedOatFileFromOatLocation(oat_location);
45 if (oat_file == nullptr) {
46 CHECK(Runtime::Current()->IsCompiler());
47 oat_file = OatFile::Open(oat_location, oat_location, NULL, false, error_msg);
48 if (oat_file == nullptr) {
49 *error_msg = StringPrintf("Unable to find or open oat file at '%s': %s", oat_location.c_str(),
50 error_msg->c_str());
51 return false;
52 }
53 CHECK_EQ(class_linker->RegisterOatFile(oat_file), oat_file);
54 }
55 return ElfPatcher::Patch(driver, elf_file, oat_file,
56 reinterpret_cast<uintptr_t>(oat_file->Begin()), cb, cb_data, error_msg);
57}
58
59bool ElfPatcher::Patch(const CompilerDriver* driver, ElfFile* elf, const OatFile* oat_file,
60 uintptr_t oat_data_start, ImageAddressCallback cb, void* cb_data,
61 std::string* error_msg) {
62 Elf32_Shdr* data_sec = elf->FindSectionByName(".rodata");
63 if (data_sec == nullptr) {
64 *error_msg = "Unable to find .rodata section and oat header";
65 return false;
66 }
67 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf->Begin() + data_sec->sh_offset);
68 if (!oat_header->IsValid()) {
69 *error_msg = "Oat header was not valid";
70 return false;
71 }
72
73 ElfPatcher p(driver, elf, oat_file, oat_header, oat_data_start, cb, cb_data, error_msg);
74 return p.PatchElf();
75}
76
77mirror::ArtMethod* ElfPatcher::GetTargetMethod(const CompilerDriver::CallPatchInformation* patch) {
78 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
79 StackHandleScope<1> hs(Thread::Current());
80 Handle<mirror::DexCache> dex_cache(
81 hs.NewHandle(class_linker->FindDexCache(*patch->GetTargetDexFile())));
82 mirror::ArtMethod* method = class_linker->ResolveMethod(*patch->GetTargetDexFile(),
83 patch->GetTargetMethodIdx(),
84 dex_cache,
85 NullHandle<mirror::ClassLoader>(),
86 NullHandle<mirror::ArtMethod>(),
87 patch->GetTargetInvokeType());
88 CHECK(method != NULL)
89 << patch->GetTargetDexFile()->GetLocation() << " " << patch->GetTargetMethodIdx();
90 CHECK(!method->IsRuntimeMethod())
91 << patch->GetTargetDexFile()->GetLocation() << " " << patch->GetTargetMethodIdx();
92 CHECK(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx()) == method)
93 << patch->GetTargetDexFile()->GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
94 << PrettyMethod(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx())) << " "
95 << PrettyMethod(method);
96 return method;
97}
98
99mirror::Class* ElfPatcher::GetTargetType(const CompilerDriver::TypePatchInformation* patch) {
100 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
101 StackHandleScope<2> hs(Thread::Current());
102 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(patch->GetDexFile())));
103 mirror::Class* klass = class_linker->ResolveType(patch->GetDexFile(), patch->GetTargetTypeIdx(),
104 dex_cache, NullHandle<mirror::ClassLoader>());
105 CHECK(klass != NULL)
106 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetTypeIdx();
107 CHECK(dex_cache->GetResolvedTypes()->Get(patch->GetTargetTypeIdx()) == klass)
108 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
109 << PrettyClass(dex_cache->GetResolvedTypes()->Get(patch->GetTargetTypeIdx())) << " "
110 << PrettyClass(klass);
111 return klass;
112}
113
114void ElfPatcher::AddPatch(uintptr_t p) {
115 if (write_patches_ && patches_set_.find(p) == patches_set_.end()) {
116 patches_set_.insert(p);
117 patches_.push_back(p);
118 }
119}
120
121uint32_t* ElfPatcher::GetPatchLocation(uintptr_t patch_ptr) {
122 CHECK_GE(patch_ptr, reinterpret_cast<uintptr_t>(oat_file_->Begin()));
123 uintptr_t off = patch_ptr - reinterpret_cast<uintptr_t>(oat_file_->Begin());
124 uintptr_t ret = reinterpret_cast<uintptr_t>(oat_header_) + off;
125
126 CHECK_GE(ret, reinterpret_cast<uintptr_t>(elf_file_->Begin()));
127 CHECK_LT(ret, reinterpret_cast<uintptr_t>(elf_file_->End()));
128 return reinterpret_cast<uint32_t*>(ret);
129}
130
131void ElfPatcher::SetPatchLocation(const CompilerDriver::PatchInformation* patch, uint32_t value) {
132 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
133 const void* quick_oat_code = class_linker->GetQuickOatCodeFor(patch->GetDexFile(),
134 patch->GetReferrerClassDefIdx(),
135 patch->GetReferrerMethodIdx());
136 // TODO: make this Thumb2 specific
137 uint8_t* base = reinterpret_cast<uint8_t*>(reinterpret_cast<uintptr_t>(quick_oat_code) & ~0x1);
138 uintptr_t patch_ptr = reinterpret_cast<uintptr_t>(base + patch->GetLiteralOffset());
139 uint32_t* patch_location = GetPatchLocation(patch_ptr);
140 if (kIsDebugBuild) {
141 if (patch->IsCall()) {
142 const CompilerDriver::CallPatchInformation* cpatch = patch->AsCall();
143 const DexFile::MethodId& id =
144 cpatch->GetTargetDexFile()->GetMethodId(cpatch->GetTargetMethodIdx());
145 uint32_t expected = reinterpret_cast<uintptr_t>(&id) & 0xFFFFFFFF;
146 uint32_t actual = *patch_location;
147 CHECK(actual == expected || actual == value) << std::hex
148 << "actual=" << actual
149 << "expected=" << expected
150 << "value=" << value;
151 }
152 if (patch->IsType()) {
153 const CompilerDriver::TypePatchInformation* tpatch = patch->AsType();
154 const DexFile::TypeId& id = tpatch->GetDexFile().GetTypeId(tpatch->GetTargetTypeIdx());
155 uint32_t expected = reinterpret_cast<uintptr_t>(&id) & 0xFFFFFFFF;
156 uint32_t actual = *patch_location;
157 CHECK(actual == expected || actual == value) << std::hex
158 << "actual=" << actual
159 << "expected=" << expected
160 << "value=" << value;
161 }
162 }
163 *patch_location = value;
164 oat_header_->UpdateChecksum(patch_location, sizeof(value));
165
166 if (patch->IsCall() && patch->AsCall()->IsRelative()) {
167 // We never record relative patches.
168 return;
169 }
170 uintptr_t loc = patch_ptr - (reinterpret_cast<uintptr_t>(oat_file_->Begin()) +
171 oat_header_->GetExecutableOffset());
172 CHECK_GT(patch_ptr, reinterpret_cast<uintptr_t>(oat_file_->Begin()) +
173 oat_header_->GetExecutableOffset());
174 CHECK_LT(loc, oat_file_->Size() - oat_header_->GetExecutableOffset());
175 AddPatch(loc);
176}
177
178bool ElfPatcher::PatchElf() {
179 // TODO if we are adding patches the resulting ELF file might have a
180 // potentially rather large amount of free space where patches might have been
181 // placed. We should adjust the ELF file to get rid of this excess space.
182 if (write_patches_) {
183 patches_.reserve(compiler_driver_->GetCodeToPatch().size() +
184 compiler_driver_->GetMethodsToPatch().size() +
185 compiler_driver_->GetClassesToPatch().size());
186 }
187 Thread* self = Thread::Current();
188 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
189 const char* old_cause = self->StartAssertNoThreadSuspension("ElfPatcher");
190
191 typedef std::vector<const CompilerDriver::CallPatchInformation*> CallPatches;
192 const CallPatches& code_to_patch = compiler_driver_->GetCodeToPatch();
193 for (size_t i = 0; i < code_to_patch.size(); i++) {
194 const CompilerDriver::CallPatchInformation* patch = code_to_patch[i];
195
196 mirror::ArtMethod* target = GetTargetMethod(patch);
197 uintptr_t quick_code = reinterpret_cast<uintptr_t>(class_linker->GetQuickOatCodeFor(target));
198 DCHECK_NE(quick_code, 0U) << PrettyMethod(target);
199 const OatFile* target_oat = class_linker->FindOpenedOatFileForDexFile(*patch->GetTargetDexFile());
200 // Get where the data actually starts. if target is this oat_file_ it is oat_data_start_,
201 // otherwise it is wherever target_oat is loaded.
202 uintptr_t oat_data_addr = GetBaseAddressFor(target_oat);
203 uintptr_t code_base = reinterpret_cast<uintptr_t>(target_oat->Begin());
204 uintptr_t code_offset = quick_code - code_base;
205 bool is_quick_offset = false;
206 if (quick_code == reinterpret_cast<uintptr_t>(GetQuickToInterpreterBridge())) {
207 is_quick_offset = true;
208 code_offset = oat_header_->GetQuickToInterpreterBridgeOffset();
209 } else if (quick_code ==
210 reinterpret_cast<uintptr_t>(class_linker->GetQuickGenericJniTrampoline())) {
211 CHECK(target->IsNative());
212 is_quick_offset = true;
213 code_offset = oat_header_->GetQuickGenericJniTrampolineOffset();
214 }
215 uintptr_t value;
216 if (patch->IsRelative()) {
217 // value to patch is relative to the location being patched
218 const void* quick_oat_code =
219 class_linker->GetQuickOatCodeFor(patch->GetDexFile(),
220 patch->GetReferrerClassDefIdx(),
221 patch->GetReferrerMethodIdx());
222 if (is_quick_offset) {
223 // If its a quick offset it means that we are doing a relative patch from the class linker
224 // oat_file to the elf_patcher oat_file so we need to adjust the quick oat code to be the
225 // one in the output oat_file (ie where it is actually going to be loaded).
226 quick_code = PointerToLowMemUInt32(reinterpret_cast<void*>(oat_data_addr + code_offset));
227 quick_oat_code =
228 reinterpret_cast<const void*>(reinterpret_cast<uintptr_t>(quick_oat_code) +
229 oat_data_addr - code_base);
230 }
231 uintptr_t base = reinterpret_cast<uintptr_t>(quick_oat_code);
232 uintptr_t patch_location = base + patch->GetLiteralOffset();
233 value = quick_code - patch_location + patch->RelativeOffset();
234 } else if (code_offset != 0) {
235 value = PointerToLowMemUInt32(reinterpret_cast<void*>(oat_data_addr + code_offset));
236 } else {
237 value = 0;
238 }
239 SetPatchLocation(patch, value);
240 }
241
242 const CallPatches& methods_to_patch = compiler_driver_->GetMethodsToPatch();
243 for (size_t i = 0; i < methods_to_patch.size(); i++) {
244 const CompilerDriver::CallPatchInformation* patch = methods_to_patch[i];
245 mirror::ArtMethod* target = GetTargetMethod(patch);
246 SetPatchLocation(patch, PointerToLowMemUInt32(get_image_address_(cb_data_, target)));
247 }
248
249 const std::vector<const CompilerDriver::TypePatchInformation*>& classes_to_patch =
250 compiler_driver_->GetClassesToPatch();
251 for (size_t i = 0; i < classes_to_patch.size(); i++) {
252 const CompilerDriver::TypePatchInformation* patch = classes_to_patch[i];
253 mirror::Class* target = GetTargetType(patch);
254 SetPatchLocation(patch, PointerToLowMemUInt32(get_image_address_(cb_data_, target)));
255 }
256
257 self->EndAssertNoThreadSuspension(old_cause);
258
259 if (write_patches_) {
260 return WriteOutPatchData();
261 }
262 return true;
263}
264
265bool ElfPatcher::WriteOutPatchData() {
266 Elf32_Shdr* shdr = elf_file_->FindSectionByName(".oat_patches");
267 if (shdr != nullptr) {
268 CHECK_EQ(shdr, elf_file_->FindSectionByType(SHT_OAT_PATCH))
269 << "Incorrect type for .oat_patches section";
270 CHECK_LE(patches_.size() * sizeof(uintptr_t), shdr->sh_size)
271 << "We got more patches than anticipated";
272 CHECK_LE(reinterpret_cast<uintptr_t>(elf_file_->Begin()) + shdr->sh_offset + shdr->sh_size,
273 reinterpret_cast<uintptr_t>(elf_file_->End())) << "section is too large";
274 CHECK(shdr == &elf_file_->GetSectionHeader(elf_file_->GetSectionHeaderNum() - 1) ||
275 shdr->sh_offset + shdr->sh_size <= (shdr + 1)->sh_offset)
276 << "Section overlaps onto next section";
277 // It's mmap'd so we can just memcpy.
278 memcpy(elf_file_->Begin() + shdr->sh_offset, patches_.data(),
279 patches_.size() * sizeof(uintptr_t));
280 // TODO We should fill in the newly empty space between the last patch and
281 // the start of the next section by moving the following sections down if
282 // possible.
283 shdr->sh_size = patches_.size() * sizeof(uintptr_t);
284 return true;
285 } else {
286 LOG(ERROR) << "Unable to find section header for SHT_OAT_PATCH";
287 *error_msg_ = "Unable to find section to write patch information to in ";
288 *error_msg_ += elf_file_->GetFile().GetPath();
289 return false;
290 }
291}
292
293} // namespace art