blob: 1ed615bf3e85d698d8f00c77bcf674149c5b24ff [file] [log] [blame]
Andreas Gampee492ae32016-10-28 19:34:57 -07001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_class.h"
33
Alex Light440b5d92017-01-24 15:32:25 -080034#include "android-base/stringprintf.h"
35
Igor Murashkin5573c372017-11-16 13:34:30 -080036#include <mutex>
Andreas Gampee6377462017-01-20 17:37:50 -080037#include <unordered_set>
38
Andreas Gampee492ae32016-10-28 19:34:57 -070039#include "art_jvmti.h"
Vladimir Markoe1993c72017-06-14 17:01:38 +010040#include "base/array_ref.h"
Andreas Gampee6377462017-01-20 17:37:50 -080041#include "base/macros.h"
David Sehrc431b9d2018-03-02 12:01:51 -080042#include "base/utils.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080043#include "class_linker.h"
Andreas Gampeb8e7c372018-02-20 18:24:55 -080044#include "class_loader_utils.h"
Steven Morelande431e272017-07-18 16:53:49 -070045#include "class_table-inl.h"
Alex Light440b5d92017-01-24 15:32:25 -080046#include "common_throws.h"
David Sehr013fd802018-01-11 22:55:24 -080047#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080048#include "dex/dex_file_annotations.h"
49#include "dex/dex_file_loader.h"
David Sehr67bf42e2018-02-26 16:43:04 -080050#include "dex/primitive.h"
Andreas Gampee6377462017-01-20 17:37:50 -080051#include "events-inl.h"
Alex Light40528472017-03-28 09:07:36 -070052#include "fixed_up_dex_file.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070053#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070054#include "gc/heap.h"
Andreas Gampe691051b2017-02-09 09:15:24 -080055#include "gc_root.h"
Andreas Gampee6377462017-01-20 17:37:50 -080056#include "handle.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010057#include "jni/jni_env_ext-inl.h"
58#include "jni/jni_internal.h"
Alex Light440b5d92017-01-24 15:32:25 -080059#include "mirror/array-inl.h"
60#include "mirror/class-inl.h"
61#include "mirror/class_ext.h"
Andreas Gampea67354b2017-02-10 16:18:30 -080062#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080063#include "mirror/object-refvisitor-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070064#include "mirror/object_array-inl.h"
65#include "mirror/object_reference.h"
Vladimir Marko6834d342018-05-25 13:12:09 +010066#include "mirror/reference-inl.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070067#include "nativehelper/scoped_local_ref.h"
Alex Light6a656312017-03-29 17:18:00 -070068#include "reflection.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080069#include "runtime.h"
Andreas Gampee6377462017-01-20 17:37:50 -080070#include "runtime_callbacks.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070071#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070072#include "thread-current-inl.h"
Andreas Gampee6377462017-01-20 17:37:50 -080073#include "thread_list.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010074#include "ti_class_definition.h"
Alex Lightc7588752018-02-20 11:15:54 -080075#include "ti_class_loader-inl.h"
Alex Lightd8ce4e72017-02-27 10:52:29 -080076#include "ti_phase.h"
Alex Light440b5d92017-01-24 15:32:25 -080077#include "ti_redefine.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010078#include "transform.h"
Andreas Gampea1d2f952017-04-20 22:53:58 -070079#include "well_known_classes.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070080
81namespace openjdkjvmti {
82
Alex Light440b5d92017-01-24 15:32:25 -080083using android::base::StringPrintf;
84
85static std::unique_ptr<const art::DexFile> MakeSingleDexFile(art::Thread* self,
86 const char* descriptor,
87 const std::string& orig_location,
88 jint final_len,
89 const unsigned char* final_dex_data)
90 REQUIRES_SHARED(art::Locks::mutator_lock_) {
91 // Make the mmap
92 std::string error_msg;
Vladimir Markoe1993c72017-06-14 17:01:38 +010093 art::ArrayRef<const unsigned char> final_data(final_dex_data, final_len);
Vladimir Markoc34bebf2018-08-16 16:12:49 +010094 art::MemMap map = Redefiner::MoveDataToMemMap(orig_location, final_data, &error_msg);
95 if (!map.IsValid()) {
Alex Light440b5d92017-01-24 15:32:25 -080096 LOG(WARNING) << "Unable to allocate mmap for redefined dex file! Error was: " << error_msg;
97 self->ThrowOutOfMemoryError(StringPrintf(
98 "Unable to allocate dex file for transformation of %s", descriptor).c_str());
99 return nullptr;
100 }
101
102 // Make a dex-file
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100103 if (map.Size() < sizeof(art::DexFile::Header)) {
Alex Light440b5d92017-01-24 15:32:25 -0800104 LOG(WARNING) << "Could not read dex file header because dex_data was too short";
105 art::ThrowClassFormatError(nullptr,
106 "Unable to read transformed dex file of %s",
107 descriptor);
108 return nullptr;
109 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100110 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map.Begin())->checksum_;
111 std::string map_name = map.GetName();
David Sehr013fd802018-01-11 22:55:24 -0800112 const art::ArtDexFileLoader dex_file_loader;
113 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(map_name,
114 checksum,
115 std::move(map),
116 /*verify*/true,
117 /*verify_checksum*/true,
118 &error_msg));
Alex Light440b5d92017-01-24 15:32:25 -0800119 if (dex_file.get() == nullptr) {
120 LOG(WARNING) << "Unable to load modified dex file for " << descriptor << ": " << error_msg;
121 art::ThrowClassFormatError(nullptr,
122 "Unable to read transformed dex file of %s because %s",
123 descriptor,
124 error_msg.c_str());
125 return nullptr;
126 }
127 if (dex_file->NumClassDefs() != 1) {
128 LOG(WARNING) << "Dex file contains more than 1 class_def. Ignoring.";
129 // TODO Throw some other sort of error here maybe?
130 art::ThrowClassFormatError(
131 nullptr,
132 "Unable to use transformed dex file of %s because it contained too many classes",
133 descriptor);
134 return nullptr;
135 }
136 return dex_file;
137}
138
Alex Light28b6e7e2017-05-22 16:05:59 -0700139// A deleter that acts like the jvmtiEnv->Deallocate so that asan does not get tripped up.
140// TODO We should everything use the actual jvmtiEnv->Allocate/Deallocate functions once we can
141// figure out which env to use.
142template <typename T>
143class FakeJvmtiDeleter {
144 public:
145 FakeJvmtiDeleter() {}
146
147 FakeJvmtiDeleter(FakeJvmtiDeleter&) = default;
148 FakeJvmtiDeleter(FakeJvmtiDeleter&&) = default;
149 FakeJvmtiDeleter& operator=(const FakeJvmtiDeleter&) = default;
150
151 template <typename U> void operator()(const U* ptr) const {
152 if (ptr != nullptr) {
153 free(const_cast<U*>(ptr));
154 }
155 }
156};
157
Andreas Gampee6377462017-01-20 17:37:50 -0800158struct ClassCallback : public art::ClassLoadCallback {
Alex Light440b5d92017-01-24 15:32:25 -0800159 void ClassPreDefine(const char* descriptor,
160 art::Handle<art::mirror::Class> klass,
161 art::Handle<art::mirror::ClassLoader> class_loader,
162 const art::DexFile& initial_dex_file,
163 const art::DexFile::ClassDef& initial_class_def ATTRIBUTE_UNUSED,
164 /*out*/art::DexFile const** final_dex_file,
165 /*out*/art::DexFile::ClassDef const** final_class_def)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100166 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light440b5d92017-01-24 15:32:25 -0800167 bool is_enabled =
168 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookRetransformable) ||
169 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookNonRetransformable);
170 if (!is_enabled) {
171 return;
172 }
173 if (descriptor[0] != 'L') {
174 // It is a primitive or array. Just return
175 return;
176 }
Alex Lightd8ce4e72017-02-27 10:52:29 -0800177 jvmtiPhase phase = PhaseUtil::GetPhaseUnchecked();
178 if (UNLIKELY(phase != JVMTI_PHASE_START && phase != JVMTI_PHASE_LIVE)) {
179 // We want to wait until we are at least in the START phase so that all WellKnownClasses and
180 // mirror classes have been initialized and loaded. The runtime relies on these classes having
181 // specific fields and methods present. Since PreDefine hooks don't need to abide by this
182 // restriction we will simply not send the event for these classes.
183 LOG(WARNING) << "Ignoring load of class <" << descriptor << "> as it is being loaded during "
184 << "runtime initialization.";
185 return;
186 }
187
Alex Light440b5d92017-01-24 15:32:25 -0800188 art::Thread* self = art::Thread::Current();
Alex Light64e4c142018-01-30 13:46:37 -0800189 ArtClassDefinition def;
190 def.InitFirstLoad(descriptor, class_loader, initial_dex_file);
Alex Light40528472017-03-28 09:07:36 -0700191
Alex Light64e4c142018-01-30 13:46:37 -0800192 // Call all non-retransformable agents.
193 Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookNonRetransformable>(
194 event_handler, self, &def);
195
196 std::vector<unsigned char> post_non_retransform;
197 if (def.IsModified()) {
198 // Copy the dex data after the non-retransformable events.
199 post_non_retransform.resize(def.GetDexData().size());
200 memcpy(post_non_retransform.data(), def.GetDexData().data(), post_non_retransform.size());
Alex Light440b5d92017-01-24 15:32:25 -0800201 }
Alex Light64e4c142018-01-30 13:46:37 -0800202
Alex Light440b5d92017-01-24 15:32:25 -0800203 // Call all retransformable agents.
Alex Light64e4c142018-01-30 13:46:37 -0800204 Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
205 event_handler, self, &def);
Alex Light440b5d92017-01-24 15:32:25 -0800206
Alex Light64e4c142018-01-30 13:46:37 -0800207 if (def.IsModified()) {
Alex Light440b5d92017-01-24 15:32:25 -0800208 LOG(WARNING) << "Changing class " << descriptor;
Alex Light440b5d92017-01-24 15:32:25 -0800209 art::StackHandleScope<2> hs(self);
210 // Save the results of all the non-retransformable agents.
211 // First allocate the ClassExt
212 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(self)));
213 // Make sure we have a ClassExt. This is fine even though we are a temporary since it will
214 // get copied.
215 if (ext.IsNull()) {
216 // We will just return failure if we fail to allocate
217 LOG(WARNING) << "Could not allocate ext-data for class '" << descriptor << "'. "
218 << "Aborting transformation since we will be unable to store it.";
219 self->AssertPendingOOMException();
220 return;
221 }
222
223 // Allocate the byte array to store the dex file bytes in.
Alex Light6a656312017-03-29 17:18:00 -0700224 art::MutableHandle<art::mirror::Object> arr(hs.NewHandle<art::mirror::Object>(nullptr));
Alex Light64e4c142018-01-30 13:46:37 -0800225 if (post_non_retransform.empty() && strcmp(descriptor, "Ljava/lang/Long;") != 0) {
Alex Light6a656312017-03-29 17:18:00 -0700226 // we didn't have any non-retransformable agents. We can just cache a pointer to the
227 // initial_dex_file. It will be kept live by the class_loader.
228 jlong dex_ptr = reinterpret_cast<uintptr_t>(&initial_dex_file);
229 art::JValue val;
230 val.SetJ(dex_ptr);
231 arr.Assign(art::BoxPrimitive(art::Primitive::kPrimLong, val));
232 } else {
233 arr.Assign(art::mirror::ByteArray::AllocateAndFill(
234 self,
Alex Light64e4c142018-01-30 13:46:37 -0800235 reinterpret_cast<const signed char*>(post_non_retransform.data()),
236 post_non_retransform.size()));
Alex Light6a656312017-03-29 17:18:00 -0700237 }
Alex Light440b5d92017-01-24 15:32:25 -0800238 if (arr.IsNull()) {
Alex Light6a656312017-03-29 17:18:00 -0700239 LOG(WARNING) << "Unable to allocate memory for initial dex-file. Aborting transformation";
Alex Light440b5d92017-01-24 15:32:25 -0800240 self->AssertPendingOOMException();
241 return;
242 }
243
244 std::unique_ptr<const art::DexFile> dex_file(MakeSingleDexFile(self,
245 descriptor,
246 initial_dex_file.GetLocation(),
Alex Light64e4c142018-01-30 13:46:37 -0800247 def.GetDexData().size(),
248 def.GetDexData().data()));
Alex Light440b5d92017-01-24 15:32:25 -0800249 if (dex_file.get() == nullptr) {
250 return;
251 }
252
Alex Lighteb98b082017-01-25 13:02:32 -0800253 // TODO Check Redefined dex file for all invariants.
Alex Light440b5d92017-01-24 15:32:25 -0800254 LOG(WARNING) << "Dex file created by class-definition time transformation of "
255 << descriptor << " is not checked for all retransformation invariants.";
Alex Lighteb98b082017-01-25 13:02:32 -0800256
257 if (!ClassLoaderHelper::AddToClassLoader(self, class_loader, dex_file.get())) {
258 LOG(ERROR) << "Unable to add " << descriptor << " to class loader!";
259 return;
260 }
261
Alex Light440b5d92017-01-24 15:32:25 -0800262 // Actually set the ClassExt's original bytes once we have actually succeeded.
Alex Light2f814aa2017-03-24 15:21:34 +0000263 ext->SetOriginalDexFile(arr.Get());
Alex Light440b5d92017-01-24 15:32:25 -0800264 // Set the return values
265 *final_class_def = &dex_file->GetClassDef(0);
266 *final_dex_file = dex_file.release();
267 }
268 }
269
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700270 void ClassLoad(art::Handle<art::mirror::Class> klass) override
271 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampee6377462017-01-20 17:37:50 -0800272 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassLoad)) {
273 art::Thread* thread = art::Thread::Current();
274 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
275 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700276 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800277 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700278 thread->GetJniEnv(),
279 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Alex Light9df79b72017-09-12 08:57:31 -0700280 event_handler->DispatchEvent<ArtJvmtiEvent::kClassLoad>(
281 thread,
282 static_cast<JNIEnv*>(thread->GetJniEnv()),
283 thread_jni.get(),
284 jklass.get());
Andreas Gampe691051b2017-02-09 09:15:24 -0800285 if (klass->IsTemp()) {
286 AddTempClass(thread, jklass.get());
287 }
Andreas Gampee6377462017-01-20 17:37:50 -0800288 }
289 }
290
Andreas Gampe691051b2017-02-09 09:15:24 -0800291 void ClassPrepare(art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800292 art::Handle<art::mirror::Class> klass)
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700293 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampee6377462017-01-20 17:37:50 -0800294 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassPrepare)) {
295 art::Thread* thread = art::Thread::Current();
Andreas Gampe691051b2017-02-09 09:15:24 -0800296 if (temp_klass.Get() != klass.Get()) {
297 DCHECK(temp_klass->IsTemp());
298 DCHECK(temp_klass->IsRetired());
299 HandleTempClass(thread, temp_klass, klass);
300 }
Andreas Gampee6377462017-01-20 17:37:50 -0800301 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
302 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700303 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800304 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700305 thread->GetJniEnv(),
306 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Andreas Gampe983c1752017-01-23 19:46:56 -0800307 event_handler->DispatchEvent<ArtJvmtiEvent::kClassPrepare>(
308 thread,
309 static_cast<JNIEnv*>(thread->GetJniEnv()),
310 thread_jni.get(),
311 jklass.get());
Andreas Gampee6377462017-01-20 17:37:50 -0800312 }
313 }
314
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800315 // To support parallel class-loading, we need to perform some locking dances here. Namely,
316 // the fixup stage must not be holding the temp_classes lock when it fixes up the system
317 // (as that requires suspending all mutators).
318
Andreas Gampee6377462017-01-20 17:37:50 -0800319 void AddTempClass(art::Thread* self, jclass klass) {
320 std::unique_lock<std::mutex> mu(temp_classes_lock);
Andreas Gampe691051b2017-02-09 09:15:24 -0800321 jclass global_klass = reinterpret_cast<jclass>(self->GetJniEnv()->NewGlobalRef(klass));
322 temp_classes.push_back(global_klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800323 }
324
Andreas Gampe691051b2017-02-09 09:15:24 -0800325 void HandleTempClass(art::Thread* self,
326 art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800327 art::Handle<art::mirror::Class> klass)
328 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800329 bool requires_fixup = false;
330 {
331 std::unique_lock<std::mutex> mu(temp_classes_lock);
332 if (temp_classes.empty()) {
333 return;
Andreas Gampee6377462017-01-20 17:37:50 -0800334 }
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800335
336 for (auto it = temp_classes.begin(); it != temp_classes.end(); ++it) {
337 if (temp_klass.Get() == art::ObjPtr<art::mirror::Class>::DownCast(self->DecodeJObject(*it))) {
338 self->GetJniEnv()->DeleteGlobalRef(*it);
339 temp_classes.erase(it);
340 requires_fixup = true;
341 break;
342 }
343 }
344 }
345 if (requires_fixup) {
346 FixupTempClass(self, temp_klass, klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800347 }
348 }
349
Andreas Gampe691051b2017-02-09 09:15:24 -0800350 void FixupTempClass(art::Thread* self,
351 art::Handle<art::mirror::Class> temp_klass,
352 art::Handle<art::mirror::Class> klass)
Andreas Gampee6377462017-01-20 17:37:50 -0800353 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe691051b2017-02-09 09:15:24 -0800354 // Suspend everything.
355 art::gc::Heap* heap = art::Runtime::Current()->GetHeap();
356 if (heap->IsGcConcurrentAndMoving()) {
357 // Need to take a heap dump while GC isn't running. See the
358 // comment in Heap::VisitObjects().
359 heap->IncrementDisableMovingGC(self);
360 }
361 {
362 art::ScopedThreadSuspension sts(self, art::kWaitingForVisitObjects);
363 art::ScopedSuspendAll ssa("FixupTempClass");
364
365 art::mirror::Class* input = temp_klass.Get();
366 art::mirror::Class* output = klass.Get();
367
368 FixupGlobalReferenceTables(input, output);
Andreas Gampe94dda932017-02-09 18:19:21 -0800369 FixupLocalReferenceTables(self, input, output);
Andreas Gampea67354b2017-02-10 16:18:30 -0800370 FixupHeap(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800371 }
372 if (heap->IsGcConcurrentAndMoving()) {
373 heap->DecrementDisableMovingGC(self);
374 }
375 }
376
Andreas Gampe94dda932017-02-09 18:19:21 -0800377 class RootUpdater : public art::RootVisitor {
378 public:
379 RootUpdater(const art::mirror::Class* input, art::mirror::Class* output)
380 : input_(input), output_(output) {}
381
382 void VisitRoots(art::mirror::Object*** roots,
383 size_t count,
384 const art::RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100385 override {
Andreas Gampe94dda932017-02-09 18:19:21 -0800386 for (size_t i = 0; i != count; ++i) {
387 if (*roots[i] == input_) {
388 *roots[i] = output_;
389 }
390 }
391 }
392
393 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
394 size_t count,
395 const art::RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100396 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe94dda932017-02-09 18:19:21 -0800397 for (size_t i = 0; i != count; ++i) {
398 if (roots[i]->AsMirrorPtr() == input_) {
399 roots[i]->Assign(output_);
400 }
401 }
402 }
403
404 private:
405 const art::mirror::Class* input_;
406 art::mirror::Class* output_;
407 };
408
Andreas Gampea67354b2017-02-10 16:18:30 -0800409 void FixupGlobalReferenceTables(art::mirror::Class* input, art::mirror::Class* output)
Andreas Gampe691051b2017-02-09 09:15:24 -0800410 REQUIRES(art::Locks::mutator_lock_) {
411 art::JavaVMExt* java_vm = art::Runtime::Current()->GetJavaVM();
412
413 // Fix up the global table with a root visitor.
Andreas Gampe94dda932017-02-09 18:19:21 -0800414 RootUpdater global_update(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800415 java_vm->VisitRoots(&global_update);
416
417 class WeakGlobalUpdate : public art::IsMarkedVisitor {
418 public:
419 WeakGlobalUpdate(art::mirror::Class* root_input, art::mirror::Class* root_output)
420 : input_(root_input), output_(root_output) {}
421
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100422 art::mirror::Object* IsMarked(art::mirror::Object* obj) override {
Andreas Gampe691051b2017-02-09 09:15:24 -0800423 if (obj == input_) {
424 return output_;
425 }
426 return obj;
427 }
428
429 private:
430 const art::mirror::Class* input_;
431 art::mirror::Class* output_;
432 };
433 WeakGlobalUpdate weak_global_update(input, output);
434 java_vm->SweepJniWeakGlobals(&weak_global_update);
Andreas Gampee6377462017-01-20 17:37:50 -0800435 }
436
Andreas Gampe94dda932017-02-09 18:19:21 -0800437 void FixupLocalReferenceTables(art::Thread* self,
438 art::mirror::Class* input,
439 art::mirror::Class* output)
440 REQUIRES(art::Locks::mutator_lock_) {
441 class LocalUpdate {
442 public:
443 LocalUpdate(const art::mirror::Class* root_input, art::mirror::Class* root_output)
444 : input_(root_input), output_(root_output) {}
445
446 static void Callback(art::Thread* t, void* arg) REQUIRES(art::Locks::mutator_lock_) {
447 LocalUpdate* local = reinterpret_cast<LocalUpdate*>(arg);
448
449 // Fix up the local table with a root visitor.
450 RootUpdater local_update(local->input_, local->output_);
Ian Rogers55256cb2017-12-21 17:07:11 -0800451 t->GetJniEnv()->VisitJniLocalRoots(
Andreas Gampe94dda932017-02-09 18:19:21 -0800452 &local_update, art::RootInfo(art::kRootJNILocal, t->GetThreadId()));
453 }
454
455 private:
456 const art::mirror::Class* input_;
457 art::mirror::Class* output_;
458 };
459 LocalUpdate local_upd(input, output);
460 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
461 art::Runtime::Current()->GetThreadList()->ForEach(LocalUpdate::Callback, &local_upd);
462 }
463
Andreas Gampea67354b2017-02-10 16:18:30 -0800464 void FixupHeap(art::mirror::Class* input, art::mirror::Class* output)
465 REQUIRES(art::Locks::mutator_lock_) {
466 class HeapFixupVisitor {
467 public:
468 HeapFixupVisitor(const art::mirror::Class* root_input, art::mirror::Class* root_output)
469 : input_(root_input), output_(root_output) {}
470
471 void operator()(art::mirror::Object* src,
472 art::MemberOffset field_offset,
473 bool is_static ATTRIBUTE_UNUSED) const
474 REQUIRES_SHARED(art::Locks::mutator_lock_) {
475 art::mirror::HeapReference<art::mirror::Object>* trg =
476 src->GetFieldObjectReferenceAddr(field_offset);
477 if (trg->AsMirrorPtr() == input_) {
478 DCHECK_NE(field_offset.Uint32Value(), 0u); // This shouldn't be the class field of
479 // an object.
480 trg->Assign(output_);
481 }
482 }
483
Andreas Gampe52784ac2017-02-13 18:10:09 -0800484 void operator()(art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
485 art::ObjPtr<art::mirror::Reference> reference) const
486 REQUIRES_SHARED(art::Locks::mutator_lock_) {
487 art::mirror::Object* val = reference->GetReferent();
488 if (val == input_) {
489 reference->SetReferent<false>(output_);
490 }
491 }
492
Andreas Gampea67354b2017-02-10 16:18:30 -0800493 void VisitRoot(art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED)
Andreas Gampe52784ac2017-02-13 18:10:09 -0800494 const {
Andreas Gampea67354b2017-02-10 16:18:30 -0800495 LOG(FATAL) << "Unreachable";
496 }
497
498 void VisitRootIfNonNull(
499 art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED) const {
500 LOG(FATAL) << "Unreachable";
501 }
502
Andreas Gampea67354b2017-02-10 16:18:30 -0800503 private:
504 const art::mirror::Class* input_;
505 art::mirror::Class* output_;
506 };
507 HeapFixupVisitor hfv(input, output);
Andreas Gampe1c158a02017-07-13 17:26:19 -0700508 auto object_visitor = [&](art::mirror::Object* obj) {
509 obj->VisitReferences<false>(hfv, hfv); // Visit references, not native roots.
510 };
511 art::Runtime::Current()->GetHeap()->VisitObjectsPaused(object_visitor);
Andreas Gampea67354b2017-02-10 16:18:30 -0800512 }
513
Andreas Gampee6377462017-01-20 17:37:50 -0800514 // A set of all the temp classes we have handed out. We have to fix up references to these.
515 // For simplicity, we store the temp classes as JNI global references in a vector. Normally a
516 // Prepare event will closely follow, so the vector should be small.
517 std::mutex temp_classes_lock;
518 std::vector<jclass> temp_classes;
519
520 EventHandler* event_handler = nullptr;
521};
522
523ClassCallback gClassCallback;
524
525void ClassUtil::Register(EventHandler* handler) {
526 gClassCallback.event_handler = handler;
527 art::ScopedThreadStateChange stsc(art::Thread::Current(),
528 art::ThreadState::kWaitingForDebuggerToAttach);
529 art::ScopedSuspendAll ssa("Add load callback");
530 art::Runtime::Current()->GetRuntimeCallbacks()->AddClassLoadCallback(&gClassCallback);
531}
532
533void ClassUtil::Unregister() {
534 art::ScopedThreadStateChange stsc(art::Thread::Current(),
535 art::ThreadState::kWaitingForDebuggerToAttach);
536 art::ScopedSuspendAll ssa("Remove thread callback");
537 art::Runtime* runtime = art::Runtime::Current();
538 runtime->GetRuntimeCallbacks()->RemoveClassLoadCallback(&gClassCallback);
539}
540
Andreas Gampeac587272017-01-05 15:21:34 -0800541jvmtiError ClassUtil::GetClassFields(jvmtiEnv* env,
542 jclass jklass,
543 jint* field_count_ptr,
544 jfieldID** fields_ptr) {
545 art::ScopedObjectAccess soa(art::Thread::Current());
546 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
547 if (klass == nullptr) {
548 return ERR(INVALID_CLASS);
549 }
550
Alex Light2c6cd692017-06-30 07:34:40 -0700551 // Check if this class is a temporary class object used for loading. Since we are seeing it the
552 // class must not have been prepared yet since otherwise the fixup would have gotten the jobject
553 // to point to the final class object.
554 if (klass->IsTemp() || klass->IsRetired()) {
555 return ERR(CLASS_NOT_PREPARED);
556 }
557
Andreas Gampeac587272017-01-05 15:21:34 -0800558 if (field_count_ptr == nullptr || fields_ptr == nullptr) {
559 return ERR(NULL_POINTER);
560 }
561
Andreas Gampeac587272017-01-05 15:21:34 -0800562 art::IterationRange<art::StrideIterator<art::ArtField>> ifields = klass->GetIFields();
563 art::IterationRange<art::StrideIterator<art::ArtField>> sfields = klass->GetSFields();
564 size_t array_size = klass->NumInstanceFields() + klass->NumStaticFields();
565
566 unsigned char* out_ptr;
567 jvmtiError allocError = env->Allocate(array_size * sizeof(jfieldID), &out_ptr);
568 if (allocError != ERR(NONE)) {
569 return allocError;
570 }
571 jfieldID* field_array = reinterpret_cast<jfieldID*>(out_ptr);
572
573 size_t array_idx = 0;
574 for (art::ArtField& field : sfields) {
575 field_array[array_idx] = art::jni::EncodeArtField(&field);
576 ++array_idx;
577 }
578 for (art::ArtField& field : ifields) {
579 field_array[array_idx] = art::jni::EncodeArtField(&field);
580 ++array_idx;
581 }
582
583 *field_count_ptr = static_cast<jint>(array_size);
584 *fields_ptr = field_array;
585
586 return ERR(NONE);
587}
588
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800589jvmtiError ClassUtil::GetClassMethods(jvmtiEnv* env,
590 jclass jklass,
591 jint* method_count_ptr,
592 jmethodID** methods_ptr) {
593 art::ScopedObjectAccess soa(art::Thread::Current());
594 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
595 if (klass == nullptr) {
596 return ERR(INVALID_CLASS);
597 }
598
Alex Light2c6cd692017-06-30 07:34:40 -0700599 // Check if this class is a temporary class object used for loading. Since we are seeing it the
600 // class must not have been prepared yet since otherwise the fixup would have gotten the jobject
601 // to point to the final class object.
602 if (klass->IsTemp() || klass->IsRetired()) {
603 return ERR(CLASS_NOT_PREPARED);
604 }
605
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800606 if (method_count_ptr == nullptr || methods_ptr == nullptr) {
607 return ERR(NULL_POINTER);
608 }
609
610 size_t array_size = klass->NumDeclaredVirtualMethods() + klass->NumDirectMethods();
611 unsigned char* out_ptr;
612 jvmtiError allocError = env->Allocate(array_size * sizeof(jmethodID), &out_ptr);
613 if (allocError != ERR(NONE)) {
614 return allocError;
615 }
616 jmethodID* method_array = reinterpret_cast<jmethodID*>(out_ptr);
617
618 if (art::kIsDebugBuild) {
619 size_t count = 0;
620 for (auto& m ATTRIBUTE_UNUSED : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
621 count++;
622 }
623 CHECK_EQ(count, klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods());
624 }
625
626 size_t array_idx = 0;
627 for (auto& m : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
628 method_array[array_idx] = art::jni::EncodeArtMethod(&m);
629 ++array_idx;
630 }
631
632 *method_count_ptr = static_cast<jint>(array_size);
633 *methods_ptr = method_array;
634
635 return ERR(NONE);
636}
637
Andreas Gampe8b07e472017-01-06 14:20:39 -0800638jvmtiError ClassUtil::GetImplementedInterfaces(jvmtiEnv* env,
639 jclass jklass,
640 jint* interface_count_ptr,
641 jclass** interfaces_ptr) {
642 art::ScopedObjectAccess soa(art::Thread::Current());
643 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
644 if (klass == nullptr) {
645 return ERR(INVALID_CLASS);
646 }
647
648 if (interface_count_ptr == nullptr || interfaces_ptr == nullptr) {
649 return ERR(NULL_POINTER);
650 }
651
652 // Need to handle array specifically. Arrays implement Serializable and Cloneable, but the
653 // spec says these should not be reported.
654 if (klass->IsArrayClass()) {
655 *interface_count_ptr = 0;
656 *interfaces_ptr = nullptr; // TODO: Should we allocate a dummy here?
657 return ERR(NONE);
658 }
659
660 size_t array_size = klass->NumDirectInterfaces();
661 unsigned char* out_ptr;
662 jvmtiError allocError = env->Allocate(array_size * sizeof(jclass), &out_ptr);
663 if (allocError != ERR(NONE)) {
664 return allocError;
665 }
666 jclass* interface_array = reinterpret_cast<jclass*>(out_ptr);
667
668 art::StackHandleScope<1> hs(soa.Self());
669 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
670
671 for (uint32_t idx = 0; idx != array_size; ++idx) {
672 art::ObjPtr<art::mirror::Class> inf_klass =
673 art::mirror::Class::ResolveDirectInterface(soa.Self(), h_klass, idx);
674 if (inf_klass == nullptr) {
675 soa.Self()->ClearException();
676 env->Deallocate(out_ptr);
677 // TODO: What is the right error code here?
678 return ERR(INTERNAL);
679 }
680 interface_array[idx] = soa.AddLocalReference<jclass>(inf_klass);
681 }
682
683 *interface_count_ptr = static_cast<jint>(array_size);
684 *interfaces_ptr = interface_array;
685
686 return ERR(NONE);
687}
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800688
Andreas Gampee492ae32016-10-28 19:34:57 -0700689jvmtiError ClassUtil::GetClassSignature(jvmtiEnv* env,
690 jclass jklass,
691 char** signature_ptr,
692 char** generic_ptr) {
693 art::ScopedObjectAccess soa(art::Thread::Current());
694 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
695 if (klass == nullptr) {
696 return ERR(INVALID_CLASS);
697 }
698
Andreas Gampe54711412017-02-21 12:41:43 -0800699 JvmtiUniquePtr<char[]> sig_copy;
Andreas Gampee492ae32016-10-28 19:34:57 -0700700 if (signature_ptr != nullptr) {
701 std::string storage;
702 const char* descriptor = klass->GetDescriptor(&storage);
703
Andreas Gampe54711412017-02-21 12:41:43 -0800704 jvmtiError ret;
705 sig_copy = CopyString(env, descriptor, &ret);
706 if (sig_copy == nullptr) {
Andreas Gampee492ae32016-10-28 19:34:57 -0700707 return ret;
708 }
Andreas Gampe54711412017-02-21 12:41:43 -0800709 *signature_ptr = sig_copy.get();
Andreas Gampee492ae32016-10-28 19:34:57 -0700710 }
711
Andreas Gampee6377462017-01-20 17:37:50 -0800712 if (generic_ptr != nullptr) {
713 *generic_ptr = nullptr;
Andreas Gampe0eb36432017-02-15 18:36:14 -0800714 if (!klass->IsProxyClass() && klass->GetDexCache() != nullptr) {
715 art::StackHandleScope<1> hs(soa.Self());
716 art::Handle<art::mirror::Class> h_klass = hs.NewHandle(klass);
Vladimir Markoacb906d2018-05-30 10:23:49 +0100717 art::ObjPtr<art::mirror::ObjectArray<art::mirror::String>> str_array =
Andreas Gampe0eb36432017-02-15 18:36:14 -0800718 art::annotations::GetSignatureAnnotationForClass(h_klass);
719 if (str_array != nullptr) {
720 std::ostringstream oss;
721 for (int32_t i = 0; i != str_array->GetLength(); ++i) {
722 oss << str_array->Get(i)->ToModifiedUtf8();
723 }
724 std::string output_string = oss.str();
Andreas Gampe54711412017-02-21 12:41:43 -0800725 jvmtiError ret;
726 JvmtiUniquePtr<char[]> copy = CopyString(env, output_string.c_str(), &ret);
727 if (copy == nullptr) {
Andreas Gampe0eb36432017-02-15 18:36:14 -0800728 return ret;
729 }
Andreas Gampe54711412017-02-21 12:41:43 -0800730 *generic_ptr = copy.release();
Andreas Gampe0eb36432017-02-15 18:36:14 -0800731 } else if (soa.Self()->IsExceptionPending()) {
732 // TODO: Should we report an error here?
733 soa.Self()->ClearException();
734 }
735 }
Andreas Gampee6377462017-01-20 17:37:50 -0800736 }
Andreas Gampee492ae32016-10-28 19:34:57 -0700737
738 // Everything is fine, release the buffers.
739 sig_copy.release();
740
741 return ERR(NONE);
742}
743
Andreas Gampeff9d2092017-01-06 09:12:49 -0800744jvmtiError ClassUtil::GetClassStatus(jvmtiEnv* env ATTRIBUTE_UNUSED,
745 jclass jklass,
746 jint* status_ptr) {
747 art::ScopedObjectAccess soa(art::Thread::Current());
748 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
749 if (klass == nullptr) {
750 return ERR(INVALID_CLASS);
751 }
752
753 if (status_ptr == nullptr) {
754 return ERR(NULL_POINTER);
755 }
756
757 if (klass->IsArrayClass()) {
758 *status_ptr = JVMTI_CLASS_STATUS_ARRAY;
759 } else if (klass->IsPrimitive()) {
760 *status_ptr = JVMTI_CLASS_STATUS_PRIMITIVE;
761 } else {
762 *status_ptr = JVMTI_CLASS_STATUS_VERIFIED; // All loaded classes are structurally verified.
763 // This is finicky. If there's an error, we'll say it wasn't prepared.
764 if (klass->IsResolved()) {
765 *status_ptr |= JVMTI_CLASS_STATUS_PREPARED;
766 }
767 if (klass->IsInitialized()) {
768 *status_ptr |= JVMTI_CLASS_STATUS_INITIALIZED;
769 }
770 // Technically the class may be erroneous for other reasons, but we do not have enough info.
771 if (klass->IsErroneous()) {
772 *status_ptr |= JVMTI_CLASS_STATUS_ERROR;
773 }
774 }
775
776 return ERR(NONE);
777}
778
Andreas Gampe4fd66ec2017-01-05 14:42:13 -0800779template <typename T>
780static jvmtiError ClassIsT(jclass jklass, T test, jboolean* is_t_ptr) {
781 art::ScopedObjectAccess soa(art::Thread::Current());
782 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
783 if (klass == nullptr) {
784 return ERR(INVALID_CLASS);
785 }
786
787 if (is_t_ptr == nullptr) {
788 return ERR(NULL_POINTER);
789 }
790
791 *is_t_ptr = test(klass) ? JNI_TRUE : JNI_FALSE;
792 return ERR(NONE);
793}
794
795jvmtiError ClassUtil::IsInterface(jvmtiEnv* env ATTRIBUTE_UNUSED,
796 jclass jklass,
797 jboolean* is_interface_ptr) {
798 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
799 return klass->IsInterface();
800 };
801 return ClassIsT(jklass, test, is_interface_ptr);
802}
803
804jvmtiError ClassUtil::IsArrayClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
805 jclass jklass,
806 jboolean* is_array_class_ptr) {
807 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
808 return klass->IsArrayClass();
809 };
810 return ClassIsT(jklass, test, is_array_class_ptr);
811}
812
Andreas Gampe64013e52017-01-06 13:07:19 -0800813// Keep this in sync with Class.getModifiers().
814static uint32_t ClassGetModifiers(art::Thread* self, art::ObjPtr<art::mirror::Class> klass)
815 REQUIRES_SHARED(art::Locks::mutator_lock_) {
816 if (klass->IsArrayClass()) {
817 uint32_t component_modifiers = ClassGetModifiers(self, klass->GetComponentType());
818 if ((component_modifiers & art::kAccInterface) != 0) {
819 component_modifiers &= ~(art::kAccInterface | art::kAccStatic);
820 }
821 return art::kAccAbstract | art::kAccFinal | component_modifiers;
822 }
823
824 uint32_t modifiers = klass->GetAccessFlags() & art::kAccJavaFlagsMask;
825
826 art::StackHandleScope<1> hs(self);
827 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
828 return art::mirror::Class::GetInnerClassFlags(h_klass, modifiers);
829}
830
831jvmtiError ClassUtil::GetClassModifiers(jvmtiEnv* env ATTRIBUTE_UNUSED,
832 jclass jklass,
833 jint* modifiers_ptr) {
834 art::ScopedObjectAccess soa(art::Thread::Current());
835 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
836 if (klass == nullptr) {
837 return ERR(INVALID_CLASS);
838 }
839
840 if (modifiers_ptr == nullptr) {
841 return ERR(NULL_POINTER);
842 }
843
844 *modifiers_ptr = ClassGetModifiers(soa.Self(), klass);
845
846 return ERR(NONE);
847}
848
Andreas Gampe8f5b6032017-01-06 15:50:55 -0800849jvmtiError ClassUtil::GetClassLoader(jvmtiEnv* env ATTRIBUTE_UNUSED,
850 jclass jklass,
851 jobject* classloader_ptr) {
852 art::ScopedObjectAccess soa(art::Thread::Current());
853 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
854 if (klass == nullptr) {
855 return ERR(INVALID_CLASS);
856 }
857
858 if (classloader_ptr == nullptr) {
859 return ERR(NULL_POINTER);
860 }
861
862 *classloader_ptr = soa.AddLocalReference<jobject>(klass->GetClassLoader());
863
864 return ERR(NONE);
865}
866
Alex Lightc7588752018-02-20 11:15:54 -0800867// Copies unique class descriptors into the classes list from dex_files.
868static jvmtiError CopyClassDescriptors(jvmtiEnv* env,
869 const std::vector<const art::DexFile*>& dex_files,
870 /*out*/jint* count_ptr,
871 /*out*/char*** classes) {
872 jvmtiError res = OK;
873 std::set<art::StringPiece> unique_descriptors;
874 std::vector<const char*> descriptors;
875 auto add_descriptor = [&](const char* desc) {
876 // Don't add duplicates.
877 if (res == OK && unique_descriptors.find(desc) == unique_descriptors.end()) {
878 // The desc will remain valid since we hold a ref to the class_loader.
879 unique_descriptors.insert(desc);
880 descriptors.push_back(CopyString(env, desc, &res).release());
881 }
882 };
883 for (const art::DexFile* dex_file : dex_files) {
884 uint32_t num_defs = dex_file->NumClassDefs();
885 for (uint32_t i = 0; i < num_defs; i++) {
886 add_descriptor(dex_file->GetClassDescriptor(dex_file->GetClassDef(i)));
887 }
888 }
889 char** out_data = nullptr;
890 if (res == OK) {
891 res = env->Allocate(sizeof(char*) * descriptors.size(),
892 reinterpret_cast<unsigned char**>(&out_data));
893 }
894 if (res != OK) {
895 env->Deallocate(reinterpret_cast<unsigned char*>(out_data));
896 // Failed to allocate. Cleanup everything.
897 for (const char* data : descriptors) {
898 env->Deallocate(reinterpret_cast<unsigned char*>(const_cast<char*>(data)));
899 }
900 descriptors.clear();
901 return res;
902 }
903 // Everything is good.
904 memcpy(out_data, descriptors.data(), sizeof(char*) * descriptors.size());
905 *count_ptr = static_cast<jint>(descriptors.size());
906 *classes = out_data;
907 return OK;
908}
909
910jvmtiError ClassUtil::GetClassLoaderClassDescriptors(jvmtiEnv* env,
911 jobject loader,
912 /*out*/jint* count_ptr,
913 /*out*/char*** classes) {
914 art::Thread* self = art::Thread::Current();
915 if (env == nullptr) {
916 return ERR(INVALID_ENVIRONMENT);
917 } else if (self == nullptr) {
918 return ERR(UNATTACHED_THREAD);
919 } else if (count_ptr == nullptr || classes == nullptr) {
920 return ERR(NULL_POINTER);
921 }
922 art::JNIEnvExt* jnienv = self->GetJniEnv();
923 if (loader == nullptr ||
924 jnienv->IsInstanceOf(loader, art::WellKnownClasses::java_lang_BootClassLoader)) {
925 // We can just get the dex files directly for the boot class path.
926 return CopyClassDescriptors(env,
927 art::Runtime::Current()->GetClassLinker()->GetBootClassPath(),
928 count_ptr,
929 classes);
930 }
931 if (!jnienv->IsInstanceOf(loader, art::WellKnownClasses::java_lang_ClassLoader)) {
932 return ERR(ILLEGAL_ARGUMENT);
933 } else if (!jnienv->IsInstanceOf(loader,
934 art::WellKnownClasses::dalvik_system_BaseDexClassLoader)) {
935 LOG(ERROR) << "GetClassLoaderClassDescriptors is only implemented for BootClassPath and "
936 << "dalvik.system.BaseDexClassLoader class loaders";
937 // TODO Possibly return OK With no classes would be better since these ones cannot have any
938 // real classes associated with them.
939 return ERR(NOT_IMPLEMENTED);
940 }
941
942 art::ScopedObjectAccess soa(self);
943 art::StackHandleScope<1> hs(self);
944 art::Handle<art::mirror::ClassLoader> class_loader(
945 hs.NewHandle(soa.Decode<art::mirror::ClassLoader>(loader)));
946 std::vector<const art::DexFile*> dex_files;
Andreas Gampeb8e7c372018-02-20 18:24:55 -0800947 art::VisitClassLoaderDexFiles(
948 soa,
Alex Lightc7588752018-02-20 11:15:54 -0800949 class_loader,
Andreas Gampeb8e7c372018-02-20 18:24:55 -0800950 [&](const art::DexFile* dex_file) {
951 dex_files.push_back(dex_file);
952 return true; // Continue with other dex files.
Alex Lightc7588752018-02-20 11:15:54 -0800953 });
954 // We hold the loader so the dex files won't go away until after this call at worst.
955 return CopyClassDescriptors(env, dex_files, count_ptr, classes);
956}
957
Andreas Gampe70f16392017-01-16 14:20:10 -0800958jvmtiError ClassUtil::GetClassLoaderClasses(jvmtiEnv* env,
959 jobject initiating_loader,
960 jint* class_count_ptr,
961 jclass** classes_ptr) {
962 UNUSED(env, initiating_loader, class_count_ptr, classes_ptr);
963
964 if (class_count_ptr == nullptr || classes_ptr == nullptr) {
965 return ERR(NULL_POINTER);
966 }
967 art::Thread* self = art::Thread::Current();
968 if (!self->GetJniEnv()->IsInstanceOf(initiating_loader,
969 art::WellKnownClasses::java_lang_ClassLoader)) {
970 return ERR(ILLEGAL_ARGUMENT);
971 }
972 if (self->GetJniEnv()->IsInstanceOf(initiating_loader,
973 art::WellKnownClasses::java_lang_BootClassLoader)) {
974 // Need to use null for the BootClassLoader.
975 initiating_loader = nullptr;
976 }
977
978 art::ScopedObjectAccess soa(self);
979 art::ObjPtr<art::mirror::ClassLoader> class_loader =
980 soa.Decode<art::mirror::ClassLoader>(initiating_loader);
981
982 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
983
984 art::ReaderMutexLock mu(self, *art::Locks::classlinker_classes_lock_);
985
986 art::ClassTable* class_table = class_linker->ClassTableForClassLoader(class_loader);
987 if (class_table == nullptr) {
988 // Nothing loaded.
989 *class_count_ptr = 0;
990 *classes_ptr = nullptr;
991 return ERR(NONE);
992 }
993
994 struct ClassTableCount {
995 bool operator()(art::ObjPtr<art::mirror::Class> klass) {
996 DCHECK(klass != nullptr);
997 ++count;
998 return true;
999 }
1000
1001 size_t count = 0;
1002 };
1003 ClassTableCount ctc;
1004 class_table->Visit(ctc);
1005
1006 if (ctc.count == 0) {
1007 // Nothing loaded.
1008 *class_count_ptr = 0;
1009 *classes_ptr = nullptr;
1010 return ERR(NONE);
1011 }
1012
1013 unsigned char* data;
1014 jvmtiError data_result = env->Allocate(ctc.count * sizeof(jclass), &data);
1015 if (data_result != ERR(NONE)) {
1016 return data_result;
1017 }
1018 jclass* class_array = reinterpret_cast<jclass*>(data);
1019
1020 struct ClassTableFill {
1021 bool operator()(art::ObjPtr<art::mirror::Class> klass)
1022 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1023 DCHECK(klass != nullptr);
1024 DCHECK_LT(count, ctc_ref.count);
1025 local_class_array[count++] = soa_ptr->AddLocalReference<jclass>(klass);
1026 return true;
1027 }
1028
1029 jclass* local_class_array;
1030 const ClassTableCount& ctc_ref;
1031 art::ScopedObjectAccess* soa_ptr;
1032 size_t count;
1033 };
1034 ClassTableFill ctf = { class_array, ctc, &soa, 0 };
1035 class_table->Visit(ctf);
1036 DCHECK_EQ(ctc.count, ctf.count);
1037
1038 *class_count_ptr = ctc.count;
1039 *classes_ptr = class_array;
1040
1041 return ERR(NONE);
1042}
1043
Andreas Gampe812a2442017-01-19 22:04:46 -08001044jvmtiError ClassUtil::GetClassVersionNumbers(jvmtiEnv* env ATTRIBUTE_UNUSED,
1045 jclass jklass,
1046 jint* minor_version_ptr,
1047 jint* major_version_ptr) {
1048 art::ScopedObjectAccess soa(art::Thread::Current());
1049 if (jklass == nullptr) {
1050 return ERR(INVALID_CLASS);
1051 }
1052 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1053 if (!jklass_obj->IsClass()) {
1054 return ERR(INVALID_CLASS);
1055 }
1056 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
1057 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1058 return ERR(INVALID_CLASS);
1059 }
1060
1061 if (minor_version_ptr == nullptr || major_version_ptr == nullptr) {
1062 return ERR(NULL_POINTER);
1063 }
1064
1065 // Note: proxies will show the dex file version of java.lang.reflect.Proxy, as that is
1066 // what their dex cache copies from.
1067 uint32_t version = klass->GetDexFile().GetHeader().GetVersion();
1068
1069 *major_version_ptr = static_cast<jint>(version);
1070 *minor_version_ptr = 0;
1071
1072 return ERR(NONE);
1073}
1074
Alex Light6fa7b812017-06-16 09:04:29 -07001075jvmtiError ClassUtil::GetSourceFileName(jvmtiEnv* env, jclass jklass, char** source_name_ptr) {
1076 art::ScopedObjectAccess soa(art::Thread::Current());
1077 if (jklass == nullptr) {
1078 return ERR(INVALID_CLASS);
1079 }
1080 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1081 if (!jklass_obj->IsClass()) {
1082 return ERR(INVALID_CLASS);
1083 }
1084 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
1085 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1086 return ERR(ABSENT_INFORMATION);
1087 }
1088 JvmtiUniquePtr<char[]> source_copy;
1089 const char* file_name = klass->GetSourceFile();
1090 if (file_name == nullptr) {
1091 return ERR(ABSENT_INFORMATION);
1092 }
1093 jvmtiError ret;
1094 source_copy = CopyString(env, file_name, &ret);
1095 if (source_copy == nullptr) {
1096 return ret;
1097 }
1098 *source_name_ptr = source_copy.release();
1099 return OK;
1100}
1101
1102jvmtiError ClassUtil::GetSourceDebugExtension(jvmtiEnv* env,
1103 jclass jklass,
1104 char** source_debug_extension_ptr) {
1105 art::ScopedObjectAccess soa(art::Thread::Current());
1106 if (jklass == nullptr) {
1107 return ERR(INVALID_CLASS);
1108 }
1109 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1110 if (!jklass_obj->IsClass()) {
1111 return ERR(INVALID_CLASS);
1112 }
1113 art::StackHandleScope<1> hs(art::Thread::Current());
1114 art::Handle<art::mirror::Class> klass(hs.NewHandle(jklass_obj->AsClass()));
1115 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1116 return ERR(ABSENT_INFORMATION);
1117 }
1118 JvmtiUniquePtr<char[]> ext_copy;
1119 const char* data = art::annotations::GetSourceDebugExtension(klass);
1120 if (data == nullptr) {
1121 return ERR(ABSENT_INFORMATION);
1122 }
1123 jvmtiError ret;
1124 ext_copy = CopyString(env, data, &ret);
1125 if (ext_copy == nullptr) {
1126 return ret;
1127 }
1128 *source_debug_extension_ptr = ext_copy.release();
1129 return OK;
1130}
1131
Andreas Gampee492ae32016-10-28 19:34:57 -07001132} // namespace openjdkjvmti