blob: 3ad1112509bf046c1fe08825ad808466391f5c10 [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>
Vladimir Marko2ef01102019-02-05 15:05:10 +000037#include <string_view>
Andreas Gampee6377462017-01-20 17:37:50 -080038#include <unordered_set>
39
Andreas Gampee492ae32016-10-28 19:34:57 -070040#include "art_jvmti.h"
Vladimir Markoe1993c72017-06-14 17:01:38 +010041#include "base/array_ref.h"
Andreas Gampee6377462017-01-20 17:37:50 -080042#include "base/macros.h"
David Sehrc431b9d2018-03-02 12:01:51 -080043#include "base/utils.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080044#include "class_linker.h"
Andreas Gampeb8e7c372018-02-20 18:24:55 -080045#include "class_loader_utils.h"
Steven Morelande431e272017-07-18 16:53:49 -070046#include "class_table-inl.h"
Alex Light440b5d92017-01-24 15:32:25 -080047#include "common_throws.h"
David Sehr013fd802018-01-11 22:55:24 -080048#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080049#include "dex/dex_file_annotations.h"
50#include "dex/dex_file_loader.h"
David Sehr67bf42e2018-02-26 16:43:04 -080051#include "dex/primitive.h"
Andreas Gampee6377462017-01-20 17:37:50 -080052#include "events-inl.h"
Alex Light40528472017-03-28 09:07:36 -070053#include "fixed_up_dex_file.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070054#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070055#include "gc/heap.h"
Andreas Gampe691051b2017-02-09 09:15:24 -080056#include "gc_root.h"
Andreas Gampee6377462017-01-20 17:37:50 -080057#include "handle.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010058#include "jni/jni_env_ext-inl.h"
59#include "jni/jni_internal.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070060#include "mirror/array-alloc-inl.h"
Alex Light440b5d92017-01-24 15:32:25 -080061#include "mirror/array-inl.h"
62#include "mirror/class-inl.h"
63#include "mirror/class_ext.h"
Andreas Gampea67354b2017-02-10 16:18:30 -080064#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080065#include "mirror/object-refvisitor-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070066#include "mirror/object_array-inl.h"
67#include "mirror/object_reference.h"
Vladimir Marko6834d342018-05-25 13:12:09 +010068#include "mirror/reference-inl.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070069#include "nativehelper/scoped_local_ref.h"
Alex Light6a656312017-03-29 17:18:00 -070070#include "reflection.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080071#include "runtime.h"
Andreas Gampee6377462017-01-20 17:37:50 -080072#include "runtime_callbacks.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070073#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070074#include "thread-current-inl.h"
Andreas Gampee6377462017-01-20 17:37:50 -080075#include "thread_list.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010076#include "ti_class_definition.h"
Alex Lightc7588752018-02-20 11:15:54 -080077#include "ti_class_loader-inl.h"
Alex Lightae45cbb2018-10-18 15:49:56 -070078#include "ti_logging.h"
Alex Lightd8ce4e72017-02-27 10:52:29 -080079#include "ti_phase.h"
Alex Light440b5d92017-01-24 15:32:25 -080080#include "ti_redefine.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010081#include "transform.h"
Andreas Gampea1d2f952017-04-20 22:53:58 -070082#include "well_known_classes.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070083
84namespace openjdkjvmti {
85
Alex Light440b5d92017-01-24 15:32:25 -080086using android::base::StringPrintf;
87
88static 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;
Vladimir Markoe1993c72017-06-14 17:01:38 +010096 art::ArrayRef<const unsigned char> final_data(final_dex_data, final_len);
Vladimir Markoc34bebf2018-08-16 16:12:49 +010097 art::MemMap map = Redefiner::MoveDataToMemMap(orig_location, final_data, &error_msg);
98 if (!map.IsValid()) {
Alex Light440b5d92017-01-24 15:32:25 -080099 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
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100106 if (map.Size() < sizeof(art::DexFile::Header)) {
Alex Light440b5d92017-01-24 15:32:25 -0800107 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 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100113 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map.Begin())->checksum_;
114 std::string map_name = map.GetName();
David Sehr013fd802018-01-11 22:55:24 -0800115 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),
Andreas Gampe6e897762018-10-16 13:09:32 -0700119 /*verify=*/true,
120 /*verify_checksum=*/true,
David Sehr013fd802018-01-11 22:55:24 -0800121 &error_msg));
Alex Light440b5d92017-01-24 15:32:25 -0800122 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
Alex Light28b6e7e2017-05-22 16:05:59 -0700142// 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.
145template <typename T>
146class FakeJvmtiDeleter {
147 public:
148 FakeJvmtiDeleter() {}
149
150 FakeJvmtiDeleter(FakeJvmtiDeleter&) = default;
Andreas Gampe44b31742018-10-01 19:30:57 -0700151 FakeJvmtiDeleter(FakeJvmtiDeleter&&) noexcept = default;
Alex Light28b6e7e2017-05-22 16:05:59 -0700152 FakeJvmtiDeleter& operator=(const FakeJvmtiDeleter&) = default;
153
154 template <typename U> void operator()(const U* ptr) const {
155 if (ptr != nullptr) {
156 free(const_cast<U*>(ptr));
157 }
158 }
159};
160
Andreas Gampee6377462017-01-20 17:37:50 -0800161struct ClassCallback : public art::ClassLoadCallback {
Alex Light440b5d92017-01-24 15:32:25 -0800162 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,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800166 const art::dex::ClassDef& initial_class_def ATTRIBUTE_UNUSED,
Alex Light440b5d92017-01-24 15:32:25 -0800167 /*out*/art::DexFile const** final_dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800168 /*out*/art::dex::ClassDef const** final_class_def)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100169 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light440b5d92017-01-24 15:32:25 -0800170 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 }
Alex Lightd8ce4e72017-02-27 10:52:29 -0800180 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
Alex Light440b5d92017-01-24 15:32:25 -0800191 art::Thread* self = art::Thread::Current();
Alex Light64e4c142018-01-30 13:46:37 -0800192 ArtClassDefinition def;
193 def.InitFirstLoad(descriptor, class_loader, initial_dex_file);
Alex Light40528472017-03-28 09:07:36 -0700194
Alex Light64e4c142018-01-30 13:46:37 -0800195 // 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());
Alex Light440b5d92017-01-24 15:32:25 -0800204 }
Alex Light64e4c142018-01-30 13:46:37 -0800205
Alex Light440b5d92017-01-24 15:32:25 -0800206 // Call all retransformable agents.
Alex Light64e4c142018-01-30 13:46:37 -0800207 Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
208 event_handler, self, &def);
Alex Light440b5d92017-01-24 15:32:25 -0800209
Alex Light64e4c142018-01-30 13:46:37 -0800210 if (def.IsModified()) {
Alex Light440b5d92017-01-24 15:32:25 -0800211 LOG(WARNING) << "Changing class " << descriptor;
Alex Light440b5d92017-01-24 15:32:25 -0800212 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.
Alex Light6a656312017-03-29 17:18:00 -0700227 art::MutableHandle<art::mirror::Object> arr(hs.NewHandle<art::mirror::Object>(nullptr));
Alex Light64e4c142018-01-30 13:46:37 -0800228 if (post_non_retransform.empty() && strcmp(descriptor, "Ljava/lang/Long;") != 0) {
Alex Light6a656312017-03-29 17:18:00 -0700229 // 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,
Alex Light64e4c142018-01-30 13:46:37 -0800238 reinterpret_cast<const signed char*>(post_non_retransform.data()),
239 post_non_retransform.size()));
Alex Light6a656312017-03-29 17:18:00 -0700240 }
Alex Light440b5d92017-01-24 15:32:25 -0800241 if (arr.IsNull()) {
Alex Light6a656312017-03-29 17:18:00 -0700242 LOG(WARNING) << "Unable to allocate memory for initial dex-file. Aborting transformation";
Alex Light440b5d92017-01-24 15:32:25 -0800243 self->AssertPendingOOMException();
244 return;
245 }
246
247 std::unique_ptr<const art::DexFile> dex_file(MakeSingleDexFile(self,
248 descriptor,
249 initial_dex_file.GetLocation(),
Alex Light64e4c142018-01-30 13:46:37 -0800250 def.GetDexData().size(),
251 def.GetDexData().data()));
Alex Light440b5d92017-01-24 15:32:25 -0800252 if (dex_file.get() == nullptr) {
253 return;
254 }
255
Alex Lighteb98b082017-01-25 13:02:32 -0800256 // TODO Check Redefined dex file for all invariants.
Alex Light440b5d92017-01-24 15:32:25 -0800257 LOG(WARNING) << "Dex file created by class-definition time transformation of "
258 << descriptor << " is not checked for all retransformation invariants.";
Alex Lighteb98b082017-01-25 13:02:32 -0800259
260 if (!ClassLoaderHelper::AddToClassLoader(self, class_loader, dex_file.get())) {
261 LOG(ERROR) << "Unable to add " << descriptor << " to class loader!";
262 return;
263 }
264
Alex Light440b5d92017-01-24 15:32:25 -0800265 // Actually set the ClassExt's original bytes once we have actually succeeded.
Alex Light2f814aa2017-03-24 15:21:34 +0000266 ext->SetOriginalDexFile(arr.Get());
Alex Light440b5d92017-01-24 15:32:25 -0800267 // Set the return values
268 *final_class_def = &dex_file->GetClassDef(0);
269 *final_dex_file = dex_file.release();
270 }
271 }
272
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700273 void ClassLoad(art::Handle<art::mirror::Class> klass) override
274 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampee6377462017-01-20 17:37:50 -0800275 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()));
Alex Light72398652017-06-16 09:08:12 -0700279 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800280 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700281 thread->GetJniEnv(),
282 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Alex Light9df79b72017-09-12 08:57:31 -0700283 event_handler->DispatchEvent<ArtJvmtiEvent::kClassLoad>(
284 thread,
285 static_cast<JNIEnv*>(thread->GetJniEnv()),
286 thread_jni.get(),
287 jklass.get());
Andreas Gampe691051b2017-02-09 09:15:24 -0800288 if (klass->IsTemp()) {
289 AddTempClass(thread, jklass.get());
290 }
Andreas Gampee6377462017-01-20 17:37:50 -0800291 }
292 }
293
Andreas Gampe691051b2017-02-09 09:15:24 -0800294 void ClassPrepare(art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800295 art::Handle<art::mirror::Class> klass)
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700296 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampee6377462017-01-20 17:37:50 -0800297 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassPrepare)) {
298 art::Thread* thread = art::Thread::Current();
Andreas Gampe691051b2017-02-09 09:15:24 -0800299 if (temp_klass.Get() != klass.Get()) {
300 DCHECK(temp_klass->IsTemp());
301 DCHECK(temp_klass->IsRetired());
302 HandleTempClass(thread, temp_klass, klass);
303 }
Andreas Gampee6377462017-01-20 17:37:50 -0800304 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
305 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700306 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800307 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700308 thread->GetJniEnv(),
309 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Andreas Gampe983c1752017-01-23 19:46:56 -0800310 event_handler->DispatchEvent<ArtJvmtiEvent::kClassPrepare>(
311 thread,
312 static_cast<JNIEnv*>(thread->GetJniEnv()),
313 thread_jni.get(),
314 jklass.get());
Andreas Gampee6377462017-01-20 17:37:50 -0800315 }
316 }
317
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800318 // 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
Andreas Gampee6377462017-01-20 17:37:50 -0800322 void AddTempClass(art::Thread* self, jclass klass) {
323 std::unique_lock<std::mutex> mu(temp_classes_lock);
Andreas Gampe691051b2017-02-09 09:15:24 -0800324 jclass global_klass = reinterpret_cast<jclass>(self->GetJniEnv()->NewGlobalRef(klass));
325 temp_classes.push_back(global_klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800326 }
327
Andreas Gampe691051b2017-02-09 09:15:24 -0800328 void HandleTempClass(art::Thread* self,
329 art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800330 art::Handle<art::mirror::Class> klass)
331 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800332 bool requires_fixup = false;
333 {
334 std::unique_lock<std::mutex> mu(temp_classes_lock);
335 if (temp_classes.empty()) {
336 return;
Andreas Gampee6377462017-01-20 17:37:50 -0800337 }
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800338
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);
Andreas Gampee6377462017-01-20 17:37:50 -0800350 }
351 }
352
Andreas Gampe691051b2017-02-09 09:15:24 -0800353 void FixupTempClass(art::Thread* self,
354 art::Handle<art::mirror::Class> temp_klass,
355 art::Handle<art::mirror::Class> klass)
Andreas Gampee6377462017-01-20 17:37:50 -0800356 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe691051b2017-02-09 09:15:24 -0800357 // 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);
Andreas Gampe94dda932017-02-09 18:19:21 -0800372 FixupLocalReferenceTables(self, input, output);
Andreas Gampea67354b2017-02-10 16:18:30 -0800373 FixupHeap(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800374 }
375 if (heap->IsGcConcurrentAndMoving()) {
376 heap->DecrementDisableMovingGC(self);
377 }
378 }
379
Andreas Gampe94dda932017-02-09 18:19:21 -0800380 class RootUpdater : public art::RootVisitor {
381 public:
382 RootUpdater(const art::mirror::Class* input, art::mirror::Class* output)
383 : input_(input), output_(output) {}
384
385 void VisitRoots(art::mirror::Object*** roots,
386 size_t count,
387 const art::RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100388 override {
Andreas Gampe94dda932017-02-09 18:19:21 -0800389 for (size_t i = 0; i != count; ++i) {
390 if (*roots[i] == input_) {
391 *roots[i] = output_;
392 }
393 }
394 }
395
396 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
397 size_t count,
398 const art::RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100399 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe94dda932017-02-09 18:19:21 -0800400 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
Andreas Gampea67354b2017-02-10 16:18:30 -0800412 void FixupGlobalReferenceTables(art::mirror::Class* input, art::mirror::Class* output)
Andreas Gampe691051b2017-02-09 09:15:24 -0800413 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.
Andreas Gampe94dda932017-02-09 18:19:21 -0800417 RootUpdater global_update(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800418 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
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100425 art::mirror::Object* IsMarked(art::mirror::Object* obj) override {
Andreas Gampe691051b2017-02-09 09:15:24 -0800426 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);
Andreas Gampee6377462017-01-20 17:37:50 -0800438 }
439
Andreas Gampe94dda932017-02-09 18:19:21 -0800440 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_);
Ian Rogers55256cb2017-12-21 17:07:11 -0800454 t->GetJniEnv()->VisitJniLocalRoots(
Andreas Gampe94dda932017-02-09 18:19:21 -0800455 &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
Andreas Gampea67354b2017-02-10 16:18:30 -0800467 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
Andreas Gampe52784ac2017-02-13 18:10:09 -0800487 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
Andreas Gampea67354b2017-02-10 16:18:30 -0800496 void VisitRoot(art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED)
Andreas Gampe52784ac2017-02-13 18:10:09 -0800497 const {
Andreas Gampea67354b2017-02-10 16:18:30 -0800498 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
Andreas Gampea67354b2017-02-10 16:18:30 -0800506 private:
507 const art::mirror::Class* input_;
508 art::mirror::Class* output_;
509 };
510 HeapFixupVisitor hfv(input, output);
Andreas Gampe1c158a02017-07-13 17:26:19 -0700511 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);
Andreas Gampea67354b2017-02-10 16:18:30 -0800515 }
516
Andreas Gampee6377462017-01-20 17:37:50 -0800517 // 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
526ClassCallback gClassCallback;
527
528void 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
536void 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
Andreas Gampeac587272017-01-05 15:21:34 -0800544jvmtiError 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
Alex Light2c6cd692017-06-30 07:34:40 -0700554 // 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
Andreas Gampeac587272017-01-05 15:21:34 -0800561 if (field_count_ptr == nullptr || fields_ptr == nullptr) {
562 return ERR(NULL_POINTER);
563 }
564
Andreas Gampeac587272017-01-05 15:21:34 -0800565 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
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800592jvmtiError 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
Alex Light2c6cd692017-06-30 07:34:40 -0700602 // 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
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800609 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
Andreas Gampe8b07e472017-01-06 14:20:39 -0800641jvmtiError 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}
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800691
Andreas Gampee492ae32016-10-28 19:34:57 -0700692jvmtiError 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
Andreas Gampe54711412017-02-21 12:41:43 -0800702 JvmtiUniquePtr<char[]> sig_copy;
Andreas Gampee492ae32016-10-28 19:34:57 -0700703 if (signature_ptr != nullptr) {
704 std::string storage;
705 const char* descriptor = klass->GetDescriptor(&storage);
706
Andreas Gampe54711412017-02-21 12:41:43 -0800707 jvmtiError ret;
708 sig_copy = CopyString(env, descriptor, &ret);
709 if (sig_copy == nullptr) {
Andreas Gampee492ae32016-10-28 19:34:57 -0700710 return ret;
711 }
Andreas Gampe54711412017-02-21 12:41:43 -0800712 *signature_ptr = sig_copy.get();
Andreas Gampee492ae32016-10-28 19:34:57 -0700713 }
714
Andreas Gampee6377462017-01-20 17:37:50 -0800715 if (generic_ptr != nullptr) {
716 *generic_ptr = nullptr;
Andreas Gampe0eb36432017-02-15 18:36:14 -0800717 if (!klass->IsProxyClass() && klass->GetDexCache() != nullptr) {
718 art::StackHandleScope<1> hs(soa.Self());
719 art::Handle<art::mirror::Class> h_klass = hs.NewHandle(klass);
Vladimir Markoacb906d2018-05-30 10:23:49 +0100720 art::ObjPtr<art::mirror::ObjectArray<art::mirror::String>> str_array =
Andreas Gampe0eb36432017-02-15 18:36:14 -0800721 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();
Andreas Gampe54711412017-02-21 12:41:43 -0800728 jvmtiError ret;
729 JvmtiUniquePtr<char[]> copy = CopyString(env, output_string.c_str(), &ret);
730 if (copy == nullptr) {
Andreas Gampe0eb36432017-02-15 18:36:14 -0800731 return ret;
732 }
Andreas Gampe54711412017-02-21 12:41:43 -0800733 *generic_ptr = copy.release();
Andreas Gampe0eb36432017-02-15 18:36:14 -0800734 } else if (soa.Self()->IsExceptionPending()) {
735 // TODO: Should we report an error here?
736 soa.Self()->ClearException();
737 }
738 }
Andreas Gampee6377462017-01-20 17:37:50 -0800739 }
Andreas Gampee492ae32016-10-28 19:34:57 -0700740
741 // Everything is fine, release the buffers.
742 sig_copy.release();
743
744 return ERR(NONE);
745}
746
Andreas Gampeff9d2092017-01-06 09:12:49 -0800747jvmtiError 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
Andreas Gampe4fd66ec2017-01-05 14:42:13 -0800782template <typename T>
783static 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
798jvmtiError 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
807jvmtiError 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
Andreas Gampe64013e52017-01-06 13:07:19 -0800816// Keep this in sync with Class.getModifiers().
817static 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
834jvmtiError 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
Andreas Gampe8f5b6032017-01-06 15:50:55 -0800852jvmtiError 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
Alex Lightc7588752018-02-20 11:15:54 -0800870// Copies unique class descriptors into the classes list from dex_files.
871static 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;
Vladimir Marko2ef01102019-02-05 15:05:10 +0000876 std::set<std::string_view> unique_descriptors;
Alex Lightc7588752018-02-20 11:15:54 -0800877 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
913jvmtiError 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)) {
Alex Lightae45cbb2018-10-18 15:49:56 -0700938 JVMTI_LOG(ERROR, env) << "GetClassLoaderClassDescriptors is only implemented for "
939 << "BootClassPath and dalvik.system.BaseDexClassLoader class loaders";
Alex Lightc7588752018-02-20 11:15:54 -0800940 // 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;
Andreas Gampeb8e7c372018-02-20 18:24:55 -0800950 art::VisitClassLoaderDexFiles(
951 soa,
Alex Lightc7588752018-02-20 11:15:54 -0800952 class_loader,
Andreas Gampeb8e7c372018-02-20 18:24:55 -0800953 [&](const art::DexFile* dex_file) {
954 dex_files.push_back(dex_file);
955 return true; // Continue with other dex files.
Alex Lightc7588752018-02-20 11:15:54 -0800956 });
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
Andreas Gampe70f16392017-01-16 14:20:10 -0800961jvmtiError 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
Andreas Gampe812a2442017-01-19 22:04:46 -08001047jvmtiError 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
Alex Light6fa7b812017-06-16 09:04:29 -07001078jvmtiError 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
1105jvmtiError 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
Andreas Gampee492ae32016-10-28 19:34:57 -07001135} // namespace openjdkjvmti