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