blob: b5622b5cadf59c2f7f4d7758d4057df1f0b0ec5a [file] [log] [blame]
Alex Light9c20a142016-08-23 15:05:12 -07001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "transform.h"
33
34#include "class_linker.h"
35#include "dex_file.h"
36#include "gc_root-inl.h"
37#include "globals.h"
38#include "jni_env_ext-inl.h"
39#include "jvmti.h"
40#include "linear_alloc.h"
41#include "mem_map.h"
42#include "mirror/array.h"
43#include "mirror/class-inl.h"
44#include "mirror/class_loader-inl.h"
45#include "mirror/string-inl.h"
46#include "scoped_thread_state_change.h"
47#include "thread_list.h"
48#include "transform.h"
49#include "utf.h"
50#include "utils/dex_cache_arrays_layout-inl.h"
51
52namespace openjdkjvmti {
53
54static bool ReadChecksum(jint data_len, const unsigned char* dex, /*out*/uint32_t* res) {
55 if (data_len < static_cast<jint>(sizeof(art::DexFile::Header))) {
56 return false;
57 }
58 *res = reinterpret_cast<const art::DexFile::Header*>(dex)->checksum_;
59 return true;
60}
61
62static std::unique_ptr<art::MemMap> MoveDataToMemMap(const std::string& original_location,
63 jint data_len,
64 unsigned char* dex_data) {
65 std::string error_msg;
66 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
67 art::StringPrintf("%s-transformed", original_location.c_str()).c_str(),
68 nullptr,
69 data_len,
70 PROT_READ|PROT_WRITE,
71 /*low_4gb*/false,
72 /*reuse*/false,
73 &error_msg));
74 if (map == nullptr) {
75 return map;
76 }
77 memcpy(map->Begin(), dex_data, data_len);
78 map->Protect(PROT_READ);
79 return map;
80}
81
82static void InvalidateExistingMethods(art::Thread* self,
83 art::Handle<art::mirror::Class> klass,
84 art::Handle<art::mirror::DexCache> cache,
85 const art::DexFile* dex_file)
86 REQUIRES_SHARED(art::Locks::mutator_lock_) {
87 // Create new DexCache with new DexFile.
88 // reset dex_class_def_idx_
89 // for each method reset entry_point_from_quick_compiled_code_ to bridge
90 // for each method reset dex_code_item_offset_
91 // for each method reset dex_method_index_
92 // for each method set dex_cache_resolved_methods_ to new DexCache
93 // for each method set dex_cache_resolved_types_ to new DexCache
94 auto* runtime = art::Runtime::Current();
95 art::ClassLinker* linker = runtime->GetClassLinker();
96 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
97 std::string descriptor_storage;
98 const char* descriptor = klass->GetDescriptor(&descriptor_storage);
99 // Get the new class def
100 const art::DexFile::ClassDef* class_def = art::OatFile::OatDexFile::FindClassDef(
101 *dex_file, descriptor, art::ComputeModifiedUtf8Hash(descriptor));
102 CHECK(class_def != nullptr);
103 const art::DexFile::TypeId& declaring_class_id = dex_file->GetTypeId(class_def->class_idx_);
104 art::StackHandleScope<6> hs(self);
105 const art::DexFile& old_dex_file = klass->GetDexFile();
106 for (art::ArtMethod& method : klass->GetMethods(image_pointer_size)) {
107 // Find the code_item for the method then find the dex_method_index and dex_code_item_offset to
108 // set.
109 const art::DexFile::StringId* new_name_id = dex_file->FindStringId(method.GetName());
110 uint16_t method_return_idx =
111 dex_file->GetIndexForTypeId(*dex_file->FindTypeId(method.GetReturnTypeDescriptor()));
112 const auto* old_type_list = method.GetParameterTypeList();
113 std::vector<uint16_t> new_type_list;
114 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
115 new_type_list.push_back(
116 dex_file->GetIndexForTypeId(
117 *dex_file->FindTypeId(
118 old_dex_file.GetTypeDescriptor(
119 old_dex_file.GetTypeId(
120 old_type_list->GetTypeItem(i).type_idx_)))));
121 }
122 const art::DexFile::ProtoId* proto_id = dex_file->FindProtoId(method_return_idx,
123 new_type_list);
124 CHECK(proto_id != nullptr || old_type_list == nullptr);
125 const art::DexFile::MethodId* method_id = dex_file->FindMethodId(declaring_class_id,
126 *new_name_id,
127 *proto_id);
128 CHECK(method_id != nullptr);
129 uint32_t dex_method_idx = dex_file->GetIndexForMethodId(*method_id);
130 method.SetDexMethodIndex(dex_method_idx);
131 linker->SetEntryPointsToInterpreter(&method);
132 method.SetCodeItemOffset(dex_file->FindCodeItemOffset(*class_def, dex_method_idx));
133 method.SetDexCacheResolvedMethods(cache->GetResolvedMethods(), image_pointer_size);
134 method.SetDexCacheResolvedTypes(cache->GetResolvedTypes(), image_pointer_size);
135 }
136
137 // Update the class fields.
138 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
139 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
140 klass->SetDexCache(cache.Get());
141 klass->SetDexCacheStrings(cache->GetStrings());
142 klass->SetDexClassDefIndex(dex_file->GetIndexForClassDef(*class_def));
143 klass->SetDexTypeIndex(dex_file->GetIndexForTypeId(*dex_file->FindTypeId(descriptor)));
144}
145
146// Adds the dex file.
147static art::mirror::LongArray* InsertDexFileIntoArray(art::Thread* self,
148 const art::DexFile* dex,
149 art::Handle<art::mirror::LongArray>& orig)
150 REQUIRES_SHARED(art::Locks::mutator_lock_) {
151 art::StackHandleScope<1> hs(self);
152 CHECK_GE(orig->GetLength(), 1);
153 art::Handle<art::mirror::LongArray> ret(
154 hs.NewHandle(art::mirror::LongArray::Alloc(self, orig->GetLength() + 1)));
155 CHECK(ret.Get() != nullptr);
156 // Copy the oat-dex.
157 // TODO Should I clear the oatdex element?
158 ret->SetWithoutChecks<false>(0, orig->GetWithoutChecks(0));
159 ret->SetWithoutChecks<false>(1, static_cast<int64_t>(reinterpret_cast<intptr_t>(dex)));
160 ret->Memcpy(2, orig.Get(), 1, orig->GetLength() - 1);
161 return ret.Get();
162}
163
164// TODO Handle all types of class loaders.
165static bool FindDalvikSystemDexFileAndLoaderForClass(
166 art::Handle<art::mirror::Class> klass,
167 /*out*/art::mirror::Object** dex_file,
168 /*out*/art::mirror::ClassLoader** loader)
169 REQUIRES_SHARED(art::Locks::mutator_lock_) {
170 const char* dex_path_list_element_array_name = "[Ldalvik/system/DexPathList$Element;";
171 const char* dex_path_list_element_name = "Ldalvik/system/DexPathList$Element;";
172 const char* dex_file_name = "Ldalvik/system/DexFile;";
173 const char* dex_path_list_name = "Ldalvik/system/DexPathList;";
174 const char* dex_class_loader_name = "Ldalvik/system/BaseDexClassLoader;";
175
176 art::Thread* self = art::Thread::Current();
177 CHECK(!self->IsExceptionPending());
178 art::StackHandleScope<11> hs(self);
179 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
180
181 art::Handle<art::mirror::ClassLoader> null_loader(hs.NewHandle<art::mirror::ClassLoader>(
182 nullptr));
183 art::Handle<art::mirror::Class> base_dex_loader_class(hs.NewHandle(class_linker->FindClass(
184 self, dex_class_loader_name, null_loader)));
185
186 art::ArtField* path_list_field = base_dex_loader_class->FindDeclaredInstanceField(
187 "pathList", dex_path_list_name);
188 CHECK(path_list_field != nullptr);
189
190 art::ArtField* dex_path_list_element_field =
191 class_linker->FindClass(self, dex_path_list_name, null_loader)
192 ->FindDeclaredInstanceField("dexElements", dex_path_list_element_array_name);
193 CHECK(dex_path_list_element_field != nullptr);
194
195 art::ArtField* element_dex_file_field =
196 class_linker->FindClass(self, dex_path_list_element_name, null_loader)
197 ->FindDeclaredInstanceField("dexFile", dex_file_name);
198 CHECK(element_dex_file_field != nullptr);
199
200 art::Handle<art::mirror::ClassLoader> h_class_loader(hs.NewHandle(klass->GetClassLoader()));
201 art::Handle<art::mirror::Class> loader_class(hs.NewHandle(h_class_loader->GetClass()));
202 // Check if loader is a BaseDexClassLoader
203 if (!loader_class->IsSubClass(base_dex_loader_class.Get())) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700204 LOG(ERROR) << "The classloader is not a BaseDexClassLoader which is currently the only "
205 << "supported class loader type!";
Alex Light9c20a142016-08-23 15:05:12 -0700206 return false;
207 }
208 art::Handle<art::mirror::Object> path_list(
209 hs.NewHandle(path_list_field->GetObject(h_class_loader.Get())));
210 CHECK(path_list.Get() != nullptr);
211 CHECK(!self->IsExceptionPending());
212 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> dex_elements_list(
213 hs.NewHandle(art::down_cast<art::mirror::ObjectArray<art::mirror::Object>*>(
214 dex_path_list_element_field->GetObject(path_list.Get()))));
215 CHECK(!self->IsExceptionPending());
216 CHECK(dex_elements_list.Get() != nullptr);
217 size_t num_elements = dex_elements_list->GetLength();
218 art::MutableHandle<art::mirror::Object> current_element(
219 hs.NewHandle<art::mirror::Object>(nullptr));
220 art::MutableHandle<art::mirror::Object> first_dex_file(
221 hs.NewHandle<art::mirror::Object>(nullptr));
222 for (size_t i = 0; i < num_elements; i++) {
223 current_element.Assign(dex_elements_list->Get(i));
224 CHECK(current_element.Get() != nullptr);
225 CHECK(!self->IsExceptionPending());
226 CHECK(dex_elements_list.Get() != nullptr);
227 CHECK_EQ(current_element->GetClass(), class_linker->FindClass(self,
228 dex_path_list_element_name,
229 null_loader));
230 // TODO It would be cleaner to put the art::DexFile into the dalvik.system.DexFile the class
231 // comes from but it is more annoying because we would need to find this class. It is not
232 // necessary for proper function since we just need to be in front of the classes old dex file
233 // in the path.
234 first_dex_file.Assign(element_dex_file_field->GetObject(current_element.Get()));
235 if (first_dex_file.Get() != nullptr) {
236 *dex_file = first_dex_file.Get();
237 *loader = h_class_loader.Get();
238 return true;
239 }
240 }
241 return false;
242}
243
244// Gets the data surrounding the given class.
245jvmtiError GetTransformationData(ArtJvmTiEnv* env,
246 jclass klass,
247 /*out*/std::string* location,
248 /*out*/JNIEnv** jni_env_ptr,
249 /*out*/jobject* loader,
250 /*out*/std::string* name,
251 /*out*/jobject* protection_domain,
252 /*out*/jint* data_len,
253 /*out*/unsigned char** dex_data) {
254 jint ret = env->art_vm->GetEnv(reinterpret_cast<void**>(jni_env_ptr), JNI_VERSION_1_1);
255 if (ret != JNI_OK) {
256 // TODO Different error might be better?
257 return ERR(INTERNAL);
258 }
259 JNIEnv* jni_env = *jni_env_ptr;
260 art::ScopedObjectAccess soa(jni_env);
261 art::StackHandleScope<3> hs(art::Thread::Current());
262 art::Handle<art::mirror::Class> hs_klass(hs.NewHandle(soa.Decode<art::mirror::Class*>(klass)));
263 *loader = soa.AddLocalReference<jobject>(hs_klass->GetClassLoader());
264 *name = art::mirror::Class::ComputeName(hs_klass)->ToModifiedUtf8();
265 // TODO is this always null?
266 *protection_domain = nullptr;
267 const art::DexFile& dex = hs_klass->GetDexFile();
268 *location = dex.GetLocation();
269 *data_len = static_cast<jint>(dex.Size());
270 // TODO We should maybe change env->Allocate to allow us to mprotect this memory and stop writes.
271 jvmtiError alloc_error = env->Allocate(*data_len, dex_data);
272 if (alloc_error != OK) {
273 return alloc_error;
274 }
275 // Copy the data into a temporary buffer.
276 memcpy(reinterpret_cast<void*>(*dex_data),
277 reinterpret_cast<const void*>(dex.Begin()),
278 *data_len);
279 return OK;
280}
281
282// Install the new dex file.
283// TODO do error checks for bad state (method in a stack, changes to number of methods/fields/etc).
284jvmtiError MoveTransformedFileIntoRuntime(jclass jklass,
285 std::string original_location,
286 jint data_len,
287 unsigned char* dex_data) {
288 const char* dex_file_name = "Ldalvik/system/DexFile;";
289 art::Thread* self = art::Thread::Current();
290 art::Runtime* runtime = art::Runtime::Current();
291 art::ThreadList* threads = runtime->GetThreadList();
292 art::ClassLinker* class_linker = runtime->GetClassLinker();
293 uint32_t checksum = 0;
294 if (!ReadChecksum(data_len, dex_data, &checksum)) {
295 return ERR(INVALID_CLASS_FORMAT);
296 }
297
298 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_location, data_len, dex_data));
299 if (map.get() == nullptr) {
300 return ERR(INTERNAL);
301 }
302 std::string error_msg;
303 // Load the new dex_data in memory (mmap it, etc)
304 std::unique_ptr<const art::DexFile> new_dex_file = art::DexFile::Open(map->GetName(),
305 checksum,
306 std::move(map),
307 /*verify*/ true,
308 /*verify_checksum*/ true,
309 &error_msg);
310 CHECK(new_dex_file.get() != nullptr) << "Unable to load dex file! " << error_msg;
311
312 // Get mutator lock. We need the lifetimes of these variables (hs, the classes, etc.) to be longer
313 // then current lock (since there isn't upgrading of the lock) so we don't use soa.
314 art::ThreadState old_state = self->TransitionFromSuspendedToRunnable();
315 // This scope is needed to make sure that the HandleScope dies with mutator_lock_ since we need to
316 // upgrade the mutator_lock during the execution.
317 {
318 art::StackHandleScope<11> hs(self);
319 art::Handle<art::mirror::ClassLoader> null_loader(
320 hs.NewHandle<art::mirror::ClassLoader>(nullptr));
321 CHECK(null_loader.Get() == nullptr);
322 art::ArtField* dex_file_cookie_field = class_linker->
323 FindClass(self, dex_file_name, null_loader)->
324 FindDeclaredInstanceField("mCookie", "Ljava/lang/Object;");
325 art::ArtField* dex_file_internal_cookie_field =
326 class_linker->FindClass(self, dex_file_name, null_loader)
327 ->FindDeclaredInstanceField("mInternalCookie", "Ljava/lang/Object;");
328 CHECK(dex_file_cookie_field != nullptr);
329 art::Handle<art::mirror::Class> klass(
330 hs.NewHandle(art::down_cast<art::mirror::Class*>(self->DecodeJObject(jklass))));
331 art::mirror::Object* dex_file_ptr = nullptr;
332 art::mirror::ClassLoader* class_loader_ptr = nullptr;
333 // Find dalvik.system.DexFile that represents the dex file we are changing.
334 if (!FindDalvikSystemDexFileAndLoaderForClass(klass, &dex_file_ptr, &class_loader_ptr)) {
335 self->TransitionFromRunnableToSuspended(old_state);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700336 LOG(ERROR) << "Could not find DexFile.";
Alex Light9c20a142016-08-23 15:05:12 -0700337 return ERR(INTERNAL);
338 }
339 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(dex_file_ptr));
340 art::Handle<art::mirror::ClassLoader> class_loader(hs.NewHandle(class_loader_ptr));
341 art::Handle<art::mirror::LongArray> art_dex_array(
342 hs.NewHandle<art::mirror::LongArray>(
343 dex_file_cookie_field->GetObject(dex_file_obj.Get())->AsLongArray()));
344 art::Handle<art::mirror::LongArray> new_art_dex_array(
345 hs.NewHandle<art::mirror::LongArray>(
346 InsertDexFileIntoArray(self, new_dex_file.get(), art_dex_array)));
347 art::Handle<art::mirror::DexCache> cache(
348 hs.NewHandle(class_linker->RegisterDexFile(*new_dex_file.get(), class_loader.Get())));
349 self->TransitionFromRunnableToSuspended(old_state);
350
351 threads->SuspendAll("moving dex file into runtime", /*long_suspend*/true);
352 // Change the mCookie field. Old value will be GC'd as normal.
353 dex_file_cookie_field->SetObject<false>(dex_file_obj.Get(), new_art_dex_array.Get());
354 dex_file_internal_cookie_field->SetObject<false>(dex_file_obj.Get(), new_art_dex_array.Get());
355 // Invalidate existing methods.
356 InvalidateExistingMethods(self, klass, cache, new_dex_file.release());
357 }
358 threads->ResumeAll();
359 return OK;
360}
361
362} // namespace openjdkjvmti