blob: d510ae5dd4a7f510f4c5a8ec89ae757eddd54d24 [file] [log] [blame]
Andreas Gampee492ae32016-10-28 19:34:57 -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 "ti_class.h"
33
Alex Light440b5d92017-01-24 15:32:25 -080034#include "android-base/stringprintf.h"
35
Igor Murashkin5573c372017-11-16 13:34:30 -080036#include <mutex>
Andreas Gampee6377462017-01-20 17:37:50 -080037#include <unordered_set>
38
Andreas Gampee492ae32016-10-28 19:34:57 -070039#include "art_jvmti.h"
Vladimir Markoe1993c72017-06-14 17:01:38 +010040#include "base/array_ref.h"
Andreas Gampee6377462017-01-20 17:37:50 -080041#include "base/macros.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080042#include "class_linker.h"
Steven Morelande431e272017-07-18 16:53:49 -070043#include "class_table-inl.h"
Alex Light440b5d92017-01-24 15:32:25 -080044#include "common_throws.h"
David Sehr013fd802018-01-11 22:55:24 -080045#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080046#include "dex/dex_file_annotations.h"
47#include "dex/dex_file_loader.h"
Andreas Gampee6377462017-01-20 17:37:50 -080048#include "events-inl.h"
Alex Light40528472017-03-28 09:07:36 -070049#include "fixed_up_dex_file.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070050#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070051#include "gc/heap.h"
Andreas Gampe691051b2017-02-09 09:15:24 -080052#include "gc_root.h"
Andreas Gampee6377462017-01-20 17:37:50 -080053#include "handle.h"
54#include "jni_env_ext-inl.h"
Andreas Gampeac587272017-01-05 15:21:34 -080055#include "jni_internal.h"
Alex Light440b5d92017-01-24 15:32:25 -080056#include "mirror/array-inl.h"
57#include "mirror/class-inl.h"
58#include "mirror/class_ext.h"
Andreas Gampea67354b2017-02-10 16:18:30 -080059#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080060#include "mirror/object-refvisitor-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070061#include "mirror/object_array-inl.h"
62#include "mirror/object_reference.h"
Andreas Gampe52784ac2017-02-13 18:10:09 -080063#include "mirror/reference.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070064#include "nativehelper/scoped_local_ref.h"
Alex Light6a656312017-03-29 17:18:00 -070065#include "primitive.h"
66#include "reflection.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080067#include "runtime.h"
Andreas Gampee6377462017-01-20 17:37:50 -080068#include "runtime_callbacks.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070069#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070070#include "thread-current-inl.h"
Andreas Gampee6377462017-01-20 17:37:50 -080071#include "thread_list.h"
Alex Lightc7588752018-02-20 11:15:54 -080072#include "ti_class_loader-inl.h"
Alex Lightd8ce4e72017-02-27 10:52:29 -080073#include "ti_phase.h"
Alex Light440b5d92017-01-24 15:32:25 -080074#include "ti_redefine.h"
75#include "utils.h"
Andreas Gampea1d2f952017-04-20 22:53:58 -070076#include "well_known_classes.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070077
78namespace openjdkjvmti {
79
Alex Light440b5d92017-01-24 15:32:25 -080080using android::base::StringPrintf;
81
82static std::unique_ptr<const art::DexFile> MakeSingleDexFile(art::Thread* self,
83 const char* descriptor,
84 const std::string& orig_location,
85 jint final_len,
86 const unsigned char* final_dex_data)
87 REQUIRES_SHARED(art::Locks::mutator_lock_) {
88 // Make the mmap
89 std::string error_msg;
Vladimir Markoe1993c72017-06-14 17:01:38 +010090 art::ArrayRef<const unsigned char> final_data(final_dex_data, final_len);
Alex Light440b5d92017-01-24 15:32:25 -080091 std::unique_ptr<art::MemMap> map(Redefiner::MoveDataToMemMap(orig_location,
Alex Lightb7354d52017-03-30 15:17:01 -070092 final_data,
Alex Light440b5d92017-01-24 15:32:25 -080093 &error_msg));
94 if (map.get() == nullptr) {
95 LOG(WARNING) << "Unable to allocate mmap for redefined dex file! Error was: " << error_msg;
96 self->ThrowOutOfMemoryError(StringPrintf(
97 "Unable to allocate dex file for transformation of %s", descriptor).c_str());
98 return nullptr;
99 }
100
101 // Make a dex-file
102 if (map->Size() < sizeof(art::DexFile::Header)) {
103 LOG(WARNING) << "Could not read dex file header because dex_data was too short";
104 art::ThrowClassFormatError(nullptr,
105 "Unable to read transformed dex file of %s",
106 descriptor);
107 return nullptr;
108 }
109 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
Andreas Gampef45d61c2017-06-07 10:29:33 -0700110 std::string map_name = map->GetName();
David Sehr013fd802018-01-11 22:55:24 -0800111 const art::ArtDexFileLoader dex_file_loader;
112 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(map_name,
113 checksum,
114 std::move(map),
115 /*verify*/true,
116 /*verify_checksum*/true,
117 &error_msg));
Alex Light440b5d92017-01-24 15:32:25 -0800118 if (dex_file.get() == nullptr) {
119 LOG(WARNING) << "Unable to load modified dex file for " << descriptor << ": " << error_msg;
120 art::ThrowClassFormatError(nullptr,
121 "Unable to read transformed dex file of %s because %s",
122 descriptor,
123 error_msg.c_str());
124 return nullptr;
125 }
126 if (dex_file->NumClassDefs() != 1) {
127 LOG(WARNING) << "Dex file contains more than 1 class_def. Ignoring.";
128 // TODO Throw some other sort of error here maybe?
129 art::ThrowClassFormatError(
130 nullptr,
131 "Unable to use transformed dex file of %s because it contained too many classes",
132 descriptor);
133 return nullptr;
134 }
135 return dex_file;
136}
137
Alex Light28b6e7e2017-05-22 16:05:59 -0700138// A deleter that acts like the jvmtiEnv->Deallocate so that asan does not get tripped up.
139// TODO We should everything use the actual jvmtiEnv->Allocate/Deallocate functions once we can
140// figure out which env to use.
141template <typename T>
142class FakeJvmtiDeleter {
143 public:
144 FakeJvmtiDeleter() {}
145
146 FakeJvmtiDeleter(FakeJvmtiDeleter&) = default;
147 FakeJvmtiDeleter(FakeJvmtiDeleter&&) = default;
148 FakeJvmtiDeleter& operator=(const FakeJvmtiDeleter&) = default;
149
150 template <typename U> void operator()(const U* ptr) const {
151 if (ptr != nullptr) {
152 free(const_cast<U*>(ptr));
153 }
154 }
155};
156
Andreas Gampee6377462017-01-20 17:37:50 -0800157struct ClassCallback : public art::ClassLoadCallback {
Alex Light440b5d92017-01-24 15:32:25 -0800158 void ClassPreDefine(const char* descriptor,
159 art::Handle<art::mirror::Class> klass,
160 art::Handle<art::mirror::ClassLoader> class_loader,
161 const art::DexFile& initial_dex_file,
162 const art::DexFile::ClassDef& initial_class_def ATTRIBUTE_UNUSED,
163 /*out*/art::DexFile const** final_dex_file,
164 /*out*/art::DexFile::ClassDef const** final_class_def)
165 OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
166 bool is_enabled =
167 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookRetransformable) ||
168 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookNonRetransformable);
169 if (!is_enabled) {
170 return;
171 }
172 if (descriptor[0] != 'L') {
173 // It is a primitive or array. Just return
174 return;
175 }
Alex Lightd8ce4e72017-02-27 10:52:29 -0800176 jvmtiPhase phase = PhaseUtil::GetPhaseUnchecked();
177 if (UNLIKELY(phase != JVMTI_PHASE_START && phase != JVMTI_PHASE_LIVE)) {
178 // We want to wait until we are at least in the START phase so that all WellKnownClasses and
179 // mirror classes have been initialized and loaded. The runtime relies on these classes having
180 // specific fields and methods present. Since PreDefine hooks don't need to abide by this
181 // restriction we will simply not send the event for these classes.
182 LOG(WARNING) << "Ignoring load of class <" << descriptor << "> as it is being loaded during "
183 << "runtime initialization.";
184 return;
185 }
186
Alex Light440b5d92017-01-24 15:32:25 -0800187 art::Thread* self = art::Thread::Current();
Alex Light64e4c142018-01-30 13:46:37 -0800188 ArtClassDefinition def;
189 def.InitFirstLoad(descriptor, class_loader, initial_dex_file);
Alex Light40528472017-03-28 09:07:36 -0700190
Alex Light64e4c142018-01-30 13:46:37 -0800191 // Call all non-retransformable agents.
192 Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookNonRetransformable>(
193 event_handler, self, &def);
194
195 std::vector<unsigned char> post_non_retransform;
196 if (def.IsModified()) {
197 // Copy the dex data after the non-retransformable events.
198 post_non_retransform.resize(def.GetDexData().size());
199 memcpy(post_non_retransform.data(), def.GetDexData().data(), post_non_retransform.size());
Alex Light440b5d92017-01-24 15:32:25 -0800200 }
Alex Light64e4c142018-01-30 13:46:37 -0800201
Alex Light440b5d92017-01-24 15:32:25 -0800202 // Call all retransformable agents.
Alex Light64e4c142018-01-30 13:46:37 -0800203 Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
204 event_handler, self, &def);
Alex Light440b5d92017-01-24 15:32:25 -0800205
Alex Light64e4c142018-01-30 13:46:37 -0800206 if (def.IsModified()) {
Alex Light440b5d92017-01-24 15:32:25 -0800207 LOG(WARNING) << "Changing class " << descriptor;
Alex Light440b5d92017-01-24 15:32:25 -0800208 art::StackHandleScope<2> hs(self);
209 // Save the results of all the non-retransformable agents.
210 // First allocate the ClassExt
211 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(self)));
212 // Make sure we have a ClassExt. This is fine even though we are a temporary since it will
213 // get copied.
214 if (ext.IsNull()) {
215 // We will just return failure if we fail to allocate
216 LOG(WARNING) << "Could not allocate ext-data for class '" << descriptor << "'. "
217 << "Aborting transformation since we will be unable to store it.";
218 self->AssertPendingOOMException();
219 return;
220 }
221
222 // Allocate the byte array to store the dex file bytes in.
Alex Light6a656312017-03-29 17:18:00 -0700223 art::MutableHandle<art::mirror::Object> arr(hs.NewHandle<art::mirror::Object>(nullptr));
Alex Light64e4c142018-01-30 13:46:37 -0800224 if (post_non_retransform.empty() && strcmp(descriptor, "Ljava/lang/Long;") != 0) {
Alex Light6a656312017-03-29 17:18:00 -0700225 // we didn't have any non-retransformable agents. We can just cache a pointer to the
226 // initial_dex_file. It will be kept live by the class_loader.
227 jlong dex_ptr = reinterpret_cast<uintptr_t>(&initial_dex_file);
228 art::JValue val;
229 val.SetJ(dex_ptr);
230 arr.Assign(art::BoxPrimitive(art::Primitive::kPrimLong, val));
231 } else {
232 arr.Assign(art::mirror::ByteArray::AllocateAndFill(
233 self,
Alex Light64e4c142018-01-30 13:46:37 -0800234 reinterpret_cast<const signed char*>(post_non_retransform.data()),
235 post_non_retransform.size()));
Alex Light6a656312017-03-29 17:18:00 -0700236 }
Alex Light440b5d92017-01-24 15:32:25 -0800237 if (arr.IsNull()) {
Alex Light6a656312017-03-29 17:18:00 -0700238 LOG(WARNING) << "Unable to allocate memory for initial dex-file. Aborting transformation";
Alex Light440b5d92017-01-24 15:32:25 -0800239 self->AssertPendingOOMException();
240 return;
241 }
242
243 std::unique_ptr<const art::DexFile> dex_file(MakeSingleDexFile(self,
244 descriptor,
245 initial_dex_file.GetLocation(),
Alex Light64e4c142018-01-30 13:46:37 -0800246 def.GetDexData().size(),
247 def.GetDexData().data()));
Alex Light440b5d92017-01-24 15:32:25 -0800248 if (dex_file.get() == nullptr) {
249 return;
250 }
251
Alex Lighteb98b082017-01-25 13:02:32 -0800252 // TODO Check Redefined dex file for all invariants.
Alex Light440b5d92017-01-24 15:32:25 -0800253 LOG(WARNING) << "Dex file created by class-definition time transformation of "
254 << descriptor << " is not checked for all retransformation invariants.";
Alex Lighteb98b082017-01-25 13:02:32 -0800255
256 if (!ClassLoaderHelper::AddToClassLoader(self, class_loader, dex_file.get())) {
257 LOG(ERROR) << "Unable to add " << descriptor << " to class loader!";
258 return;
259 }
260
Alex Light440b5d92017-01-24 15:32:25 -0800261 // Actually set the ClassExt's original bytes once we have actually succeeded.
Alex Light2f814aa2017-03-24 15:21:34 +0000262 ext->SetOriginalDexFile(arr.Get());
Alex Light440b5d92017-01-24 15:32:25 -0800263 // Set the return values
264 *final_class_def = &dex_file->GetClassDef(0);
265 *final_dex_file = dex_file.release();
266 }
267 }
268
Andreas Gampee6377462017-01-20 17:37:50 -0800269 void ClassLoad(art::Handle<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
270 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassLoad)) {
271 art::Thread* thread = art::Thread::Current();
272 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
273 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700274 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800275 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700276 thread->GetJniEnv(),
277 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Alex Light9df79b72017-09-12 08:57:31 -0700278 event_handler->DispatchEvent<ArtJvmtiEvent::kClassLoad>(
279 thread,
280 static_cast<JNIEnv*>(thread->GetJniEnv()),
281 thread_jni.get(),
282 jklass.get());
Andreas Gampe691051b2017-02-09 09:15:24 -0800283 if (klass->IsTemp()) {
284 AddTempClass(thread, jklass.get());
285 }
Andreas Gampee6377462017-01-20 17:37:50 -0800286 }
287 }
288
Andreas Gampe691051b2017-02-09 09:15:24 -0800289 void ClassPrepare(art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800290 art::Handle<art::mirror::Class> klass)
291 REQUIRES_SHARED(art::Locks::mutator_lock_) {
292 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassPrepare)) {
293 art::Thread* thread = art::Thread::Current();
Andreas Gampe691051b2017-02-09 09:15:24 -0800294 if (temp_klass.Get() != klass.Get()) {
295 DCHECK(temp_klass->IsTemp());
296 DCHECK(temp_klass->IsRetired());
297 HandleTempClass(thread, temp_klass, klass);
298 }
Andreas Gampee6377462017-01-20 17:37:50 -0800299 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
300 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700301 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800302 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700303 thread->GetJniEnv(),
304 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Andreas Gampe983c1752017-01-23 19:46:56 -0800305 event_handler->DispatchEvent<ArtJvmtiEvent::kClassPrepare>(
306 thread,
307 static_cast<JNIEnv*>(thread->GetJniEnv()),
308 thread_jni.get(),
309 jklass.get());
Andreas Gampee6377462017-01-20 17:37:50 -0800310 }
311 }
312
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800313 // To support parallel class-loading, we need to perform some locking dances here. Namely,
314 // the fixup stage must not be holding the temp_classes lock when it fixes up the system
315 // (as that requires suspending all mutators).
316
Andreas Gampee6377462017-01-20 17:37:50 -0800317 void AddTempClass(art::Thread* self, jclass klass) {
318 std::unique_lock<std::mutex> mu(temp_classes_lock);
Andreas Gampe691051b2017-02-09 09:15:24 -0800319 jclass global_klass = reinterpret_cast<jclass>(self->GetJniEnv()->NewGlobalRef(klass));
320 temp_classes.push_back(global_klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800321 }
322
Andreas Gampe691051b2017-02-09 09:15:24 -0800323 void HandleTempClass(art::Thread* self,
324 art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800325 art::Handle<art::mirror::Class> klass)
326 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800327 bool requires_fixup = false;
328 {
329 std::unique_lock<std::mutex> mu(temp_classes_lock);
330 if (temp_classes.empty()) {
331 return;
Andreas Gampee6377462017-01-20 17:37:50 -0800332 }
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800333
334 for (auto it = temp_classes.begin(); it != temp_classes.end(); ++it) {
335 if (temp_klass.Get() == art::ObjPtr<art::mirror::Class>::DownCast(self->DecodeJObject(*it))) {
336 self->GetJniEnv()->DeleteGlobalRef(*it);
337 temp_classes.erase(it);
338 requires_fixup = true;
339 break;
340 }
341 }
342 }
343 if (requires_fixup) {
344 FixupTempClass(self, temp_klass, klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800345 }
346 }
347
Andreas Gampe691051b2017-02-09 09:15:24 -0800348 void FixupTempClass(art::Thread* self,
349 art::Handle<art::mirror::Class> temp_klass,
350 art::Handle<art::mirror::Class> klass)
Andreas Gampee6377462017-01-20 17:37:50 -0800351 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe691051b2017-02-09 09:15:24 -0800352 // Suspend everything.
353 art::gc::Heap* heap = art::Runtime::Current()->GetHeap();
354 if (heap->IsGcConcurrentAndMoving()) {
355 // Need to take a heap dump while GC isn't running. See the
356 // comment in Heap::VisitObjects().
357 heap->IncrementDisableMovingGC(self);
358 }
359 {
360 art::ScopedThreadSuspension sts(self, art::kWaitingForVisitObjects);
361 art::ScopedSuspendAll ssa("FixupTempClass");
362
363 art::mirror::Class* input = temp_klass.Get();
364 art::mirror::Class* output = klass.Get();
365
366 FixupGlobalReferenceTables(input, output);
Andreas Gampe94dda932017-02-09 18:19:21 -0800367 FixupLocalReferenceTables(self, input, output);
Andreas Gampea67354b2017-02-10 16:18:30 -0800368 FixupHeap(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800369 }
370 if (heap->IsGcConcurrentAndMoving()) {
371 heap->DecrementDisableMovingGC(self);
372 }
373 }
374
Andreas Gampe94dda932017-02-09 18:19:21 -0800375 class RootUpdater : public art::RootVisitor {
376 public:
377 RootUpdater(const art::mirror::Class* input, art::mirror::Class* output)
378 : input_(input), output_(output) {}
379
380 void VisitRoots(art::mirror::Object*** roots,
381 size_t count,
382 const art::RootInfo& info ATTRIBUTE_UNUSED)
383 OVERRIDE {
384 for (size_t i = 0; i != count; ++i) {
385 if (*roots[i] == input_) {
386 *roots[i] = output_;
387 }
388 }
389 }
390
391 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
392 size_t count,
393 const art::RootInfo& info ATTRIBUTE_UNUSED)
394 OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
395 for (size_t i = 0; i != count; ++i) {
396 if (roots[i]->AsMirrorPtr() == input_) {
397 roots[i]->Assign(output_);
398 }
399 }
400 }
401
402 private:
403 const art::mirror::Class* input_;
404 art::mirror::Class* output_;
405 };
406
Andreas Gampea67354b2017-02-10 16:18:30 -0800407 void FixupGlobalReferenceTables(art::mirror::Class* input, art::mirror::Class* output)
Andreas Gampe691051b2017-02-09 09:15:24 -0800408 REQUIRES(art::Locks::mutator_lock_) {
409 art::JavaVMExt* java_vm = art::Runtime::Current()->GetJavaVM();
410
411 // Fix up the global table with a root visitor.
Andreas Gampe94dda932017-02-09 18:19:21 -0800412 RootUpdater global_update(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800413 java_vm->VisitRoots(&global_update);
414
415 class WeakGlobalUpdate : public art::IsMarkedVisitor {
416 public:
417 WeakGlobalUpdate(art::mirror::Class* root_input, art::mirror::Class* root_output)
418 : input_(root_input), output_(root_output) {}
419
420 art::mirror::Object* IsMarked(art::mirror::Object* obj) OVERRIDE {
421 if (obj == input_) {
422 return output_;
423 }
424 return obj;
425 }
426
427 private:
428 const art::mirror::Class* input_;
429 art::mirror::Class* output_;
430 };
431 WeakGlobalUpdate weak_global_update(input, output);
432 java_vm->SweepJniWeakGlobals(&weak_global_update);
Andreas Gampee6377462017-01-20 17:37:50 -0800433 }
434
Andreas Gampe94dda932017-02-09 18:19:21 -0800435 void FixupLocalReferenceTables(art::Thread* self,
436 art::mirror::Class* input,
437 art::mirror::Class* output)
438 REQUIRES(art::Locks::mutator_lock_) {
439 class LocalUpdate {
440 public:
441 LocalUpdate(const art::mirror::Class* root_input, art::mirror::Class* root_output)
442 : input_(root_input), output_(root_output) {}
443
444 static void Callback(art::Thread* t, void* arg) REQUIRES(art::Locks::mutator_lock_) {
445 LocalUpdate* local = reinterpret_cast<LocalUpdate*>(arg);
446
447 // Fix up the local table with a root visitor.
448 RootUpdater local_update(local->input_, local->output_);
Ian Rogers55256cb2017-12-21 17:07:11 -0800449 t->GetJniEnv()->VisitJniLocalRoots(
Andreas Gampe94dda932017-02-09 18:19:21 -0800450 &local_update, art::RootInfo(art::kRootJNILocal, t->GetThreadId()));
451 }
452
453 private:
454 const art::mirror::Class* input_;
455 art::mirror::Class* output_;
456 };
457 LocalUpdate local_upd(input, output);
458 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
459 art::Runtime::Current()->GetThreadList()->ForEach(LocalUpdate::Callback, &local_upd);
460 }
461
Andreas Gampea67354b2017-02-10 16:18:30 -0800462 void FixupHeap(art::mirror::Class* input, art::mirror::Class* output)
463 REQUIRES(art::Locks::mutator_lock_) {
464 class HeapFixupVisitor {
465 public:
466 HeapFixupVisitor(const art::mirror::Class* root_input, art::mirror::Class* root_output)
467 : input_(root_input), output_(root_output) {}
468
469 void operator()(art::mirror::Object* src,
470 art::MemberOffset field_offset,
471 bool is_static ATTRIBUTE_UNUSED) const
472 REQUIRES_SHARED(art::Locks::mutator_lock_) {
473 art::mirror::HeapReference<art::mirror::Object>* trg =
474 src->GetFieldObjectReferenceAddr(field_offset);
475 if (trg->AsMirrorPtr() == input_) {
476 DCHECK_NE(field_offset.Uint32Value(), 0u); // This shouldn't be the class field of
477 // an object.
478 trg->Assign(output_);
479 }
480 }
481
Andreas Gampe52784ac2017-02-13 18:10:09 -0800482 void operator()(art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
483 art::ObjPtr<art::mirror::Reference> reference) const
484 REQUIRES_SHARED(art::Locks::mutator_lock_) {
485 art::mirror::Object* val = reference->GetReferent();
486 if (val == input_) {
487 reference->SetReferent<false>(output_);
488 }
489 }
490
Andreas Gampea67354b2017-02-10 16:18:30 -0800491 void VisitRoot(art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED)
Andreas Gampe52784ac2017-02-13 18:10:09 -0800492 const {
Andreas Gampea67354b2017-02-10 16:18:30 -0800493 LOG(FATAL) << "Unreachable";
494 }
495
496 void VisitRootIfNonNull(
497 art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED) const {
498 LOG(FATAL) << "Unreachable";
499 }
500
Andreas Gampea67354b2017-02-10 16:18:30 -0800501 private:
502 const art::mirror::Class* input_;
503 art::mirror::Class* output_;
504 };
505 HeapFixupVisitor hfv(input, output);
Andreas Gampe1c158a02017-07-13 17:26:19 -0700506 auto object_visitor = [&](art::mirror::Object* obj) {
507 obj->VisitReferences<false>(hfv, hfv); // Visit references, not native roots.
508 };
509 art::Runtime::Current()->GetHeap()->VisitObjectsPaused(object_visitor);
Andreas Gampea67354b2017-02-10 16:18:30 -0800510 }
511
Andreas Gampee6377462017-01-20 17:37:50 -0800512 // A set of all the temp classes we have handed out. We have to fix up references to these.
513 // For simplicity, we store the temp classes as JNI global references in a vector. Normally a
514 // Prepare event will closely follow, so the vector should be small.
515 std::mutex temp_classes_lock;
516 std::vector<jclass> temp_classes;
517
518 EventHandler* event_handler = nullptr;
519};
520
521ClassCallback gClassCallback;
522
523void ClassUtil::Register(EventHandler* handler) {
524 gClassCallback.event_handler = handler;
525 art::ScopedThreadStateChange stsc(art::Thread::Current(),
526 art::ThreadState::kWaitingForDebuggerToAttach);
527 art::ScopedSuspendAll ssa("Add load callback");
528 art::Runtime::Current()->GetRuntimeCallbacks()->AddClassLoadCallback(&gClassCallback);
529}
530
531void ClassUtil::Unregister() {
532 art::ScopedThreadStateChange stsc(art::Thread::Current(),
533 art::ThreadState::kWaitingForDebuggerToAttach);
534 art::ScopedSuspendAll ssa("Remove thread callback");
535 art::Runtime* runtime = art::Runtime::Current();
536 runtime->GetRuntimeCallbacks()->RemoveClassLoadCallback(&gClassCallback);
537}
538
Andreas Gampeac587272017-01-05 15:21:34 -0800539jvmtiError ClassUtil::GetClassFields(jvmtiEnv* env,
540 jclass jklass,
541 jint* field_count_ptr,
542 jfieldID** fields_ptr) {
543 art::ScopedObjectAccess soa(art::Thread::Current());
544 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
545 if (klass == nullptr) {
546 return ERR(INVALID_CLASS);
547 }
548
Alex Light2c6cd692017-06-30 07:34:40 -0700549 // Check if this class is a temporary class object used for loading. Since we are seeing it the
550 // class must not have been prepared yet since otherwise the fixup would have gotten the jobject
551 // to point to the final class object.
552 if (klass->IsTemp() || klass->IsRetired()) {
553 return ERR(CLASS_NOT_PREPARED);
554 }
555
Andreas Gampeac587272017-01-05 15:21:34 -0800556 if (field_count_ptr == nullptr || fields_ptr == nullptr) {
557 return ERR(NULL_POINTER);
558 }
559
Andreas Gampeac587272017-01-05 15:21:34 -0800560 art::IterationRange<art::StrideIterator<art::ArtField>> ifields = klass->GetIFields();
561 art::IterationRange<art::StrideIterator<art::ArtField>> sfields = klass->GetSFields();
562 size_t array_size = klass->NumInstanceFields() + klass->NumStaticFields();
563
564 unsigned char* out_ptr;
565 jvmtiError allocError = env->Allocate(array_size * sizeof(jfieldID), &out_ptr);
566 if (allocError != ERR(NONE)) {
567 return allocError;
568 }
569 jfieldID* field_array = reinterpret_cast<jfieldID*>(out_ptr);
570
571 size_t array_idx = 0;
572 for (art::ArtField& field : sfields) {
573 field_array[array_idx] = art::jni::EncodeArtField(&field);
574 ++array_idx;
575 }
576 for (art::ArtField& field : ifields) {
577 field_array[array_idx] = art::jni::EncodeArtField(&field);
578 ++array_idx;
579 }
580
581 *field_count_ptr = static_cast<jint>(array_size);
582 *fields_ptr = field_array;
583
584 return ERR(NONE);
585}
586
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800587jvmtiError ClassUtil::GetClassMethods(jvmtiEnv* env,
588 jclass jklass,
589 jint* method_count_ptr,
590 jmethodID** methods_ptr) {
591 art::ScopedObjectAccess soa(art::Thread::Current());
592 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
593 if (klass == nullptr) {
594 return ERR(INVALID_CLASS);
595 }
596
Alex Light2c6cd692017-06-30 07:34:40 -0700597 // Check if this class is a temporary class object used for loading. Since we are seeing it the
598 // class must not have been prepared yet since otherwise the fixup would have gotten the jobject
599 // to point to the final class object.
600 if (klass->IsTemp() || klass->IsRetired()) {
601 return ERR(CLASS_NOT_PREPARED);
602 }
603
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800604 if (method_count_ptr == nullptr || methods_ptr == nullptr) {
605 return ERR(NULL_POINTER);
606 }
607
608 size_t array_size = klass->NumDeclaredVirtualMethods() + klass->NumDirectMethods();
609 unsigned char* out_ptr;
610 jvmtiError allocError = env->Allocate(array_size * sizeof(jmethodID), &out_ptr);
611 if (allocError != ERR(NONE)) {
612 return allocError;
613 }
614 jmethodID* method_array = reinterpret_cast<jmethodID*>(out_ptr);
615
616 if (art::kIsDebugBuild) {
617 size_t count = 0;
618 for (auto& m ATTRIBUTE_UNUSED : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
619 count++;
620 }
621 CHECK_EQ(count, klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods());
622 }
623
624 size_t array_idx = 0;
625 for (auto& m : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
626 method_array[array_idx] = art::jni::EncodeArtMethod(&m);
627 ++array_idx;
628 }
629
630 *method_count_ptr = static_cast<jint>(array_size);
631 *methods_ptr = method_array;
632
633 return ERR(NONE);
634}
635
Andreas Gampe8b07e472017-01-06 14:20:39 -0800636jvmtiError ClassUtil::GetImplementedInterfaces(jvmtiEnv* env,
637 jclass jklass,
638 jint* interface_count_ptr,
639 jclass** interfaces_ptr) {
640 art::ScopedObjectAccess soa(art::Thread::Current());
641 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
642 if (klass == nullptr) {
643 return ERR(INVALID_CLASS);
644 }
645
646 if (interface_count_ptr == nullptr || interfaces_ptr == nullptr) {
647 return ERR(NULL_POINTER);
648 }
649
650 // Need to handle array specifically. Arrays implement Serializable and Cloneable, but the
651 // spec says these should not be reported.
652 if (klass->IsArrayClass()) {
653 *interface_count_ptr = 0;
654 *interfaces_ptr = nullptr; // TODO: Should we allocate a dummy here?
655 return ERR(NONE);
656 }
657
658 size_t array_size = klass->NumDirectInterfaces();
659 unsigned char* out_ptr;
660 jvmtiError allocError = env->Allocate(array_size * sizeof(jclass), &out_ptr);
661 if (allocError != ERR(NONE)) {
662 return allocError;
663 }
664 jclass* interface_array = reinterpret_cast<jclass*>(out_ptr);
665
666 art::StackHandleScope<1> hs(soa.Self());
667 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
668
669 for (uint32_t idx = 0; idx != array_size; ++idx) {
670 art::ObjPtr<art::mirror::Class> inf_klass =
671 art::mirror::Class::ResolveDirectInterface(soa.Self(), h_klass, idx);
672 if (inf_klass == nullptr) {
673 soa.Self()->ClearException();
674 env->Deallocate(out_ptr);
675 // TODO: What is the right error code here?
676 return ERR(INTERNAL);
677 }
678 interface_array[idx] = soa.AddLocalReference<jclass>(inf_klass);
679 }
680
681 *interface_count_ptr = static_cast<jint>(array_size);
682 *interfaces_ptr = interface_array;
683
684 return ERR(NONE);
685}
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800686
Andreas Gampee492ae32016-10-28 19:34:57 -0700687jvmtiError ClassUtil::GetClassSignature(jvmtiEnv* env,
688 jclass jklass,
689 char** signature_ptr,
690 char** generic_ptr) {
691 art::ScopedObjectAccess soa(art::Thread::Current());
692 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
693 if (klass == nullptr) {
694 return ERR(INVALID_CLASS);
695 }
696
Andreas Gampe54711412017-02-21 12:41:43 -0800697 JvmtiUniquePtr<char[]> sig_copy;
Andreas Gampee492ae32016-10-28 19:34:57 -0700698 if (signature_ptr != nullptr) {
699 std::string storage;
700 const char* descriptor = klass->GetDescriptor(&storage);
701
Andreas Gampe54711412017-02-21 12:41:43 -0800702 jvmtiError ret;
703 sig_copy = CopyString(env, descriptor, &ret);
704 if (sig_copy == nullptr) {
Andreas Gampee492ae32016-10-28 19:34:57 -0700705 return ret;
706 }
Andreas Gampe54711412017-02-21 12:41:43 -0800707 *signature_ptr = sig_copy.get();
Andreas Gampee492ae32016-10-28 19:34:57 -0700708 }
709
Andreas Gampee6377462017-01-20 17:37:50 -0800710 if (generic_ptr != nullptr) {
711 *generic_ptr = nullptr;
Andreas Gampe0eb36432017-02-15 18:36:14 -0800712 if (!klass->IsProxyClass() && klass->GetDexCache() != nullptr) {
713 art::StackHandleScope<1> hs(soa.Self());
714 art::Handle<art::mirror::Class> h_klass = hs.NewHandle(klass);
715 art::mirror::ObjectArray<art::mirror::String>* str_array =
716 art::annotations::GetSignatureAnnotationForClass(h_klass);
717 if (str_array != nullptr) {
718 std::ostringstream oss;
719 for (int32_t i = 0; i != str_array->GetLength(); ++i) {
720 oss << str_array->Get(i)->ToModifiedUtf8();
721 }
722 std::string output_string = oss.str();
Andreas Gampe54711412017-02-21 12:41:43 -0800723 jvmtiError ret;
724 JvmtiUniquePtr<char[]> copy = CopyString(env, output_string.c_str(), &ret);
725 if (copy == nullptr) {
Andreas Gampe0eb36432017-02-15 18:36:14 -0800726 return ret;
727 }
Andreas Gampe54711412017-02-21 12:41:43 -0800728 *generic_ptr = copy.release();
Andreas Gampe0eb36432017-02-15 18:36:14 -0800729 } else if (soa.Self()->IsExceptionPending()) {
730 // TODO: Should we report an error here?
731 soa.Self()->ClearException();
732 }
733 }
Andreas Gampee6377462017-01-20 17:37:50 -0800734 }
Andreas Gampee492ae32016-10-28 19:34:57 -0700735
736 // Everything is fine, release the buffers.
737 sig_copy.release();
738
739 return ERR(NONE);
740}
741
Andreas Gampeff9d2092017-01-06 09:12:49 -0800742jvmtiError ClassUtil::GetClassStatus(jvmtiEnv* env ATTRIBUTE_UNUSED,
743 jclass jklass,
744 jint* status_ptr) {
745 art::ScopedObjectAccess soa(art::Thread::Current());
746 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
747 if (klass == nullptr) {
748 return ERR(INVALID_CLASS);
749 }
750
751 if (status_ptr == nullptr) {
752 return ERR(NULL_POINTER);
753 }
754
755 if (klass->IsArrayClass()) {
756 *status_ptr = JVMTI_CLASS_STATUS_ARRAY;
757 } else if (klass->IsPrimitive()) {
758 *status_ptr = JVMTI_CLASS_STATUS_PRIMITIVE;
759 } else {
760 *status_ptr = JVMTI_CLASS_STATUS_VERIFIED; // All loaded classes are structurally verified.
761 // This is finicky. If there's an error, we'll say it wasn't prepared.
762 if (klass->IsResolved()) {
763 *status_ptr |= JVMTI_CLASS_STATUS_PREPARED;
764 }
765 if (klass->IsInitialized()) {
766 *status_ptr |= JVMTI_CLASS_STATUS_INITIALIZED;
767 }
768 // Technically the class may be erroneous for other reasons, but we do not have enough info.
769 if (klass->IsErroneous()) {
770 *status_ptr |= JVMTI_CLASS_STATUS_ERROR;
771 }
772 }
773
774 return ERR(NONE);
775}
776
Andreas Gampe4fd66ec2017-01-05 14:42:13 -0800777template <typename T>
778static jvmtiError ClassIsT(jclass jklass, T test, jboolean* is_t_ptr) {
779 art::ScopedObjectAccess soa(art::Thread::Current());
780 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
781 if (klass == nullptr) {
782 return ERR(INVALID_CLASS);
783 }
784
785 if (is_t_ptr == nullptr) {
786 return ERR(NULL_POINTER);
787 }
788
789 *is_t_ptr = test(klass) ? JNI_TRUE : JNI_FALSE;
790 return ERR(NONE);
791}
792
793jvmtiError ClassUtil::IsInterface(jvmtiEnv* env ATTRIBUTE_UNUSED,
794 jclass jklass,
795 jboolean* is_interface_ptr) {
796 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
797 return klass->IsInterface();
798 };
799 return ClassIsT(jklass, test, is_interface_ptr);
800}
801
802jvmtiError ClassUtil::IsArrayClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
803 jclass jklass,
804 jboolean* is_array_class_ptr) {
805 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
806 return klass->IsArrayClass();
807 };
808 return ClassIsT(jklass, test, is_array_class_ptr);
809}
810
Andreas Gampe64013e52017-01-06 13:07:19 -0800811// Keep this in sync with Class.getModifiers().
812static uint32_t ClassGetModifiers(art::Thread* self, art::ObjPtr<art::mirror::Class> klass)
813 REQUIRES_SHARED(art::Locks::mutator_lock_) {
814 if (klass->IsArrayClass()) {
815 uint32_t component_modifiers = ClassGetModifiers(self, klass->GetComponentType());
816 if ((component_modifiers & art::kAccInterface) != 0) {
817 component_modifiers &= ~(art::kAccInterface | art::kAccStatic);
818 }
819 return art::kAccAbstract | art::kAccFinal | component_modifiers;
820 }
821
822 uint32_t modifiers = klass->GetAccessFlags() & art::kAccJavaFlagsMask;
823
824 art::StackHandleScope<1> hs(self);
825 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
826 return art::mirror::Class::GetInnerClassFlags(h_klass, modifiers);
827}
828
829jvmtiError ClassUtil::GetClassModifiers(jvmtiEnv* env ATTRIBUTE_UNUSED,
830 jclass jklass,
831 jint* modifiers_ptr) {
832 art::ScopedObjectAccess soa(art::Thread::Current());
833 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
834 if (klass == nullptr) {
835 return ERR(INVALID_CLASS);
836 }
837
838 if (modifiers_ptr == nullptr) {
839 return ERR(NULL_POINTER);
840 }
841
842 *modifiers_ptr = ClassGetModifiers(soa.Self(), klass);
843
844 return ERR(NONE);
845}
846
Andreas Gampe8f5b6032017-01-06 15:50:55 -0800847jvmtiError ClassUtil::GetClassLoader(jvmtiEnv* env ATTRIBUTE_UNUSED,
848 jclass jklass,
849 jobject* classloader_ptr) {
850 art::ScopedObjectAccess soa(art::Thread::Current());
851 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
852 if (klass == nullptr) {
853 return ERR(INVALID_CLASS);
854 }
855
856 if (classloader_ptr == nullptr) {
857 return ERR(NULL_POINTER);
858 }
859
860 *classloader_ptr = soa.AddLocalReference<jobject>(klass->GetClassLoader());
861
862 return ERR(NONE);
863}
864
Alex Lightc7588752018-02-20 11:15:54 -0800865// Copies unique class descriptors into the classes list from dex_files.
866static jvmtiError CopyClassDescriptors(jvmtiEnv* env,
867 const std::vector<const art::DexFile*>& dex_files,
868 /*out*/jint* count_ptr,
869 /*out*/char*** classes) {
870 jvmtiError res = OK;
871 std::set<art::StringPiece> unique_descriptors;
872 std::vector<const char*> descriptors;
873 auto add_descriptor = [&](const char* desc) {
874 // Don't add duplicates.
875 if (res == OK && unique_descriptors.find(desc) == unique_descriptors.end()) {
876 // The desc will remain valid since we hold a ref to the class_loader.
877 unique_descriptors.insert(desc);
878 descriptors.push_back(CopyString(env, desc, &res).release());
879 }
880 };
881 for (const art::DexFile* dex_file : dex_files) {
882 uint32_t num_defs = dex_file->NumClassDefs();
883 for (uint32_t i = 0; i < num_defs; i++) {
884 add_descriptor(dex_file->GetClassDescriptor(dex_file->GetClassDef(i)));
885 }
886 }
887 char** out_data = nullptr;
888 if (res == OK) {
889 res = env->Allocate(sizeof(char*) * descriptors.size(),
890 reinterpret_cast<unsigned char**>(&out_data));
891 }
892 if (res != OK) {
893 env->Deallocate(reinterpret_cast<unsigned char*>(out_data));
894 // Failed to allocate. Cleanup everything.
895 for (const char* data : descriptors) {
896 env->Deallocate(reinterpret_cast<unsigned char*>(const_cast<char*>(data)));
897 }
898 descriptors.clear();
899 return res;
900 }
901 // Everything is good.
902 memcpy(out_data, descriptors.data(), sizeof(char*) * descriptors.size());
903 *count_ptr = static_cast<jint>(descriptors.size());
904 *classes = out_data;
905 return OK;
906}
907
908jvmtiError ClassUtil::GetClassLoaderClassDescriptors(jvmtiEnv* env,
909 jobject loader,
910 /*out*/jint* count_ptr,
911 /*out*/char*** classes) {
912 art::Thread* self = art::Thread::Current();
913 if (env == nullptr) {
914 return ERR(INVALID_ENVIRONMENT);
915 } else if (self == nullptr) {
916 return ERR(UNATTACHED_THREAD);
917 } else if (count_ptr == nullptr || classes == nullptr) {
918 return ERR(NULL_POINTER);
919 }
920 art::JNIEnvExt* jnienv = self->GetJniEnv();
921 if (loader == nullptr ||
922 jnienv->IsInstanceOf(loader, art::WellKnownClasses::java_lang_BootClassLoader)) {
923 // We can just get the dex files directly for the boot class path.
924 return CopyClassDescriptors(env,
925 art::Runtime::Current()->GetClassLinker()->GetBootClassPath(),
926 count_ptr,
927 classes);
928 }
929 if (!jnienv->IsInstanceOf(loader, art::WellKnownClasses::java_lang_ClassLoader)) {
930 return ERR(ILLEGAL_ARGUMENT);
931 } else if (!jnienv->IsInstanceOf(loader,
932 art::WellKnownClasses::dalvik_system_BaseDexClassLoader)) {
933 LOG(ERROR) << "GetClassLoaderClassDescriptors is only implemented for BootClassPath and "
934 << "dalvik.system.BaseDexClassLoader class loaders";
935 // TODO Possibly return OK With no classes would be better since these ones cannot have any
936 // real classes associated with them.
937 return ERR(NOT_IMPLEMENTED);
938 }
939
940 art::ScopedObjectAccess soa(self);
941 art::StackHandleScope<1> hs(self);
942 art::Handle<art::mirror::ClassLoader> class_loader(
943 hs.NewHandle(soa.Decode<art::mirror::ClassLoader>(loader)));
944 std::vector<const art::DexFile*> dex_files;
945 ClassLoaderHelper::VisitDexFileObjects(
946 self,
947 class_loader,
948 [&] (art::ObjPtr<art::mirror::Object> dex_file) REQUIRES_SHARED(art::Locks::mutator_lock_) {
949 art::StackHandleScope<2> hs(self);
950 art::Handle<art::mirror::Object> h_dex_file(hs.NewHandle(dex_file));
951 art::Handle<art::mirror::LongArray> cookie(
952 hs.NewHandle(ClassLoaderHelper::GetDexFileCookie(h_dex_file)));
953 size_t num_elements = cookie->GetLength();
954 // We need to skip over the oat_file that's the first element. The other elements are all
955 // dex files.
956 for (size_t i = 1; i < num_elements; i++) {
957 dex_files.push_back(
958 reinterpret_cast<const art::DexFile*>(static_cast<uintptr_t>(cookie->Get(i))));
959 }
960 // Iterate over all dex files.
961 return true;
962 });
963 // We hold the loader so the dex files won't go away until after this call at worst.
964 return CopyClassDescriptors(env, dex_files, count_ptr, classes);
965}
966
Andreas Gampe70f16392017-01-16 14:20:10 -0800967jvmtiError ClassUtil::GetClassLoaderClasses(jvmtiEnv* env,
968 jobject initiating_loader,
969 jint* class_count_ptr,
970 jclass** classes_ptr) {
971 UNUSED(env, initiating_loader, class_count_ptr, classes_ptr);
972
973 if (class_count_ptr == nullptr || classes_ptr == nullptr) {
974 return ERR(NULL_POINTER);
975 }
976 art::Thread* self = art::Thread::Current();
977 if (!self->GetJniEnv()->IsInstanceOf(initiating_loader,
978 art::WellKnownClasses::java_lang_ClassLoader)) {
979 return ERR(ILLEGAL_ARGUMENT);
980 }
981 if (self->GetJniEnv()->IsInstanceOf(initiating_loader,
982 art::WellKnownClasses::java_lang_BootClassLoader)) {
983 // Need to use null for the BootClassLoader.
984 initiating_loader = nullptr;
985 }
986
987 art::ScopedObjectAccess soa(self);
988 art::ObjPtr<art::mirror::ClassLoader> class_loader =
989 soa.Decode<art::mirror::ClassLoader>(initiating_loader);
990
991 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
992
993 art::ReaderMutexLock mu(self, *art::Locks::classlinker_classes_lock_);
994
995 art::ClassTable* class_table = class_linker->ClassTableForClassLoader(class_loader);
996 if (class_table == nullptr) {
997 // Nothing loaded.
998 *class_count_ptr = 0;
999 *classes_ptr = nullptr;
1000 return ERR(NONE);
1001 }
1002
1003 struct ClassTableCount {
1004 bool operator()(art::ObjPtr<art::mirror::Class> klass) {
1005 DCHECK(klass != nullptr);
1006 ++count;
1007 return true;
1008 }
1009
1010 size_t count = 0;
1011 };
1012 ClassTableCount ctc;
1013 class_table->Visit(ctc);
1014
1015 if (ctc.count == 0) {
1016 // Nothing loaded.
1017 *class_count_ptr = 0;
1018 *classes_ptr = nullptr;
1019 return ERR(NONE);
1020 }
1021
1022 unsigned char* data;
1023 jvmtiError data_result = env->Allocate(ctc.count * sizeof(jclass), &data);
1024 if (data_result != ERR(NONE)) {
1025 return data_result;
1026 }
1027 jclass* class_array = reinterpret_cast<jclass*>(data);
1028
1029 struct ClassTableFill {
1030 bool operator()(art::ObjPtr<art::mirror::Class> klass)
1031 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1032 DCHECK(klass != nullptr);
1033 DCHECK_LT(count, ctc_ref.count);
1034 local_class_array[count++] = soa_ptr->AddLocalReference<jclass>(klass);
1035 return true;
1036 }
1037
1038 jclass* local_class_array;
1039 const ClassTableCount& ctc_ref;
1040 art::ScopedObjectAccess* soa_ptr;
1041 size_t count;
1042 };
1043 ClassTableFill ctf = { class_array, ctc, &soa, 0 };
1044 class_table->Visit(ctf);
1045 DCHECK_EQ(ctc.count, ctf.count);
1046
1047 *class_count_ptr = ctc.count;
1048 *classes_ptr = class_array;
1049
1050 return ERR(NONE);
1051}
1052
Andreas Gampe812a2442017-01-19 22:04:46 -08001053jvmtiError ClassUtil::GetClassVersionNumbers(jvmtiEnv* env ATTRIBUTE_UNUSED,
1054 jclass jklass,
1055 jint* minor_version_ptr,
1056 jint* major_version_ptr) {
1057 art::ScopedObjectAccess soa(art::Thread::Current());
1058 if (jklass == nullptr) {
1059 return ERR(INVALID_CLASS);
1060 }
1061 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1062 if (!jklass_obj->IsClass()) {
1063 return ERR(INVALID_CLASS);
1064 }
1065 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
1066 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1067 return ERR(INVALID_CLASS);
1068 }
1069
1070 if (minor_version_ptr == nullptr || major_version_ptr == nullptr) {
1071 return ERR(NULL_POINTER);
1072 }
1073
1074 // Note: proxies will show the dex file version of java.lang.reflect.Proxy, as that is
1075 // what their dex cache copies from.
1076 uint32_t version = klass->GetDexFile().GetHeader().GetVersion();
1077
1078 *major_version_ptr = static_cast<jint>(version);
1079 *minor_version_ptr = 0;
1080
1081 return ERR(NONE);
1082}
1083
Alex Light6fa7b812017-06-16 09:04:29 -07001084jvmtiError ClassUtil::GetSourceFileName(jvmtiEnv* env, jclass jklass, char** source_name_ptr) {
1085 art::ScopedObjectAccess soa(art::Thread::Current());
1086 if (jklass == nullptr) {
1087 return ERR(INVALID_CLASS);
1088 }
1089 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1090 if (!jklass_obj->IsClass()) {
1091 return ERR(INVALID_CLASS);
1092 }
1093 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
1094 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1095 return ERR(ABSENT_INFORMATION);
1096 }
1097 JvmtiUniquePtr<char[]> source_copy;
1098 const char* file_name = klass->GetSourceFile();
1099 if (file_name == nullptr) {
1100 return ERR(ABSENT_INFORMATION);
1101 }
1102 jvmtiError ret;
1103 source_copy = CopyString(env, file_name, &ret);
1104 if (source_copy == nullptr) {
1105 return ret;
1106 }
1107 *source_name_ptr = source_copy.release();
1108 return OK;
1109}
1110
1111jvmtiError ClassUtil::GetSourceDebugExtension(jvmtiEnv* env,
1112 jclass jklass,
1113 char** source_debug_extension_ptr) {
1114 art::ScopedObjectAccess soa(art::Thread::Current());
1115 if (jklass == nullptr) {
1116 return ERR(INVALID_CLASS);
1117 }
1118 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1119 if (!jklass_obj->IsClass()) {
1120 return ERR(INVALID_CLASS);
1121 }
1122 art::StackHandleScope<1> hs(art::Thread::Current());
1123 art::Handle<art::mirror::Class> klass(hs.NewHandle(jklass_obj->AsClass()));
1124 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1125 return ERR(ABSENT_INFORMATION);
1126 }
1127 JvmtiUniquePtr<char[]> ext_copy;
1128 const char* data = art::annotations::GetSourceDebugExtension(klass);
1129 if (data == nullptr) {
1130 return ERR(ABSENT_INFORMATION);
1131 }
1132 jvmtiError ret;
1133 ext_copy = CopyString(env, data, &ret);
1134 if (ext_copy == nullptr) {
1135 return ret;
1136 }
1137 *source_debug_extension_ptr = ext_copy.release();
1138 return OK;
1139}
1140
Andreas Gampee492ae32016-10-28 19:34:57 -07001141} // namespace openjdkjvmti