blob: 9ae755d45aaaffb5d55b4c56ac07bb1d7d94bd4b [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());
Fred Shihe7f82e22014-08-06 10:46:37 -0700102 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
103 patch->GetTargetTypeDexFile())));
104 mirror::Class* klass = class_linker->ResolveType(patch->GetTargetTypeDexFile(),
105 patch->GetTargetTypeIdx(),
Alex Lighta59dd802014-07-02 16:28:08 -0700106 dex_cache, NullHandle<mirror::ClassLoader>());
107 CHECK(klass != NULL)
Fred Shihe7f82e22014-08-06 10:46:37 -0700108 << patch->GetTargetTypeDexFile().GetLocation() << " " << patch->GetTargetTypeIdx();
Alex Lighta59dd802014-07-02 16:28:08 -0700109 CHECK(dex_cache->GetResolvedTypes()->Get(patch->GetTargetTypeIdx()) == klass)
110 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
111 << PrettyClass(dex_cache->GetResolvedTypes()->Get(patch->GetTargetTypeIdx())) << " "
112 << PrettyClass(klass);
113 return klass;
114}
115
116void ElfPatcher::AddPatch(uintptr_t p) {
117 if (write_patches_ && patches_set_.find(p) == patches_set_.end()) {
118 patches_set_.insert(p);
119 patches_.push_back(p);
120 }
121}
122
123uint32_t* ElfPatcher::GetPatchLocation(uintptr_t patch_ptr) {
124 CHECK_GE(patch_ptr, reinterpret_cast<uintptr_t>(oat_file_->Begin()));
Alex Light6e183f22014-07-18 14:57:04 -0700125 CHECK_LE(patch_ptr, reinterpret_cast<uintptr_t>(oat_file_->End()));
Alex Lighta59dd802014-07-02 16:28:08 -0700126 uintptr_t off = patch_ptr - reinterpret_cast<uintptr_t>(oat_file_->Begin());
127 uintptr_t ret = reinterpret_cast<uintptr_t>(oat_header_) + off;
128
129 CHECK_GE(ret, reinterpret_cast<uintptr_t>(elf_file_->Begin()));
130 CHECK_LT(ret, reinterpret_cast<uintptr_t>(elf_file_->End()));
131 return reinterpret_cast<uint32_t*>(ret);
132}
133
134void ElfPatcher::SetPatchLocation(const CompilerDriver::PatchInformation* patch, uint32_t value) {
135 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
136 const void* quick_oat_code = class_linker->GetQuickOatCodeFor(patch->GetDexFile(),
137 patch->GetReferrerClassDefIdx(),
138 patch->GetReferrerMethodIdx());
139 // TODO: make this Thumb2 specific
140 uint8_t* base = reinterpret_cast<uint8_t*>(reinterpret_cast<uintptr_t>(quick_oat_code) & ~0x1);
141 uintptr_t patch_ptr = reinterpret_cast<uintptr_t>(base + patch->GetLiteralOffset());
142 uint32_t* patch_location = GetPatchLocation(patch_ptr);
143 if (kIsDebugBuild) {
144 if (patch->IsCall()) {
145 const CompilerDriver::CallPatchInformation* cpatch = patch->AsCall();
146 const DexFile::MethodId& id =
147 cpatch->GetTargetDexFile()->GetMethodId(cpatch->GetTargetMethodIdx());
148 uint32_t expected = reinterpret_cast<uintptr_t>(&id) & 0xFFFFFFFF;
149 uint32_t actual = *patch_location;
Alex Light6e183f22014-07-18 14:57:04 -0700150 CHECK(actual == expected || actual == value) << "Patching call failed: " << std::hex
151 << " actual=" << actual
152 << " expected=" << expected
153 << " value=" << value;
Alex Lighta59dd802014-07-02 16:28:08 -0700154 }
155 if (patch->IsType()) {
156 const CompilerDriver::TypePatchInformation* tpatch = patch->AsType();
Fred Shihe7f82e22014-08-06 10:46:37 -0700157 const DexFile::TypeId& id = tpatch->GetTargetTypeDexFile().GetTypeId(tpatch->GetTargetTypeIdx());
Alex Lighta59dd802014-07-02 16:28:08 -0700158 uint32_t expected = reinterpret_cast<uintptr_t>(&id) & 0xFFFFFFFF;
159 uint32_t actual = *patch_location;
Alex Light6e183f22014-07-18 14:57:04 -0700160 CHECK(actual == expected || actual == value) << "Patching type failed: " << std::hex
161 << " actual=" << actual
162 << " expected=" << expected
163 << " value=" << value;
Alex Lighta59dd802014-07-02 16:28:08 -0700164 }
165 }
166 *patch_location = value;
167 oat_header_->UpdateChecksum(patch_location, sizeof(value));
168
169 if (patch->IsCall() && patch->AsCall()->IsRelative()) {
170 // We never record relative patches.
171 return;
172 }
173 uintptr_t loc = patch_ptr - (reinterpret_cast<uintptr_t>(oat_file_->Begin()) +
174 oat_header_->GetExecutableOffset());
175 CHECK_GT(patch_ptr, reinterpret_cast<uintptr_t>(oat_file_->Begin()) +
176 oat_header_->GetExecutableOffset());
177 CHECK_LT(loc, oat_file_->Size() - oat_header_->GetExecutableOffset());
178 AddPatch(loc);
179}
180
181bool ElfPatcher::PatchElf() {
182 // TODO if we are adding patches the resulting ELF file might have a
183 // potentially rather large amount of free space where patches might have been
184 // placed. We should adjust the ELF file to get rid of this excess space.
185 if (write_patches_) {
186 patches_.reserve(compiler_driver_->GetCodeToPatch().size() +
187 compiler_driver_->GetMethodsToPatch().size() +
188 compiler_driver_->GetClassesToPatch().size());
189 }
190 Thread* self = Thread::Current();
191 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
192 const char* old_cause = self->StartAssertNoThreadSuspension("ElfPatcher");
193
194 typedef std::vector<const CompilerDriver::CallPatchInformation*> CallPatches;
195 const CallPatches& code_to_patch = compiler_driver_->GetCodeToPatch();
196 for (size_t i = 0; i < code_to_patch.size(); i++) {
197 const CompilerDriver::CallPatchInformation* patch = code_to_patch[i];
198
199 mirror::ArtMethod* target = GetTargetMethod(patch);
200 uintptr_t quick_code = reinterpret_cast<uintptr_t>(class_linker->GetQuickOatCodeFor(target));
201 DCHECK_NE(quick_code, 0U) << PrettyMethod(target);
202 const OatFile* target_oat = class_linker->FindOpenedOatFileForDexFile(*patch->GetTargetDexFile());
203 // Get where the data actually starts. if target is this oat_file_ it is oat_data_start_,
204 // otherwise it is wherever target_oat is loaded.
205 uintptr_t oat_data_addr = GetBaseAddressFor(target_oat);
206 uintptr_t code_base = reinterpret_cast<uintptr_t>(target_oat->Begin());
207 uintptr_t code_offset = quick_code - code_base;
208 bool is_quick_offset = false;
209 if (quick_code == reinterpret_cast<uintptr_t>(GetQuickToInterpreterBridge())) {
210 is_quick_offset = true;
211 code_offset = oat_header_->GetQuickToInterpreterBridgeOffset();
212 } else if (quick_code ==
213 reinterpret_cast<uintptr_t>(class_linker->GetQuickGenericJniTrampoline())) {
214 CHECK(target->IsNative());
215 is_quick_offset = true;
216 code_offset = oat_header_->GetQuickGenericJniTrampolineOffset();
217 }
218 uintptr_t value;
219 if (patch->IsRelative()) {
220 // value to patch is relative to the location being patched
221 const void* quick_oat_code =
222 class_linker->GetQuickOatCodeFor(patch->GetDexFile(),
223 patch->GetReferrerClassDefIdx(),
224 patch->GetReferrerMethodIdx());
225 if (is_quick_offset) {
226 // If its a quick offset it means that we are doing a relative patch from the class linker
227 // oat_file to the elf_patcher oat_file so we need to adjust the quick oat code to be the
228 // one in the output oat_file (ie where it is actually going to be loaded).
229 quick_code = PointerToLowMemUInt32(reinterpret_cast<void*>(oat_data_addr + code_offset));
230 quick_oat_code =
231 reinterpret_cast<const void*>(reinterpret_cast<uintptr_t>(quick_oat_code) +
232 oat_data_addr - code_base);
233 }
234 uintptr_t base = reinterpret_cast<uintptr_t>(quick_oat_code);
235 uintptr_t patch_location = base + patch->GetLiteralOffset();
236 value = quick_code - patch_location + patch->RelativeOffset();
237 } else if (code_offset != 0) {
238 value = PointerToLowMemUInt32(reinterpret_cast<void*>(oat_data_addr + code_offset));
239 } else {
240 value = 0;
241 }
242 SetPatchLocation(patch, value);
243 }
244
245 const CallPatches& methods_to_patch = compiler_driver_->GetMethodsToPatch();
246 for (size_t i = 0; i < methods_to_patch.size(); i++) {
247 const CompilerDriver::CallPatchInformation* patch = methods_to_patch[i];
248 mirror::ArtMethod* target = GetTargetMethod(patch);
249 SetPatchLocation(patch, PointerToLowMemUInt32(get_image_address_(cb_data_, target)));
250 }
251
252 const std::vector<const CompilerDriver::TypePatchInformation*>& classes_to_patch =
253 compiler_driver_->GetClassesToPatch();
254 for (size_t i = 0; i < classes_to_patch.size(); i++) {
255 const CompilerDriver::TypePatchInformation* patch = classes_to_patch[i];
256 mirror::Class* target = GetTargetType(patch);
257 SetPatchLocation(patch, PointerToLowMemUInt32(get_image_address_(cb_data_, target)));
258 }
259
260 self->EndAssertNoThreadSuspension(old_cause);
261
262 if (write_patches_) {
263 return WriteOutPatchData();
264 }
265 return true;
266}
267
268bool ElfPatcher::WriteOutPatchData() {
269 Elf32_Shdr* shdr = elf_file_->FindSectionByName(".oat_patches");
270 if (shdr != nullptr) {
271 CHECK_EQ(shdr, elf_file_->FindSectionByType(SHT_OAT_PATCH))
272 << "Incorrect type for .oat_patches section";
273 CHECK_LE(patches_.size() * sizeof(uintptr_t), shdr->sh_size)
274 << "We got more patches than anticipated";
275 CHECK_LE(reinterpret_cast<uintptr_t>(elf_file_->Begin()) + shdr->sh_offset + shdr->sh_size,
276 reinterpret_cast<uintptr_t>(elf_file_->End())) << "section is too large";
277 CHECK(shdr == &elf_file_->GetSectionHeader(elf_file_->GetSectionHeaderNum() - 1) ||
278 shdr->sh_offset + shdr->sh_size <= (shdr + 1)->sh_offset)
279 << "Section overlaps onto next section";
280 // It's mmap'd so we can just memcpy.
281 memcpy(elf_file_->Begin() + shdr->sh_offset, patches_.data(),
282 patches_.size() * sizeof(uintptr_t));
283 // TODO We should fill in the newly empty space between the last patch and
284 // the start of the next section by moving the following sections down if
285 // possible.
286 shdr->sh_size = patches_.size() * sizeof(uintptr_t);
287 return true;
288 } else {
289 LOG(ERROR) << "Unable to find section header for SHT_OAT_PATCH";
290 *error_msg_ = "Unable to find section to write patch information to in ";
291 *error_msg_ += elf_file_->GetFile().GetPath();
292 return false;
293 }
294}
295
296} // namespace art