1 /* 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
34 #include "android-base/stringprintf.h"
35
36 #include <mutex>
37 #include <string_view>
38 #include <unordered_set>
39
40 #include "art_jvmti.h"
41 #include "base/array_ref.h"
42 #include "base/logging.h"
43 #include "base/macros.h"
44 #include "base/utils.h"
45 #include "class_linker.h"
46 #include "class_loader_utils.h"
47 #include "class_table-inl.h"
48 #include "common_throws.h"
49 #include "dex/art_dex_file_loader.h"
50 #include "dex/dex_file_annotations.h"
51 #include "dex/dex_file_loader.h"
52 #include "dex/primitive.h"
53 #include "events-inl.h"
54 #include "fixed_up_dex_file.h"
55 #include "gc/heap-visit-objects-inl.h"
56 #include "gc/heap.h"
57 #include "gc_root.h"
58 #include "handle.h"
59 #include "hidden_api.h"
60 #include "jni/jni_env_ext-inl.h"
61 #include "jni/jni_internal.h"
62 #include "mirror/array-alloc-inl.h"
63 #include "mirror/array-inl.h"
64 #include "mirror/class-inl.h"
65 #include "mirror/class_ext.h"
66 #include "mirror/object-inl.h"
67 #include "mirror/object-refvisitor-inl.h"
68 #include "mirror/object_array-inl.h"
69 #include "mirror/object_reference.h"
70 #include "mirror/reference-inl.h"
71 #include "nativehelper/scoped_local_ref.h"
72 #include "reflection.h"
73 #include "runtime.h"
74 #include "runtime_callbacks.h"
75 #include "scoped_thread_state_change-inl.h"
76 #include "thread-current-inl.h"
77 #include "thread_list.h"
78 #include "ti_class_definition.h"
79 #include "ti_class_loader-inl.h"
80 #include "ti_logging.h"
81 #include "ti_phase.h"
82 #include "ti_redefine.h"
83 #include "transform.h"
84 #include "well_known_classes.h"
85
86 namespace openjdkjvmti {
87
88 using android::base::StringPrintf;
89
MakeSingleDexFile(art::Thread * self,const char * descriptor,const std::string & orig_location,jint final_len,const unsigned char * final_dex_data)90 static std::unique_ptr<const art::DexFile> MakeSingleDexFile(art::Thread* self,
91 const char* descriptor,
92 const std::string& orig_location,
93 jint final_len,
94 const unsigned char* final_dex_data)
95 REQUIRES_SHARED(art::Locks::mutator_lock_) {
96 // Make the mmap
97 std::string error_msg;
98 art::ArrayRef<const unsigned char> final_data(final_dex_data, final_len);
99 art::MemMap map = Redefiner::MoveDataToMemMap(orig_location, final_data, &error_msg);
100 if (!map.IsValid()) {
101 LOG(WARNING) << "Unable to allocate mmap for redefined dex file! Error was: " << error_msg;
102 self->ThrowOutOfMemoryError(StringPrintf(
103 "Unable to allocate dex file for transformation of %s", descriptor).c_str());
104 return nullptr;
105 }
106
107 // Make a dex-file
108 if (map.Size() < sizeof(art::DexFile::Header)) {
109 LOG(WARNING) << "Could not read dex file header because dex_data was too short";
110 art::ThrowClassFormatError(nullptr,
111 "Unable to read transformed dex file of %s",
112 descriptor);
113 return nullptr;
114 }
115 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map.Begin())->checksum_;
116 std::string map_name = map.GetName();
117 const art::ArtDexFileLoader dex_file_loader;
118 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(map_name,
119 checksum,
120 std::move(map),
121 /*verify=*/true,
122 /*verify_checksum=*/true,
123 &error_msg));
124 if (dex_file.get() == nullptr) {
125 LOG(WARNING) << "Unable to load modified dex file for " << descriptor << ": " << error_msg;
126 art::ThrowClassFormatError(nullptr,
127 "Unable to read transformed dex file of %s because %s",
128 descriptor,
129 error_msg.c_str());
130 return nullptr;
131 }
132 if (dex_file->NumClassDefs() != 1) {
133 LOG(WARNING) << "Dex file contains more than 1 class_def. Ignoring.";
134 // TODO Throw some other sort of error here maybe?
135 art::ThrowClassFormatError(
136 nullptr,
137 "Unable to use transformed dex file of %s because it contained too many classes",
138 descriptor);
139 return nullptr;
140 }
141 return dex_file;
142 }
143
144 // A deleter that acts like the jvmtiEnv->Deallocate so that asan does not get tripped up.
145 // TODO We should everything use the actual jvmtiEnv->Allocate/Deallocate functions once we can
146 // figure out which env to use.
147 template <typename T>
148 class FakeJvmtiDeleter {
149 public:
FakeJvmtiDeleter()150 FakeJvmtiDeleter() {}
151
152 FakeJvmtiDeleter(FakeJvmtiDeleter&) = default;
153 FakeJvmtiDeleter(FakeJvmtiDeleter&&) noexcept = default;
154 FakeJvmtiDeleter& operator=(const FakeJvmtiDeleter&) = default;
155
operator ()(const U * ptr) const156 template <typename U> void operator()(const U* ptr) const {
157 if (ptr != nullptr) {
158 free(const_cast<U*>(ptr));
159 }
160 }
161 };
162
163 struct ClassCallback : public art::ClassLoadCallback {
ClassPreDefineopenjdkjvmti::ClassCallback164 void ClassPreDefine(const char* descriptor,
165 art::Handle<art::mirror::Class> klass,
166 art::Handle<art::mirror::ClassLoader> class_loader,
167 const art::DexFile& initial_dex_file,
168 const art::dex::ClassDef& initial_class_def ATTRIBUTE_UNUSED,
169 /*out*/art::DexFile const** final_dex_file,
170 /*out*/art::dex::ClassDef const** final_class_def)
171 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
172 bool is_enabled =
173 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookRetransformable) ||
174 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookNonRetransformable);
175 if (!is_enabled) {
176 return;
177 }
178 if (descriptor[0] != 'L') {
179 // It is a primitive or array. Just return
180 return;
181 }
182 jvmtiPhase phase = PhaseUtil::GetPhaseUnchecked();
183 if (UNLIKELY(phase != JVMTI_PHASE_START && phase != JVMTI_PHASE_LIVE)) {
184 // We want to wait until we are at least in the START phase so that all WellKnownClasses and
185 // mirror classes have been initialized and loaded. The runtime relies on these classes having
186 // specific fields and methods present. Since PreDefine hooks don't need to abide by this
187 // restriction we will simply not send the event for these classes.
188 LOG(WARNING) << "Ignoring load of class <" << descriptor << "> as it is being loaded during "
189 << "runtime initialization.";
190 return;
191 }
192
193 art::Thread* self = art::Thread::Current();
194 ArtClassDefinition def;
195 def.InitFirstLoad(descriptor, class_loader, initial_dex_file);
196
197 // Call all non-retransformable agents.
198 Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookNonRetransformable>(
199 event_handler, self, &def);
200
201 std::vector<unsigned char> post_non_retransform;
202 if (def.IsModified()) {
203 // Copy the dex data after the non-retransformable events.
204 post_non_retransform.resize(def.GetDexData().size());
205 memcpy(post_non_retransform.data(), def.GetDexData().data(), post_non_retransform.size());
206 }
207
208 // Call all structural transformation agents.
209 Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kStructuralDexFileLoadHook>(
210 event_handler, self, &def);
211 // Call all retransformable agents.
212 Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
213 event_handler, self, &def);
214
215 if (def.IsModified()) {
216 VLOG(class_linker) << "Changing class " << descriptor;
217 art::StackHandleScope<2> hs(self);
218 // Save the results of all the non-retransformable agents.
219 // First allocate the ClassExt
220 art::Handle<art::mirror::ClassExt> ext =
221 hs.NewHandle(art::mirror::Class::EnsureExtDataPresent(klass, self));
222 // Make sure we have a ClassExt. This is fine even though we are a temporary since it will
223 // get copied.
224 if (ext.IsNull()) {
225 // We will just return failure if we fail to allocate
226 LOG(WARNING) << "Could not allocate ext-data for class '" << descriptor << "'. "
227 << "Aborting transformation since we will be unable to store it.";
228 self->AssertPendingOOMException();
229 return;
230 }
231
232 // Allocate the byte array to store the dex file bytes in.
233 art::MutableHandle<art::mirror::Object> arr(hs.NewHandle<art::mirror::Object>(nullptr));
234 if (post_non_retransform.empty() && strcmp(descriptor, "Ljava/lang/Long;") != 0) {
235 // we didn't have any non-retransformable agents. We can just cache a pointer to the
236 // initial_dex_file. It will be kept live by the class_loader.
237 jlong dex_ptr = reinterpret_cast<uintptr_t>(&initial_dex_file);
238 art::JValue val;
239 val.SetJ(dex_ptr);
240 arr.Assign(art::BoxPrimitive(art::Primitive::kPrimLong, val));
241 } else {
242 arr.Assign(art::mirror::ByteArray::AllocateAndFill(
243 self,
244 reinterpret_cast<const signed char*>(post_non_retransform.data()),
245 post_non_retransform.size()));
246 }
247 if (arr.IsNull()) {
248 LOG(WARNING) << "Unable to allocate memory for initial dex-file. Aborting transformation";
249 self->AssertPendingOOMException();
250 return;
251 }
252
253 std::unique_ptr<const art::DexFile> dex_file(MakeSingleDexFile(self,
254 descriptor,
255 initial_dex_file.GetLocation(),
256 def.GetDexData().size(),
257 def.GetDexData().data()));
258 if (dex_file.get() == nullptr) {
259 return;
260 }
261
262 // TODO Check Redefined dex file for all invariants.
263 LOG(WARNING) << "Dex file created by class-definition time transformation of "
264 << descriptor << " is not checked for all retransformation invariants.";
265
266 if (!ClassLoaderHelper::AddToClassLoader(self, class_loader, dex_file.get())) {
267 LOG(ERROR) << "Unable to add " << descriptor << " to class loader!";
268 return;
269 }
270
271 // Actually set the ClassExt's original bytes once we have actually succeeded.
272 ext->SetOriginalDexFile(arr.Get());
273 // Set the return values
274 *final_class_def = &dex_file->GetClassDef(0);
275 *final_dex_file = dex_file.release();
276 }
277 }
278
ClassLoadopenjdkjvmti::ClassCallback279 void ClassLoad(art::Handle<art::mirror::Class> klass) override
280 REQUIRES_SHARED(art::Locks::mutator_lock_) {
281 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassLoad)) {
282 art::Thread* thread = art::Thread::Current();
283 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
284 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
285 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
286 ScopedLocalRef<jthread> thread_jni(
287 thread->GetJniEnv(),
288 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
289 event_handler->DispatchEvent<ArtJvmtiEvent::kClassLoad>(
290 thread,
291 static_cast<JNIEnv*>(thread->GetJniEnv()),
292 thread_jni.get(),
293 jklass.get());
294 if (klass->IsTemp()) {
295 AddTempClass(thread, jklass.get());
296 }
297 }
298 }
299
ClassPrepareopenjdkjvmti::ClassCallback300 void ClassPrepare(art::Handle<art::mirror::Class> temp_klass,
301 art::Handle<art::mirror::Class> klass)
302 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
303 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassPrepare)) {
304 art::Thread* thread = art::Thread::Current();
305 if (temp_klass.Get() != klass.Get()) {
306 DCHECK(temp_klass->IsTemp());
307 DCHECK(temp_klass->IsRetired());
308 HandleTempClass(thread, temp_klass, klass);
309 }
310 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
311 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
312 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
313 ScopedLocalRef<jthread> thread_jni(
314 thread->GetJniEnv(),
315 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
316 event_handler->DispatchEvent<ArtJvmtiEvent::kClassPrepare>(
317 thread,
318 static_cast<JNIEnv*>(thread->GetJniEnv()),
319 thread_jni.get(),
320 jklass.get());
321 }
322 }
323
324 // To support parallel class-loading, we need to perform some locking dances here. Namely,
325 // the fixup stage must not be holding the temp_classes lock when it fixes up the system
326 // (as that requires suspending all mutators).
327
AddTempClassopenjdkjvmti::ClassCallback328 void AddTempClass(art::Thread* self, jclass klass) {
329 std::unique_lock<std::mutex> mu(temp_classes_lock);
330 jclass global_klass = reinterpret_cast<jclass>(self->GetJniEnv()->NewGlobalRef(klass));
331 temp_classes.push_back(global_klass);
332 }
333
HandleTempClassopenjdkjvmti::ClassCallback334 void HandleTempClass(art::Thread* self,
335 art::Handle<art::mirror::Class> temp_klass,
336 art::Handle<art::mirror::Class> klass)
337 REQUIRES_SHARED(art::Locks::mutator_lock_) {
338 bool requires_fixup = false;
339 {
340 std::unique_lock<std::mutex> mu(temp_classes_lock);
341 if (temp_classes.empty()) {
342 return;
343 }
344
345 for (auto it = temp_classes.begin(); it != temp_classes.end(); ++it) {
346 if (temp_klass.Get() == art::ObjPtr<art::mirror::Class>::DownCast(self->DecodeJObject(*it))) {
347 self->GetJniEnv()->DeleteGlobalRef(*it);
348 temp_classes.erase(it);
349 requires_fixup = true;
350 break;
351 }
352 }
353 }
354 if (requires_fixup) {
355 FixupTempClass(self, temp_klass, klass);
356 }
357 }
358
FixupTempClassopenjdkjvmti::ClassCallback359 void FixupTempClass(art::Thread* self,
360 art::Handle<art::mirror::Class> temp_klass,
361 art::Handle<art::mirror::Class> klass)
362 REQUIRES_SHARED(art::Locks::mutator_lock_) {
363 // Suspend everything.
364 art::gc::Heap* heap = art::Runtime::Current()->GetHeap();
365 if (heap->IsGcConcurrentAndMoving()) {
366 // Need to take a heap dump while GC isn't running. See the
367 // comment in Heap::VisitObjects().
368 heap->IncrementDisableMovingGC(self);
369 }
370 {
371 art::ScopedThreadSuspension sts(self, art::kWaitingForVisitObjects);
372 art::ScopedSuspendAll ssa("FixupTempClass");
373
374 art::mirror::Class* input = temp_klass.Get();
375 art::mirror::Class* output = klass.Get();
376
377 FixupGlobalReferenceTables(input, output);
378 FixupLocalReferenceTables(self, input, output);
379 FixupHeap(input, output);
380 }
381 if (heap->IsGcConcurrentAndMoving()) {
382 heap->DecrementDisableMovingGC(self);
383 }
384 }
385
386 class RootUpdater : public art::RootVisitor {
387 public:
RootUpdater(const art::mirror::Class * input,art::mirror::Class * output)388 RootUpdater(const art::mirror::Class* input, art::mirror::Class* output)
389 : input_(input), output_(output) {}
390
VisitRoots(art::mirror::Object *** roots,size_t count,const art::RootInfo & info ATTRIBUTE_UNUSED)391 void VisitRoots(art::mirror::Object*** roots,
392 size_t count,
393 const art::RootInfo& info ATTRIBUTE_UNUSED)
394 override {
395 for (size_t i = 0; i != count; ++i) {
396 if (*roots[i] == input_) {
397 *roots[i] = output_;
398 }
399 }
400 }
401
VisitRoots(art::mirror::CompressedReference<art::mirror::Object> ** roots,size_t count,const art::RootInfo & info ATTRIBUTE_UNUSED)402 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
403 size_t count,
404 const art::RootInfo& info ATTRIBUTE_UNUSED)
405 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
406 for (size_t i = 0; i != count; ++i) {
407 if (roots[i]->AsMirrorPtr() == input_) {
408 roots[i]->Assign(output_);
409 }
410 }
411 }
412
413 private:
414 const art::mirror::Class* input_;
415 art::mirror::Class* output_;
416 };
417
FixupGlobalReferenceTablesopenjdkjvmti::ClassCallback418 void FixupGlobalReferenceTables(art::mirror::Class* input, art::mirror::Class* output)
419 REQUIRES(art::Locks::mutator_lock_) {
420 art::JavaVMExt* java_vm = art::Runtime::Current()->GetJavaVM();
421
422 // Fix up the global table with a root visitor.
423 RootUpdater global_update(input, output);
424 java_vm->VisitRoots(&global_update);
425
426 class WeakGlobalUpdate : public art::IsMarkedVisitor {
427 public:
428 WeakGlobalUpdate(art::mirror::Class* root_input, art::mirror::Class* root_output)
429 : input_(root_input), output_(root_output) {}
430
431 art::mirror::Object* IsMarked(art::mirror::Object* obj) override {
432 if (obj == input_) {
433 return output_;
434 }
435 return obj;
436 }
437
438 private:
439 const art::mirror::Class* input_;
440 art::mirror::Class* output_;
441 };
442 WeakGlobalUpdate weak_global_update(input, output);
443 java_vm->SweepJniWeakGlobals(&weak_global_update);
444 }
445
FixupLocalReferenceTablesopenjdkjvmti::ClassCallback446 void FixupLocalReferenceTables(art::Thread* self,
447 art::mirror::Class* input,
448 art::mirror::Class* output)
449 REQUIRES(art::Locks::mutator_lock_) {
450 class LocalUpdate {
451 public:
452 LocalUpdate(const art::mirror::Class* root_input, art::mirror::Class* root_output)
453 : input_(root_input), output_(root_output) {}
454
455 static void Callback(art::Thread* t, void* arg) REQUIRES(art::Locks::mutator_lock_) {
456 LocalUpdate* local = reinterpret_cast<LocalUpdate*>(arg);
457
458 // Fix up the local table with a root visitor.
459 RootUpdater local_update(local->input_, local->output_);
460 t->GetJniEnv()->VisitJniLocalRoots(
461 &local_update, art::RootInfo(art::kRootJNILocal, t->GetThreadId()));
462 }
463
464 private:
465 const art::mirror::Class* input_;
466 art::mirror::Class* output_;
467 };
468 LocalUpdate local_upd(input, output);
469 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
470 art::Runtime::Current()->GetThreadList()->ForEach(LocalUpdate::Callback, &local_upd);
471 }
472
FixupHeapopenjdkjvmti::ClassCallback473 void FixupHeap(art::mirror::Class* input, art::mirror::Class* output)
474 REQUIRES(art::Locks::mutator_lock_) {
475 class HeapFixupVisitor {
476 public:
477 HeapFixupVisitor(const art::mirror::Class* root_input, art::mirror::Class* root_output)
478 : input_(root_input), output_(root_output) {}
479
480 void operator()(art::mirror::Object* src,
481 art::MemberOffset field_offset,
482 bool is_static ATTRIBUTE_UNUSED) const
483 REQUIRES_SHARED(art::Locks::mutator_lock_) {
484 art::mirror::HeapReference<art::mirror::Object>* trg =
485 src->GetFieldObjectReferenceAddr(field_offset);
486 if (trg->AsMirrorPtr() == input_) {
487 DCHECK_NE(field_offset.Uint32Value(), 0u); // This shouldn't be the class field of
488 // an object.
489 trg->Assign(output_);
490 }
491 }
492
493 void operator()(art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
494 art::ObjPtr<art::mirror::Reference> reference) const
495 REQUIRES_SHARED(art::Locks::mutator_lock_) {
496 art::mirror::Object* val = reference->GetReferent();
497 if (val == input_) {
498 reference->SetReferent<false>(output_);
499 }
500 }
501
502 void VisitRoot(art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED)
503 const {
504 LOG(FATAL) << "Unreachable";
505 }
506
507 void VisitRootIfNonNull(
508 art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED) const {
509 LOG(FATAL) << "Unreachable";
510 }
511
512 private:
513 const art::mirror::Class* input_;
514 art::mirror::Class* output_;
515 };
516 HeapFixupVisitor hfv(input, output);
517 auto object_visitor = [&](art::mirror::Object* obj) {
518 obj->VisitReferences<false>(hfv, hfv); // Visit references, not native roots.
519 };
520 art::Runtime::Current()->GetHeap()->VisitObjectsPaused(object_visitor);
521 }
522
523 // A set of all the temp classes we have handed out. We have to fix up references to these.
524 // For simplicity, we store the temp classes as JNI global references in a vector. Normally a
525 // Prepare event will closely follow, so the vector should be small.
526 std::mutex temp_classes_lock;
527 std::vector<jclass> temp_classes;
528
529 EventHandler* event_handler = nullptr;
530 };
531
532 ClassCallback gClassCallback;
533
Register(EventHandler * handler)534 void ClassUtil::Register(EventHandler* handler) {
535 gClassCallback.event_handler = handler;
536 art::ScopedThreadStateChange stsc(art::Thread::Current(),
537 art::ThreadState::kWaitingForDebuggerToAttach);
538 art::ScopedSuspendAll ssa("Add load callback");
539 art::Runtime::Current()->GetRuntimeCallbacks()->AddClassLoadCallback(&gClassCallback);
540 }
541
Unregister()542 void ClassUtil::Unregister() {
543 art::ScopedThreadStateChange stsc(art::Thread::Current(),
544 art::ThreadState::kWaitingForDebuggerToAttach);
545 art::ScopedSuspendAll ssa("Remove thread callback");
546 art::Runtime* runtime = art::Runtime::Current();
547 runtime->GetRuntimeCallbacks()->RemoveClassLoadCallback(&gClassCallback);
548 }
549
GetClassFields(jvmtiEnv * env,jclass jklass,jint * field_count_ptr,jfieldID ** fields_ptr)550 jvmtiError ClassUtil::GetClassFields(jvmtiEnv* env,
551 jclass jklass,
552 jint* field_count_ptr,
553 jfieldID** fields_ptr) {
554 art::ScopedObjectAccess soa(art::Thread::Current());
555 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
556 if (klass == nullptr) {
557 return ERR(INVALID_CLASS);
558 }
559
560 // Check if this class is a temporary class object used for loading. Since we are seeing it the
561 // class must not have been prepared yet since otherwise the fixup would have gotten the jobject
562 // to point to the final class object.
563 if (klass->IsTemp() || klass->IsRetired()) {
564 return ERR(CLASS_NOT_PREPARED);
565 }
566
567 if (field_count_ptr == nullptr || fields_ptr == nullptr) {
568 return ERR(NULL_POINTER);
569 }
570
571 art::IterationRange<art::StrideIterator<art::ArtField>> ifields = klass->GetIFields();
572 art::IterationRange<art::StrideIterator<art::ArtField>> sfields = klass->GetSFields();
573 size_t array_size = klass->NumInstanceFields() + klass->NumStaticFields();
574
575 unsigned char* out_ptr;
576 jvmtiError allocError = env->Allocate(array_size * sizeof(jfieldID), &out_ptr);
577 if (allocError != ERR(NONE)) {
578 return allocError;
579 }
580 jfieldID* field_array = reinterpret_cast<jfieldID*>(out_ptr);
581
582 size_t array_idx = 0;
583 for (art::ArtField& field : sfields) {
584 field_array[array_idx] = art::jni::EncodeArtField(&field);
585 ++array_idx;
586 }
587 for (art::ArtField& field : ifields) {
588 field_array[array_idx] = art::jni::EncodeArtField(&field);
589 ++array_idx;
590 }
591
592 *field_count_ptr = static_cast<jint>(array_size);
593 *fields_ptr = field_array;
594
595 return ERR(NONE);
596 }
597
GetClassMethods(jvmtiEnv * env,jclass jklass,jint * method_count_ptr,jmethodID ** methods_ptr)598 jvmtiError ClassUtil::GetClassMethods(jvmtiEnv* env,
599 jclass jklass,
600 jint* method_count_ptr,
601 jmethodID** methods_ptr) {
602 art::ScopedObjectAccess soa(art::Thread::Current());
603 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
604 if (klass == nullptr) {
605 return ERR(INVALID_CLASS);
606 }
607
608 // Check if this class is a temporary class object used for loading. Since we are seeing it the
609 // class must not have been prepared yet since otherwise the fixup would have gotten the jobject
610 // to point to the final class object.
611 if (klass->IsTemp() || klass->IsRetired()) {
612 return ERR(CLASS_NOT_PREPARED);
613 }
614
615 if (method_count_ptr == nullptr || methods_ptr == nullptr) {
616 return ERR(NULL_POINTER);
617 }
618
619 size_t array_size = klass->NumDeclaredVirtualMethods() + klass->NumDirectMethods();
620 unsigned char* out_ptr;
621 jvmtiError allocError = env->Allocate(array_size * sizeof(jmethodID), &out_ptr);
622 if (allocError != ERR(NONE)) {
623 return allocError;
624 }
625 jmethodID* method_array = reinterpret_cast<jmethodID*>(out_ptr);
626
627 if (art::kIsDebugBuild) {
628 size_t count = 0;
629 for (auto& m ATTRIBUTE_UNUSED : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
630 count++;
631 }
632 CHECK_EQ(count, klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods());
633 }
634
635 size_t array_idx = 0;
636 for (auto& m : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
637 method_array[array_idx] = art::jni::EncodeArtMethod(&m);
638 ++array_idx;
639 }
640
641 *method_count_ptr = static_cast<jint>(array_size);
642 *methods_ptr = method_array;
643
644 return ERR(NONE);
645 }
646
GetImplementedInterfaces(jvmtiEnv * env,jclass jklass,jint * interface_count_ptr,jclass ** interfaces_ptr)647 jvmtiError ClassUtil::GetImplementedInterfaces(jvmtiEnv* env,
648 jclass jklass,
649 jint* interface_count_ptr,
650 jclass** interfaces_ptr) {
651 art::ScopedObjectAccess soa(art::Thread::Current());
652 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
653 if (klass == nullptr) {
654 return ERR(INVALID_CLASS);
655 }
656
657 if (interface_count_ptr == nullptr || interfaces_ptr == nullptr) {
658 return ERR(NULL_POINTER);
659 }
660
661 // Need to handle array specifically. Arrays implement Serializable and Cloneable, but the
662 // spec says these should not be reported.
663 if (klass->IsArrayClass()) {
664 *interface_count_ptr = 0;
665 *interfaces_ptr = nullptr; // TODO: Should we allocate a placeholder here?
666 return ERR(NONE);
667 }
668
669 size_t array_size = klass->NumDirectInterfaces();
670 unsigned char* out_ptr;
671 jvmtiError allocError = env->Allocate(array_size * sizeof(jclass), &out_ptr);
672 if (allocError != ERR(NONE)) {
673 return allocError;
674 }
675 jclass* interface_array = reinterpret_cast<jclass*>(out_ptr);
676
677 art::StackHandleScope<1> hs(soa.Self());
678 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
679
680 for (uint32_t idx = 0; idx != array_size; ++idx) {
681 art::ObjPtr<art::mirror::Class> inf_klass =
682 art::mirror::Class::ResolveDirectInterface(soa.Self(), h_klass, idx);
683 if (inf_klass == nullptr) {
684 soa.Self()->ClearException();
685 env->Deallocate(out_ptr);
686 // TODO: What is the right error code here?
687 return ERR(INTERNAL);
688 }
689 interface_array[idx] = soa.AddLocalReference<jclass>(inf_klass);
690 }
691
692 *interface_count_ptr = static_cast<jint>(array_size);
693 *interfaces_ptr = interface_array;
694
695 return ERR(NONE);
696 }
697
GetClassSignature(jvmtiEnv * env,jclass jklass,char ** signature_ptr,char ** generic_ptr)698 jvmtiError ClassUtil::GetClassSignature(jvmtiEnv* env,
699 jclass jklass,
700 char** signature_ptr,
701 char** generic_ptr) {
702 art::ScopedObjectAccess soa(art::Thread::Current());
703 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
704 if (klass == nullptr) {
705 return ERR(INVALID_CLASS);
706 }
707
708 JvmtiUniquePtr<char[]> sig_copy;
709 if (signature_ptr != nullptr) {
710 std::string storage;
711 const char* descriptor = klass->GetDescriptor(&storage);
712
713 jvmtiError ret;
714 sig_copy = CopyString(env, descriptor, &ret);
715 if (sig_copy == nullptr) {
716 return ret;
717 }
718 *signature_ptr = sig_copy.get();
719 }
720
721 if (generic_ptr != nullptr) {
722 *generic_ptr = nullptr;
723 if (!klass->IsProxyClass() && klass->GetDexCache() != nullptr) {
724 art::StackHandleScope<1> hs(soa.Self());
725 art::Handle<art::mirror::Class> h_klass = hs.NewHandle(klass);
726 art::ObjPtr<art::mirror::ObjectArray<art::mirror::String>> str_array =
727 art::annotations::GetSignatureAnnotationForClass(h_klass);
728 if (str_array != nullptr) {
729 std::ostringstream oss;
730 for (auto str : str_array->Iterate()) {
731 oss << str->ToModifiedUtf8();
732 }
733 std::string output_string = oss.str();
734 jvmtiError ret;
735 JvmtiUniquePtr<char[]> copy = CopyString(env, output_string.c_str(), &ret);
736 if (copy == nullptr) {
737 return ret;
738 }
739 *generic_ptr = copy.release();
740 } else if (soa.Self()->IsExceptionPending()) {
741 // TODO: Should we report an error here?
742 soa.Self()->ClearException();
743 }
744 }
745 }
746
747 // Everything is fine, release the buffers.
748 sig_copy.release();
749
750 return ERR(NONE);
751 }
752
GetClassStatus(jvmtiEnv * env ATTRIBUTE_UNUSED,jclass jklass,jint * status_ptr)753 jvmtiError ClassUtil::GetClassStatus(jvmtiEnv* env ATTRIBUTE_UNUSED,
754 jclass jklass,
755 jint* status_ptr) {
756 art::ScopedObjectAccess soa(art::Thread::Current());
757 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
758 if (klass == nullptr) {
759 return ERR(INVALID_CLASS);
760 }
761
762 if (status_ptr == nullptr) {
763 return ERR(NULL_POINTER);
764 }
765
766 if (klass->IsArrayClass()) {
767 *status_ptr = JVMTI_CLASS_STATUS_ARRAY;
768 } else if (klass->IsPrimitive()) {
769 *status_ptr = JVMTI_CLASS_STATUS_PRIMITIVE;
770 } else {
771 *status_ptr = JVMTI_CLASS_STATUS_VERIFIED; // All loaded classes are structurally verified.
772 // This is finicky. If there's an error, we'll say it wasn't prepared.
773 if (klass->IsResolved()) {
774 *status_ptr |= JVMTI_CLASS_STATUS_PREPARED;
775 }
776 if (klass->IsInitialized()) {
777 *status_ptr |= JVMTI_CLASS_STATUS_INITIALIZED;
778 }
779 // Technically the class may be erroneous for other reasons, but we do not have enough info.
780 if (klass->IsErroneous()) {
781 *status_ptr |= JVMTI_CLASS_STATUS_ERROR;
782 }
783 }
784
785 return ERR(NONE);
786 }
787
788 template <typename T>
ClassIsT(jclass jklass,T test,jboolean * is_t_ptr)789 static jvmtiError ClassIsT(jclass jklass, T test, jboolean* is_t_ptr) {
790 art::ScopedObjectAccess soa(art::Thread::Current());
791 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
792 if (klass == nullptr) {
793 return ERR(INVALID_CLASS);
794 }
795
796 if (is_t_ptr == nullptr) {
797 return ERR(NULL_POINTER);
798 }
799
800 *is_t_ptr = test(klass) ? JNI_TRUE : JNI_FALSE;
801 return ERR(NONE);
802 }
803
IsInterface(jvmtiEnv * env ATTRIBUTE_UNUSED,jclass jklass,jboolean * is_interface_ptr)804 jvmtiError ClassUtil::IsInterface(jvmtiEnv* env ATTRIBUTE_UNUSED,
805 jclass jklass,
806 jboolean* is_interface_ptr) {
807 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
808 return klass->IsInterface();
809 };
810 return ClassIsT(jklass, test, is_interface_ptr);
811 }
812
IsArrayClass(jvmtiEnv * env ATTRIBUTE_UNUSED,jclass jklass,jboolean * is_array_class_ptr)813 jvmtiError ClassUtil::IsArrayClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
814 jclass jklass,
815 jboolean* is_array_class_ptr) {
816 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
817 return klass->IsArrayClass();
818 };
819 return ClassIsT(jklass, test, is_array_class_ptr);
820 }
821
822 // Keep this in sync with Class.getModifiers().
ClassGetModifiers(art::Thread * self,art::ObjPtr<art::mirror::Class> klass)823 static uint32_t ClassGetModifiers(art::Thread* self, art::ObjPtr<art::mirror::Class> klass)
824 REQUIRES_SHARED(art::Locks::mutator_lock_) {
825 if (klass->IsArrayClass()) {
826 uint32_t component_modifiers = ClassGetModifiers(self, klass->GetComponentType());
827 if ((component_modifiers & art::kAccInterface) != 0) {
828 component_modifiers &= ~(art::kAccInterface | art::kAccStatic);
829 }
830 return art::kAccAbstract | art::kAccFinal | component_modifiers;
831 }
832
833 uint32_t modifiers = klass->GetAccessFlags() & art::kAccJavaFlagsMask;
834
835 art::StackHandleScope<1> hs(self);
836 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
837 return art::mirror::Class::GetInnerClassFlags(h_klass, modifiers);
838 }
839
GetClassModifiers(jvmtiEnv * env ATTRIBUTE_UNUSED,jclass jklass,jint * modifiers_ptr)840 jvmtiError ClassUtil::GetClassModifiers(jvmtiEnv* env ATTRIBUTE_UNUSED,
841 jclass jklass,
842 jint* modifiers_ptr) {
843 art::ScopedObjectAccess soa(art::Thread::Current());
844 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
845 if (klass == nullptr) {
846 return ERR(INVALID_CLASS);
847 }
848
849 if (modifiers_ptr == nullptr) {
850 return ERR(NULL_POINTER);
851 }
852
853 *modifiers_ptr = ClassGetModifiers(soa.Self(), klass);
854
855 return ERR(NONE);
856 }
857
GetClassLoader(jvmtiEnv * env ATTRIBUTE_UNUSED,jclass jklass,jobject * classloader_ptr)858 jvmtiError ClassUtil::GetClassLoader(jvmtiEnv* env ATTRIBUTE_UNUSED,
859 jclass jklass,
860 jobject* classloader_ptr) {
861 art::ScopedObjectAccess soa(art::Thread::Current());
862 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
863 if (klass == nullptr) {
864 return ERR(INVALID_CLASS);
865 }
866
867 if (classloader_ptr == nullptr) {
868 return ERR(NULL_POINTER);
869 }
870
871 *classloader_ptr = soa.AddLocalReference<jobject>(klass->GetClassLoader());
872
873 return ERR(NONE);
874 }
875
876 // Copies unique class descriptors into the classes list from dex_files.
CopyClassDescriptors(jvmtiEnv * env,const std::vector<const art::DexFile * > & dex_files,jint * count_ptr,char *** classes)877 static jvmtiError CopyClassDescriptors(jvmtiEnv* env,
878 const std::vector<const art::DexFile*>& dex_files,
879 /*out*/jint* count_ptr,
880 /*out*/char*** classes) {
881 jvmtiError res = OK;
882 std::set<std::string_view> unique_descriptors;
883 std::vector<const char*> descriptors;
884 auto add_descriptor = [&](const char* desc) {
885 // Don't add duplicates.
886 if (res == OK && unique_descriptors.find(desc) == unique_descriptors.end()) {
887 // The desc will remain valid since we hold a ref to the class_loader.
888 unique_descriptors.insert(desc);
889 descriptors.push_back(CopyString(env, desc, &res).release());
890 }
891 };
892 for (const art::DexFile* dex_file : dex_files) {
893 uint32_t num_defs = dex_file->NumClassDefs();
894 for (uint32_t i = 0; i < num_defs; i++) {
895 add_descriptor(dex_file->GetClassDescriptor(dex_file->GetClassDef(i)));
896 }
897 }
898 char** out_data = nullptr;
899 if (res == OK) {
900 res = env->Allocate(sizeof(char*) * descriptors.size(),
901 reinterpret_cast<unsigned char**>(&out_data));
902 }
903 if (res != OK) {
904 env->Deallocate(reinterpret_cast<unsigned char*>(out_data));
905 // Failed to allocate. Cleanup everything.
906 for (const char* data : descriptors) {
907 env->Deallocate(reinterpret_cast<unsigned char*>(const_cast<char*>(data)));
908 }
909 descriptors.clear();
910 return res;
911 }
912 // Everything is good.
913 memcpy(out_data, descriptors.data(), sizeof(char*) * descriptors.size());
914 *count_ptr = static_cast<jint>(descriptors.size());
915 *classes = out_data;
916 return OK;
917 }
918
GetClassLoaderClassDescriptors(jvmtiEnv * env,jobject loader,jint * count_ptr,char *** classes)919 jvmtiError ClassUtil::GetClassLoaderClassDescriptors(jvmtiEnv* env,
920 jobject loader,
921 /*out*/jint* count_ptr,
922 /*out*/char*** classes) {
923 art::Thread* self = art::Thread::Current();
924 if (env == nullptr) {
925 return ERR(INVALID_ENVIRONMENT);
926 } else if (self == nullptr) {
927 return ERR(UNATTACHED_THREAD);
928 } else if (count_ptr == nullptr || classes == nullptr) {
929 return ERR(NULL_POINTER);
930 }
931 art::JNIEnvExt* jnienv = self->GetJniEnv();
932 if (loader == nullptr ||
933 jnienv->IsInstanceOf(loader, art::WellKnownClasses::java_lang_BootClassLoader)) {
934 // We can just get the dex files directly for the boot class path.
935 return CopyClassDescriptors(env,
936 art::Runtime::Current()->GetClassLinker()->GetBootClassPath(),
937 count_ptr,
938 classes);
939 }
940 if (!jnienv->IsInstanceOf(loader, art::WellKnownClasses::java_lang_ClassLoader)) {
941 return ERR(ILLEGAL_ARGUMENT);
942 } else if (!jnienv->IsInstanceOf(loader,
943 art::WellKnownClasses::dalvik_system_BaseDexClassLoader)) {
944 JVMTI_LOG(ERROR, env) << "GetClassLoaderClassDescriptors is only implemented for "
945 << "BootClassPath and dalvik.system.BaseDexClassLoader class loaders";
946 // TODO Possibly return OK With no classes would be better since these ones cannot have any
947 // real classes associated with them.
948 return ERR(NOT_IMPLEMENTED);
949 }
950
951 art::ScopedObjectAccess soa(self);
952 art::StackHandleScope<1> hs(self);
953 art::Handle<art::mirror::ClassLoader> class_loader(
954 hs.NewHandle(soa.Decode<art::mirror::ClassLoader>(loader)));
955 std::vector<const art::DexFile*> dex_files;
956 art::VisitClassLoaderDexFiles(
957 soa,
958 class_loader,
959 [&](const art::DexFile* dex_file) {
960 dex_files.push_back(dex_file);
961 return true; // Continue with other dex files.
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
GetClassLoaderClasses(jvmtiEnv * env,jobject initiating_loader,jint * class_count_ptr,jclass ** classes_ptr)967 jvmtiError 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
GetClassVersionNumbers(jvmtiEnv * env ATTRIBUTE_UNUSED,jclass jklass,jint * minor_version_ptr,jint * major_version_ptr)1053 jvmtiError 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
GetSourceFileName(jvmtiEnv * env,jclass jklass,char ** source_name_ptr)1084 jvmtiError 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
GetSourceDebugExtension(jvmtiEnv * env,jclass jklass,char ** source_debug_extension_ptr)1111 jvmtiError 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
DisableHiddenApiEnforcementPolicy(jvmtiEnv * env)1141 jvmtiError ClassUtil::DisableHiddenApiEnforcementPolicy(jvmtiEnv* env) {
1142 return SetHiddenApiEnforcementPolicy(
1143 env, static_cast<jint>(art::hiddenapi::EnforcementPolicy::kDisabled));
1144 }
1145
GetHiddenApiEnforcementPolicy(jvmtiEnv * env,jint * policy)1146 jvmtiError ClassUtil::GetHiddenApiEnforcementPolicy(jvmtiEnv* env, jint* policy) {
1147 if (env == nullptr) {
1148 return ERR(INVALID_ENVIRONMENT);
1149 } else if (art::Thread::Current() == nullptr) {
1150 return ERR(UNATTACHED_THREAD);
1151 } else if (policy == nullptr) {
1152 return ERR(NULL_POINTER);
1153 }
1154 *policy = static_cast<jint>(art::Runtime::Current()->GetHiddenApiEnforcementPolicy());
1155 return OK;
1156 }
1157
SetHiddenApiEnforcementPolicy(jvmtiEnv * env,jint policy)1158 jvmtiError ClassUtil::SetHiddenApiEnforcementPolicy(jvmtiEnv* env, jint policy) {
1159 if (env == nullptr) {
1160 return ERR(INVALID_ENVIRONMENT);
1161 } else if (art::Thread::Current() == nullptr) {
1162 return ERR(UNATTACHED_THREAD);
1163 } else if (policy < static_cast<jint>(art::hiddenapi::EnforcementPolicy::kDisabled) ||
1164 policy > static_cast<jint>(art::hiddenapi::EnforcementPolicy::kMax)) {
1165 JVMTI_LOG(INFO, env) << "Bad policy: " << policy << ", must be between "
1166 << static_cast<jint>(art::hiddenapi::EnforcementPolicy::kDisabled)
1167 << " and " << static_cast<jint>(art::hiddenapi::EnforcementPolicy::kMax);
1168 return ERR(ILLEGAL_ARGUMENT);
1169 }
1170 art::Runtime::Current()->SetHiddenApiEnforcementPolicy(
1171 static_cast<art::hiddenapi::EnforcementPolicy>(policy));
1172 return OK;
1173 }
1174
1175 } // namespace openjdkjvmti
1176