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