blob: 7537f28df6c62a19fbc21db8ac8b1d003191e850 [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"
Alex Light307b2842019-04-11 16:13:04 -070042#include "base/logging.h"
Andreas Gampee6377462017-01-20 17:37:50 -080043#include "base/macros.h"
David Sehrc431b9d2018-03-02 12:01:51 -080044#include "base/utils.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080045#include "class_linker.h"
Andreas Gampeb8e7c372018-02-20 18:24:55 -080046#include "class_loader_utils.h"
Steven Morelande431e272017-07-18 16:53:49 -070047#include "class_table-inl.h"
Alex Light440b5d92017-01-24 15:32:25 -080048#include "common_throws.h"
David Sehr013fd802018-01-11 22:55:24 -080049#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080050#include "dex/dex_file_annotations.h"
51#include "dex/dex_file_loader.h"
David Sehr67bf42e2018-02-26 16:43:04 -080052#include "dex/primitive.h"
Andreas Gampee6377462017-01-20 17:37:50 -080053#include "events-inl.h"
Alex Light40528472017-03-28 09:07:36 -070054#include "fixed_up_dex_file.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070055#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070056#include "gc/heap.h"
Andreas Gampe691051b2017-02-09 09:15:24 -080057#include "gc_root.h"
Andreas Gampee6377462017-01-20 17:37:50 -080058#include "handle.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010059#include "jni/jni_env_ext-inl.h"
60#include "jni/jni_internal.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070061#include "mirror/array-alloc-inl.h"
Alex Light440b5d92017-01-24 15:32:25 -080062#include "mirror/array-inl.h"
63#include "mirror/class-inl.h"
64#include "mirror/class_ext.h"
Andreas Gampea67354b2017-02-10 16:18:30 -080065#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080066#include "mirror/object-refvisitor-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070067#include "mirror/object_array-inl.h"
68#include "mirror/object_reference.h"
Vladimir Marko6834d342018-05-25 13:12:09 +010069#include "mirror/reference-inl.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070070#include "nativehelper/scoped_local_ref.h"
Alex Light6a656312017-03-29 17:18:00 -070071#include "reflection.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080072#include "runtime.h"
Andreas Gampee6377462017-01-20 17:37:50 -080073#include "runtime_callbacks.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070074#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070075#include "thread-current-inl.h"
Andreas Gampee6377462017-01-20 17:37:50 -080076#include "thread_list.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010077#include "ti_class_definition.h"
Alex Lightc7588752018-02-20 11:15:54 -080078#include "ti_class_loader-inl.h"
Alex Lightae45cbb2018-10-18 15:49:56 -070079#include "ti_logging.h"
Alex Lightd8ce4e72017-02-27 10:52:29 -080080#include "ti_phase.h"
Alex Light440b5d92017-01-24 15:32:25 -080081#include "ti_redefine.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010082#include "transform.h"
Andreas Gampea1d2f952017-04-20 22:53:58 -070083#include "well_known_classes.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070084
85namespace openjdkjvmti {
86
Alex Light440b5d92017-01-24 15:32:25 -080087using android::base::StringPrintf;
88
89static std::unique_ptr<const art::DexFile> MakeSingleDexFile(art::Thread* self,
90 const char* descriptor,
91 const std::string& orig_location,
92 jint final_len,
93 const unsigned char* final_dex_data)
94 REQUIRES_SHARED(art::Locks::mutator_lock_) {
95 // Make the mmap
96 std::string error_msg;
Vladimir Markoe1993c72017-06-14 17:01:38 +010097 art::ArrayRef<const unsigned char> final_data(final_dex_data, final_len);
Vladimir Markoc34bebf2018-08-16 16:12:49 +010098 art::MemMap map = Redefiner::MoveDataToMemMap(orig_location, final_data, &error_msg);
99 if (!map.IsValid()) {
Alex Light440b5d92017-01-24 15:32:25 -0800100 LOG(WARNING) << "Unable to allocate mmap for redefined dex file! Error was: " << error_msg;
101 self->ThrowOutOfMemoryError(StringPrintf(
102 "Unable to allocate dex file for transformation of %s", descriptor).c_str());
103 return nullptr;
104 }
105
106 // Make a dex-file
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100107 if (map.Size() < sizeof(art::DexFile::Header)) {
Alex Light440b5d92017-01-24 15:32:25 -0800108 LOG(WARNING) << "Could not read dex file header because dex_data was too short";
109 art::ThrowClassFormatError(nullptr,
110 "Unable to read transformed dex file of %s",
111 descriptor);
112 return nullptr;
113 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100114 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map.Begin())->checksum_;
115 std::string map_name = map.GetName();
David Sehr013fd802018-01-11 22:55:24 -0800116 const art::ArtDexFileLoader dex_file_loader;
117 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(map_name,
118 checksum,
119 std::move(map),
Andreas Gampe6e897762018-10-16 13:09:32 -0700120 /*verify=*/true,
121 /*verify_checksum=*/true,
David Sehr013fd802018-01-11 22:55:24 -0800122 &error_msg));
Alex Light440b5d92017-01-24 15:32:25 -0800123 if (dex_file.get() == nullptr) {
124 LOG(WARNING) << "Unable to load modified dex file for " << descriptor << ": " << error_msg;
125 art::ThrowClassFormatError(nullptr,
126 "Unable to read transformed dex file of %s because %s",
127 descriptor,
128 error_msg.c_str());
129 return nullptr;
130 }
131 if (dex_file->NumClassDefs() != 1) {
132 LOG(WARNING) << "Dex file contains more than 1 class_def. Ignoring.";
133 // TODO Throw some other sort of error here maybe?
134 art::ThrowClassFormatError(
135 nullptr,
136 "Unable to use transformed dex file of %s because it contained too many classes",
137 descriptor);
138 return nullptr;
139 }
140 return dex_file;
141}
142
Alex Light28b6e7e2017-05-22 16:05:59 -0700143// A deleter that acts like the jvmtiEnv->Deallocate so that asan does not get tripped up.
144// TODO We should everything use the actual jvmtiEnv->Allocate/Deallocate functions once we can
145// figure out which env to use.
146template <typename T>
147class FakeJvmtiDeleter {
148 public:
149 FakeJvmtiDeleter() {}
150
151 FakeJvmtiDeleter(FakeJvmtiDeleter&) = default;
Andreas Gampe44b31742018-10-01 19:30:57 -0700152 FakeJvmtiDeleter(FakeJvmtiDeleter&&) noexcept = default;
Alex Light28b6e7e2017-05-22 16:05:59 -0700153 FakeJvmtiDeleter& operator=(const FakeJvmtiDeleter&) = default;
154
155 template <typename U> void operator()(const U* ptr) const {
156 if (ptr != nullptr) {
157 free(const_cast<U*>(ptr));
158 }
159 }
160};
161
Andreas Gampee6377462017-01-20 17:37:50 -0800162struct ClassCallback : public art::ClassLoadCallback {
Alex Light440b5d92017-01-24 15:32:25 -0800163 void ClassPreDefine(const char* descriptor,
164 art::Handle<art::mirror::Class> klass,
165 art::Handle<art::mirror::ClassLoader> class_loader,
166 const art::DexFile& initial_dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800167 const art::dex::ClassDef& initial_class_def ATTRIBUTE_UNUSED,
Alex Light440b5d92017-01-24 15:32:25 -0800168 /*out*/art::DexFile const** final_dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800169 /*out*/art::dex::ClassDef const** final_class_def)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100170 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light440b5d92017-01-24 15:32:25 -0800171 bool is_enabled =
172 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookRetransformable) ||
173 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookNonRetransformable);
174 if (!is_enabled) {
175 return;
176 }
177 if (descriptor[0] != 'L') {
178 // It is a primitive or array. Just return
179 return;
180 }
Alex Lightd8ce4e72017-02-27 10:52:29 -0800181 jvmtiPhase phase = PhaseUtil::GetPhaseUnchecked();
182 if (UNLIKELY(phase != JVMTI_PHASE_START && phase != JVMTI_PHASE_LIVE)) {
183 // We want to wait until we are at least in the START phase so that all WellKnownClasses and
184 // mirror classes have been initialized and loaded. The runtime relies on these classes having
185 // specific fields and methods present. Since PreDefine hooks don't need to abide by this
186 // restriction we will simply not send the event for these classes.
187 LOG(WARNING) << "Ignoring load of class <" << descriptor << "> as it is being loaded during "
188 << "runtime initialization.";
189 return;
190 }
191
Alex Light440b5d92017-01-24 15:32:25 -0800192 art::Thread* self = art::Thread::Current();
Alex Light64e4c142018-01-30 13:46:37 -0800193 ArtClassDefinition def;
194 def.InitFirstLoad(descriptor, class_loader, initial_dex_file);
Alex Light40528472017-03-28 09:07:36 -0700195
Alex Light64e4c142018-01-30 13:46:37 -0800196 // Call all non-retransformable agents.
197 Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookNonRetransformable>(
198 event_handler, self, &def);
199
200 std::vector<unsigned char> post_non_retransform;
201 if (def.IsModified()) {
202 // Copy the dex data after the non-retransformable events.
203 post_non_retransform.resize(def.GetDexData().size());
204 memcpy(post_non_retransform.data(), def.GetDexData().data(), post_non_retransform.size());
Alex Light440b5d92017-01-24 15:32:25 -0800205 }
Alex Light64e4c142018-01-30 13:46:37 -0800206
Alex Light440b5d92017-01-24 15:32:25 -0800207 // Call all retransformable agents.
Alex Light64e4c142018-01-30 13:46:37 -0800208 Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
209 event_handler, self, &def);
Alex Light440b5d92017-01-24 15:32:25 -0800210
Alex Light64e4c142018-01-30 13:46:37 -0800211 if (def.IsModified()) {
Alex Light307b2842019-04-11 16:13:04 -0700212 VLOG(class_linker) << "Changing class " << descriptor;
Alex Light440b5d92017-01-24 15:32:25 -0800213 art::StackHandleScope<2> hs(self);
214 // Save the results of all the non-retransformable agents.
215 // First allocate the ClassExt
216 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(self)));
217 // Make sure we have a ClassExt. This is fine even though we are a temporary since it will
218 // get copied.
219 if (ext.IsNull()) {
220 // We will just return failure if we fail to allocate
221 LOG(WARNING) << "Could not allocate ext-data for class '" << descriptor << "'. "
222 << "Aborting transformation since we will be unable to store it.";
223 self->AssertPendingOOMException();
224 return;
225 }
226
227 // Allocate the byte array to store the dex file bytes in.
Alex Light6a656312017-03-29 17:18:00 -0700228 art::MutableHandle<art::mirror::Object> arr(hs.NewHandle<art::mirror::Object>(nullptr));
Alex Light64e4c142018-01-30 13:46:37 -0800229 if (post_non_retransform.empty() && strcmp(descriptor, "Ljava/lang/Long;") != 0) {
Alex Light6a656312017-03-29 17:18:00 -0700230 // we didn't have any non-retransformable agents. We can just cache a pointer to the
231 // initial_dex_file. It will be kept live by the class_loader.
232 jlong dex_ptr = reinterpret_cast<uintptr_t>(&initial_dex_file);
233 art::JValue val;
234 val.SetJ(dex_ptr);
235 arr.Assign(art::BoxPrimitive(art::Primitive::kPrimLong, val));
236 } else {
237 arr.Assign(art::mirror::ByteArray::AllocateAndFill(
238 self,
Alex Light64e4c142018-01-30 13:46:37 -0800239 reinterpret_cast<const signed char*>(post_non_retransform.data()),
240 post_non_retransform.size()));
Alex Light6a656312017-03-29 17:18:00 -0700241 }
Alex Light440b5d92017-01-24 15:32:25 -0800242 if (arr.IsNull()) {
Alex Light6a656312017-03-29 17:18:00 -0700243 LOG(WARNING) << "Unable to allocate memory for initial dex-file. Aborting transformation";
Alex Light440b5d92017-01-24 15:32:25 -0800244 self->AssertPendingOOMException();
245 return;
246 }
247
248 std::unique_ptr<const art::DexFile> dex_file(MakeSingleDexFile(self,
249 descriptor,
250 initial_dex_file.GetLocation(),
Alex Light64e4c142018-01-30 13:46:37 -0800251 def.GetDexData().size(),
252 def.GetDexData().data()));
Alex Light440b5d92017-01-24 15:32:25 -0800253 if (dex_file.get() == nullptr) {
254 return;
255 }
256
Alex Lighteb98b082017-01-25 13:02:32 -0800257 // TODO Check Redefined dex file for all invariants.
Alex Light440b5d92017-01-24 15:32:25 -0800258 LOG(WARNING) << "Dex file created by class-definition time transformation of "
259 << descriptor << " is not checked for all retransformation invariants.";
Alex Lighteb98b082017-01-25 13:02:32 -0800260
261 if (!ClassLoaderHelper::AddToClassLoader(self, class_loader, dex_file.get())) {
262 LOG(ERROR) << "Unable to add " << descriptor << " to class loader!";
263 return;
264 }
265
Alex Light440b5d92017-01-24 15:32:25 -0800266 // Actually set the ClassExt's original bytes once we have actually succeeded.
Alex Light2f814aa2017-03-24 15:21:34 +0000267 ext->SetOriginalDexFile(arr.Get());
Alex Light440b5d92017-01-24 15:32:25 -0800268 // Set the return values
269 *final_class_def = &dex_file->GetClassDef(0);
270 *final_dex_file = dex_file.release();
271 }
272 }
273
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700274 void ClassLoad(art::Handle<art::mirror::Class> klass) override
275 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampee6377462017-01-20 17:37:50 -0800276 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassLoad)) {
277 art::Thread* thread = art::Thread::Current();
278 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
279 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700280 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800281 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700282 thread->GetJniEnv(),
283 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Alex Light9df79b72017-09-12 08:57:31 -0700284 event_handler->DispatchEvent<ArtJvmtiEvent::kClassLoad>(
285 thread,
286 static_cast<JNIEnv*>(thread->GetJniEnv()),
287 thread_jni.get(),
288 jklass.get());
Andreas Gampe691051b2017-02-09 09:15:24 -0800289 if (klass->IsTemp()) {
290 AddTempClass(thread, jklass.get());
291 }
Andreas Gampee6377462017-01-20 17:37:50 -0800292 }
293 }
294
Andreas Gampe691051b2017-02-09 09:15:24 -0800295 void ClassPrepare(art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800296 art::Handle<art::mirror::Class> klass)
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700297 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampee6377462017-01-20 17:37:50 -0800298 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassPrepare)) {
299 art::Thread* thread = art::Thread::Current();
Andreas Gampe691051b2017-02-09 09:15:24 -0800300 if (temp_klass.Get() != klass.Get()) {
301 DCHECK(temp_klass->IsTemp());
302 DCHECK(temp_klass->IsRetired());
303 HandleTempClass(thread, temp_klass, klass);
304 }
Andreas Gampee6377462017-01-20 17:37:50 -0800305 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
306 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700307 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800308 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700309 thread->GetJniEnv(),
310 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Andreas Gampe983c1752017-01-23 19:46:56 -0800311 event_handler->DispatchEvent<ArtJvmtiEvent::kClassPrepare>(
312 thread,
313 static_cast<JNIEnv*>(thread->GetJniEnv()),
314 thread_jni.get(),
315 jklass.get());
Andreas Gampee6377462017-01-20 17:37:50 -0800316 }
317 }
318
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800319 // To support parallel class-loading, we need to perform some locking dances here. Namely,
320 // the fixup stage must not be holding the temp_classes lock when it fixes up the system
321 // (as that requires suspending all mutators).
322
Andreas Gampee6377462017-01-20 17:37:50 -0800323 void AddTempClass(art::Thread* self, jclass klass) {
324 std::unique_lock<std::mutex> mu(temp_classes_lock);
Andreas Gampe691051b2017-02-09 09:15:24 -0800325 jclass global_klass = reinterpret_cast<jclass>(self->GetJniEnv()->NewGlobalRef(klass));
326 temp_classes.push_back(global_klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800327 }
328
Andreas Gampe691051b2017-02-09 09:15:24 -0800329 void HandleTempClass(art::Thread* self,
330 art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800331 art::Handle<art::mirror::Class> klass)
332 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800333 bool requires_fixup = false;
334 {
335 std::unique_lock<std::mutex> mu(temp_classes_lock);
336 if (temp_classes.empty()) {
337 return;
Andreas Gampee6377462017-01-20 17:37:50 -0800338 }
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800339
340 for (auto it = temp_classes.begin(); it != temp_classes.end(); ++it) {
341 if (temp_klass.Get() == art::ObjPtr<art::mirror::Class>::DownCast(self->DecodeJObject(*it))) {
342 self->GetJniEnv()->DeleteGlobalRef(*it);
343 temp_classes.erase(it);
344 requires_fixup = true;
345 break;
346 }
347 }
348 }
349 if (requires_fixup) {
350 FixupTempClass(self, temp_klass, klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800351 }
352 }
353
Andreas Gampe691051b2017-02-09 09:15:24 -0800354 void FixupTempClass(art::Thread* self,
355 art::Handle<art::mirror::Class> temp_klass,
356 art::Handle<art::mirror::Class> klass)
Andreas Gampee6377462017-01-20 17:37:50 -0800357 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe691051b2017-02-09 09:15:24 -0800358 // Suspend everything.
359 art::gc::Heap* heap = art::Runtime::Current()->GetHeap();
360 if (heap->IsGcConcurrentAndMoving()) {
361 // Need to take a heap dump while GC isn't running. See the
362 // comment in Heap::VisitObjects().
363 heap->IncrementDisableMovingGC(self);
364 }
365 {
366 art::ScopedThreadSuspension sts(self, art::kWaitingForVisitObjects);
367 art::ScopedSuspendAll ssa("FixupTempClass");
368
369 art::mirror::Class* input = temp_klass.Get();
370 art::mirror::Class* output = klass.Get();
371
372 FixupGlobalReferenceTables(input, output);
Andreas Gampe94dda932017-02-09 18:19:21 -0800373 FixupLocalReferenceTables(self, input, output);
Andreas Gampea67354b2017-02-10 16:18:30 -0800374 FixupHeap(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800375 }
376 if (heap->IsGcConcurrentAndMoving()) {
377 heap->DecrementDisableMovingGC(self);
378 }
379 }
380
Andreas Gampe94dda932017-02-09 18:19:21 -0800381 class RootUpdater : public art::RootVisitor {
382 public:
383 RootUpdater(const art::mirror::Class* input, art::mirror::Class* output)
384 : input_(input), output_(output) {}
385
386 void VisitRoots(art::mirror::Object*** roots,
387 size_t count,
388 const art::RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100389 override {
Andreas Gampe94dda932017-02-09 18:19:21 -0800390 for (size_t i = 0; i != count; ++i) {
391 if (*roots[i] == input_) {
392 *roots[i] = output_;
393 }
394 }
395 }
396
397 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
398 size_t count,
399 const art::RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100400 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe94dda932017-02-09 18:19:21 -0800401 for (size_t i = 0; i != count; ++i) {
402 if (roots[i]->AsMirrorPtr() == input_) {
403 roots[i]->Assign(output_);
404 }
405 }
406 }
407
408 private:
409 const art::mirror::Class* input_;
410 art::mirror::Class* output_;
411 };
412
Andreas Gampea67354b2017-02-10 16:18:30 -0800413 void FixupGlobalReferenceTables(art::mirror::Class* input, art::mirror::Class* output)
Andreas Gampe691051b2017-02-09 09:15:24 -0800414 REQUIRES(art::Locks::mutator_lock_) {
415 art::JavaVMExt* java_vm = art::Runtime::Current()->GetJavaVM();
416
417 // Fix up the global table with a root visitor.
Andreas Gampe94dda932017-02-09 18:19:21 -0800418 RootUpdater global_update(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800419 java_vm->VisitRoots(&global_update);
420
421 class WeakGlobalUpdate : public art::IsMarkedVisitor {
422 public:
423 WeakGlobalUpdate(art::mirror::Class* root_input, art::mirror::Class* root_output)
424 : input_(root_input), output_(root_output) {}
425
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100426 art::mirror::Object* IsMarked(art::mirror::Object* obj) override {
Andreas Gampe691051b2017-02-09 09:15:24 -0800427 if (obj == input_) {
428 return output_;
429 }
430 return obj;
431 }
432
433 private:
434 const art::mirror::Class* input_;
435 art::mirror::Class* output_;
436 };
437 WeakGlobalUpdate weak_global_update(input, output);
438 java_vm->SweepJniWeakGlobals(&weak_global_update);
Andreas Gampee6377462017-01-20 17:37:50 -0800439 }
440
Andreas Gampe94dda932017-02-09 18:19:21 -0800441 void FixupLocalReferenceTables(art::Thread* self,
442 art::mirror::Class* input,
443 art::mirror::Class* output)
444 REQUIRES(art::Locks::mutator_lock_) {
445 class LocalUpdate {
446 public:
447 LocalUpdate(const art::mirror::Class* root_input, art::mirror::Class* root_output)
448 : input_(root_input), output_(root_output) {}
449
450 static void Callback(art::Thread* t, void* arg) REQUIRES(art::Locks::mutator_lock_) {
451 LocalUpdate* local = reinterpret_cast<LocalUpdate*>(arg);
452
453 // Fix up the local table with a root visitor.
454 RootUpdater local_update(local->input_, local->output_);
Ian Rogers55256cb2017-12-21 17:07:11 -0800455 t->GetJniEnv()->VisitJniLocalRoots(
Andreas Gampe94dda932017-02-09 18:19:21 -0800456 &local_update, art::RootInfo(art::kRootJNILocal, t->GetThreadId()));
457 }
458
459 private:
460 const art::mirror::Class* input_;
461 art::mirror::Class* output_;
462 };
463 LocalUpdate local_upd(input, output);
464 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
465 art::Runtime::Current()->GetThreadList()->ForEach(LocalUpdate::Callback, &local_upd);
466 }
467
Andreas Gampea67354b2017-02-10 16:18:30 -0800468 void FixupHeap(art::mirror::Class* input, art::mirror::Class* output)
469 REQUIRES(art::Locks::mutator_lock_) {
470 class HeapFixupVisitor {
471 public:
472 HeapFixupVisitor(const art::mirror::Class* root_input, art::mirror::Class* root_output)
473 : input_(root_input), output_(root_output) {}
474
475 void operator()(art::mirror::Object* src,
476 art::MemberOffset field_offset,
477 bool is_static ATTRIBUTE_UNUSED) const
478 REQUIRES_SHARED(art::Locks::mutator_lock_) {
479 art::mirror::HeapReference<art::mirror::Object>* trg =
480 src->GetFieldObjectReferenceAddr(field_offset);
481 if (trg->AsMirrorPtr() == input_) {
482 DCHECK_NE(field_offset.Uint32Value(), 0u); // This shouldn't be the class field of
483 // an object.
484 trg->Assign(output_);
485 }
486 }
487
Andreas Gampe52784ac2017-02-13 18:10:09 -0800488 void operator()(art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
489 art::ObjPtr<art::mirror::Reference> reference) const
490 REQUIRES_SHARED(art::Locks::mutator_lock_) {
491 art::mirror::Object* val = reference->GetReferent();
492 if (val == input_) {
493 reference->SetReferent<false>(output_);
494 }
495 }
496
Andreas Gampea67354b2017-02-10 16:18:30 -0800497 void VisitRoot(art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED)
Andreas Gampe52784ac2017-02-13 18:10:09 -0800498 const {
Andreas Gampea67354b2017-02-10 16:18:30 -0800499 LOG(FATAL) << "Unreachable";
500 }
501
502 void VisitRootIfNonNull(
503 art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED) const {
504 LOG(FATAL) << "Unreachable";
505 }
506
Andreas Gampea67354b2017-02-10 16:18:30 -0800507 private:
508 const art::mirror::Class* input_;
509 art::mirror::Class* output_;
510 };
511 HeapFixupVisitor hfv(input, output);
Andreas Gampe1c158a02017-07-13 17:26:19 -0700512 auto object_visitor = [&](art::mirror::Object* obj) {
513 obj->VisitReferences<false>(hfv, hfv); // Visit references, not native roots.
514 };
515 art::Runtime::Current()->GetHeap()->VisitObjectsPaused(object_visitor);
Andreas Gampea67354b2017-02-10 16:18:30 -0800516 }
517
Andreas Gampee6377462017-01-20 17:37:50 -0800518 // A set of all the temp classes we have handed out. We have to fix up references to these.
519 // For simplicity, we store the temp classes as JNI global references in a vector. Normally a
520 // Prepare event will closely follow, so the vector should be small.
521 std::mutex temp_classes_lock;
522 std::vector<jclass> temp_classes;
523
524 EventHandler* event_handler = nullptr;
525};
526
527ClassCallback gClassCallback;
528
529void ClassUtil::Register(EventHandler* handler) {
530 gClassCallback.event_handler = handler;
531 art::ScopedThreadStateChange stsc(art::Thread::Current(),
532 art::ThreadState::kWaitingForDebuggerToAttach);
533 art::ScopedSuspendAll ssa("Add load callback");
534 art::Runtime::Current()->GetRuntimeCallbacks()->AddClassLoadCallback(&gClassCallback);
535}
536
537void ClassUtil::Unregister() {
538 art::ScopedThreadStateChange stsc(art::Thread::Current(),
539 art::ThreadState::kWaitingForDebuggerToAttach);
540 art::ScopedSuspendAll ssa("Remove thread callback");
541 art::Runtime* runtime = art::Runtime::Current();
542 runtime->GetRuntimeCallbacks()->RemoveClassLoadCallback(&gClassCallback);
543}
544
Andreas Gampeac587272017-01-05 15:21:34 -0800545jvmtiError ClassUtil::GetClassFields(jvmtiEnv* env,
546 jclass jklass,
547 jint* field_count_ptr,
548 jfieldID** fields_ptr) {
549 art::ScopedObjectAccess soa(art::Thread::Current());
550 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
551 if (klass == nullptr) {
552 return ERR(INVALID_CLASS);
553 }
554
Alex Light2c6cd692017-06-30 07:34:40 -0700555 // Check if this class is a temporary class object used for loading. Since we are seeing it the
556 // class must not have been prepared yet since otherwise the fixup would have gotten the jobject
557 // to point to the final class object.
558 if (klass->IsTemp() || klass->IsRetired()) {
559 return ERR(CLASS_NOT_PREPARED);
560 }
561
Andreas Gampeac587272017-01-05 15:21:34 -0800562 if (field_count_ptr == nullptr || fields_ptr == nullptr) {
563 return ERR(NULL_POINTER);
564 }
565
Andreas Gampeac587272017-01-05 15:21:34 -0800566 art::IterationRange<art::StrideIterator<art::ArtField>> ifields = klass->GetIFields();
567 art::IterationRange<art::StrideIterator<art::ArtField>> sfields = klass->GetSFields();
568 size_t array_size = klass->NumInstanceFields() + klass->NumStaticFields();
569
570 unsigned char* out_ptr;
571 jvmtiError allocError = env->Allocate(array_size * sizeof(jfieldID), &out_ptr);
572 if (allocError != ERR(NONE)) {
573 return allocError;
574 }
575 jfieldID* field_array = reinterpret_cast<jfieldID*>(out_ptr);
576
577 size_t array_idx = 0;
578 for (art::ArtField& field : sfields) {
579 field_array[array_idx] = art::jni::EncodeArtField(&field);
580 ++array_idx;
581 }
582 for (art::ArtField& field : ifields) {
583 field_array[array_idx] = art::jni::EncodeArtField(&field);
584 ++array_idx;
585 }
586
587 *field_count_ptr = static_cast<jint>(array_size);
588 *fields_ptr = field_array;
589
590 return ERR(NONE);
591}
592
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800593jvmtiError ClassUtil::GetClassMethods(jvmtiEnv* env,
594 jclass jklass,
595 jint* method_count_ptr,
596 jmethodID** methods_ptr) {
597 art::ScopedObjectAccess soa(art::Thread::Current());
598 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
599 if (klass == nullptr) {
600 return ERR(INVALID_CLASS);
601 }
602
Alex Light2c6cd692017-06-30 07:34:40 -0700603 // Check if this class is a temporary class object used for loading. Since we are seeing it the
604 // class must not have been prepared yet since otherwise the fixup would have gotten the jobject
605 // to point to the final class object.
606 if (klass->IsTemp() || klass->IsRetired()) {
607 return ERR(CLASS_NOT_PREPARED);
608 }
609
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800610 if (method_count_ptr == nullptr || methods_ptr == nullptr) {
611 return ERR(NULL_POINTER);
612 }
613
614 size_t array_size = klass->NumDeclaredVirtualMethods() + klass->NumDirectMethods();
615 unsigned char* out_ptr;
616 jvmtiError allocError = env->Allocate(array_size * sizeof(jmethodID), &out_ptr);
617 if (allocError != ERR(NONE)) {
618 return allocError;
619 }
620 jmethodID* method_array = reinterpret_cast<jmethodID*>(out_ptr);
621
622 if (art::kIsDebugBuild) {
623 size_t count = 0;
624 for (auto& m ATTRIBUTE_UNUSED : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
625 count++;
626 }
627 CHECK_EQ(count, klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods());
628 }
629
630 size_t array_idx = 0;
631 for (auto& m : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
632 method_array[array_idx] = art::jni::EncodeArtMethod(&m);
633 ++array_idx;
634 }
635
636 *method_count_ptr = static_cast<jint>(array_size);
637 *methods_ptr = method_array;
638
639 return ERR(NONE);
640}
641
Andreas Gampe8b07e472017-01-06 14:20:39 -0800642jvmtiError ClassUtil::GetImplementedInterfaces(jvmtiEnv* env,
643 jclass jklass,
644 jint* interface_count_ptr,
645 jclass** interfaces_ptr) {
646 art::ScopedObjectAccess soa(art::Thread::Current());
647 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
648 if (klass == nullptr) {
649 return ERR(INVALID_CLASS);
650 }
651
652 if (interface_count_ptr == nullptr || interfaces_ptr == nullptr) {
653 return ERR(NULL_POINTER);
654 }
655
656 // Need to handle array specifically. Arrays implement Serializable and Cloneable, but the
657 // spec says these should not be reported.
658 if (klass->IsArrayClass()) {
659 *interface_count_ptr = 0;
660 *interfaces_ptr = nullptr; // TODO: Should we allocate a dummy here?
661 return ERR(NONE);
662 }
663
664 size_t array_size = klass->NumDirectInterfaces();
665 unsigned char* out_ptr;
666 jvmtiError allocError = env->Allocate(array_size * sizeof(jclass), &out_ptr);
667 if (allocError != ERR(NONE)) {
668 return allocError;
669 }
670 jclass* interface_array = reinterpret_cast<jclass*>(out_ptr);
671
672 art::StackHandleScope<1> hs(soa.Self());
673 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
674
675 for (uint32_t idx = 0; idx != array_size; ++idx) {
676 art::ObjPtr<art::mirror::Class> inf_klass =
677 art::mirror::Class::ResolveDirectInterface(soa.Self(), h_klass, idx);
678 if (inf_klass == nullptr) {
679 soa.Self()->ClearException();
680 env->Deallocate(out_ptr);
681 // TODO: What is the right error code here?
682 return ERR(INTERNAL);
683 }
684 interface_array[idx] = soa.AddLocalReference<jclass>(inf_klass);
685 }
686
687 *interface_count_ptr = static_cast<jint>(array_size);
688 *interfaces_ptr = interface_array;
689
690 return ERR(NONE);
691}
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800692
Andreas Gampee492ae32016-10-28 19:34:57 -0700693jvmtiError ClassUtil::GetClassSignature(jvmtiEnv* env,
694 jclass jklass,
695 char** signature_ptr,
696 char** generic_ptr) {
697 art::ScopedObjectAccess soa(art::Thread::Current());
698 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
699 if (klass == nullptr) {
700 return ERR(INVALID_CLASS);
701 }
702
Andreas Gampe54711412017-02-21 12:41:43 -0800703 JvmtiUniquePtr<char[]> sig_copy;
Andreas Gampee492ae32016-10-28 19:34:57 -0700704 if (signature_ptr != nullptr) {
705 std::string storage;
706 const char* descriptor = klass->GetDescriptor(&storage);
707
Andreas Gampe54711412017-02-21 12:41:43 -0800708 jvmtiError ret;
709 sig_copy = CopyString(env, descriptor, &ret);
710 if (sig_copy == nullptr) {
Andreas Gampee492ae32016-10-28 19:34:57 -0700711 return ret;
712 }
Andreas Gampe54711412017-02-21 12:41:43 -0800713 *signature_ptr = sig_copy.get();
Andreas Gampee492ae32016-10-28 19:34:57 -0700714 }
715
Andreas Gampee6377462017-01-20 17:37:50 -0800716 if (generic_ptr != nullptr) {
717 *generic_ptr = nullptr;
Andreas Gampe0eb36432017-02-15 18:36:14 -0800718 if (!klass->IsProxyClass() && klass->GetDexCache() != nullptr) {
719 art::StackHandleScope<1> hs(soa.Self());
720 art::Handle<art::mirror::Class> h_klass = hs.NewHandle(klass);
Vladimir Markoacb906d2018-05-30 10:23:49 +0100721 art::ObjPtr<art::mirror::ObjectArray<art::mirror::String>> str_array =
Andreas Gampe0eb36432017-02-15 18:36:14 -0800722 art::annotations::GetSignatureAnnotationForClass(h_klass);
723 if (str_array != nullptr) {
724 std::ostringstream oss;
725 for (int32_t i = 0; i != str_array->GetLength(); ++i) {
726 oss << str_array->Get(i)->ToModifiedUtf8();
727 }
728 std::string output_string = oss.str();
Andreas Gampe54711412017-02-21 12:41:43 -0800729 jvmtiError ret;
730 JvmtiUniquePtr<char[]> copy = CopyString(env, output_string.c_str(), &ret);
731 if (copy == nullptr) {
Andreas Gampe0eb36432017-02-15 18:36:14 -0800732 return ret;
733 }
Andreas Gampe54711412017-02-21 12:41:43 -0800734 *generic_ptr = copy.release();
Andreas Gampe0eb36432017-02-15 18:36:14 -0800735 } else if (soa.Self()->IsExceptionPending()) {
736 // TODO: Should we report an error here?
737 soa.Self()->ClearException();
738 }
739 }
Andreas Gampee6377462017-01-20 17:37:50 -0800740 }
Andreas Gampee492ae32016-10-28 19:34:57 -0700741
742 // Everything is fine, release the buffers.
743 sig_copy.release();
744
745 return ERR(NONE);
746}
747
Andreas Gampeff9d2092017-01-06 09:12:49 -0800748jvmtiError ClassUtil::GetClassStatus(jvmtiEnv* env ATTRIBUTE_UNUSED,
749 jclass jklass,
750 jint* status_ptr) {
751 art::ScopedObjectAccess soa(art::Thread::Current());
752 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
753 if (klass == nullptr) {
754 return ERR(INVALID_CLASS);
755 }
756
757 if (status_ptr == nullptr) {
758 return ERR(NULL_POINTER);
759 }
760
761 if (klass->IsArrayClass()) {
762 *status_ptr = JVMTI_CLASS_STATUS_ARRAY;
763 } else if (klass->IsPrimitive()) {
764 *status_ptr = JVMTI_CLASS_STATUS_PRIMITIVE;
765 } else {
766 *status_ptr = JVMTI_CLASS_STATUS_VERIFIED; // All loaded classes are structurally verified.
767 // This is finicky. If there's an error, we'll say it wasn't prepared.
768 if (klass->IsResolved()) {
769 *status_ptr |= JVMTI_CLASS_STATUS_PREPARED;
770 }
771 if (klass->IsInitialized()) {
772 *status_ptr |= JVMTI_CLASS_STATUS_INITIALIZED;
773 }
774 // Technically the class may be erroneous for other reasons, but we do not have enough info.
775 if (klass->IsErroneous()) {
776 *status_ptr |= JVMTI_CLASS_STATUS_ERROR;
777 }
778 }
779
780 return ERR(NONE);
781}
782
Andreas Gampe4fd66ec2017-01-05 14:42:13 -0800783template <typename T>
784static jvmtiError ClassIsT(jclass jklass, T test, jboolean* is_t_ptr) {
785 art::ScopedObjectAccess soa(art::Thread::Current());
786 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
787 if (klass == nullptr) {
788 return ERR(INVALID_CLASS);
789 }
790
791 if (is_t_ptr == nullptr) {
792 return ERR(NULL_POINTER);
793 }
794
795 *is_t_ptr = test(klass) ? JNI_TRUE : JNI_FALSE;
796 return ERR(NONE);
797}
798
799jvmtiError ClassUtil::IsInterface(jvmtiEnv* env ATTRIBUTE_UNUSED,
800 jclass jklass,
801 jboolean* is_interface_ptr) {
802 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
803 return klass->IsInterface();
804 };
805 return ClassIsT(jklass, test, is_interface_ptr);
806}
807
808jvmtiError ClassUtil::IsArrayClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
809 jclass jklass,
810 jboolean* is_array_class_ptr) {
811 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
812 return klass->IsArrayClass();
813 };
814 return ClassIsT(jklass, test, is_array_class_ptr);
815}
816
Andreas Gampe64013e52017-01-06 13:07:19 -0800817// Keep this in sync with Class.getModifiers().
818static uint32_t ClassGetModifiers(art::Thread* self, art::ObjPtr<art::mirror::Class> klass)
819 REQUIRES_SHARED(art::Locks::mutator_lock_) {
820 if (klass->IsArrayClass()) {
821 uint32_t component_modifiers = ClassGetModifiers(self, klass->GetComponentType());
822 if ((component_modifiers & art::kAccInterface) != 0) {
823 component_modifiers &= ~(art::kAccInterface | art::kAccStatic);
824 }
825 return art::kAccAbstract | art::kAccFinal | component_modifiers;
826 }
827
828 uint32_t modifiers = klass->GetAccessFlags() & art::kAccJavaFlagsMask;
829
830 art::StackHandleScope<1> hs(self);
831 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
832 return art::mirror::Class::GetInnerClassFlags(h_klass, modifiers);
833}
834
835jvmtiError ClassUtil::GetClassModifiers(jvmtiEnv* env ATTRIBUTE_UNUSED,
836 jclass jklass,
837 jint* modifiers_ptr) {
838 art::ScopedObjectAccess soa(art::Thread::Current());
839 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
840 if (klass == nullptr) {
841 return ERR(INVALID_CLASS);
842 }
843
844 if (modifiers_ptr == nullptr) {
845 return ERR(NULL_POINTER);
846 }
847
848 *modifiers_ptr = ClassGetModifiers(soa.Self(), klass);
849
850 return ERR(NONE);
851}
852
Andreas Gampe8f5b6032017-01-06 15:50:55 -0800853jvmtiError ClassUtil::GetClassLoader(jvmtiEnv* env ATTRIBUTE_UNUSED,
854 jclass jklass,
855 jobject* classloader_ptr) {
856 art::ScopedObjectAccess soa(art::Thread::Current());
857 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
858 if (klass == nullptr) {
859 return ERR(INVALID_CLASS);
860 }
861
862 if (classloader_ptr == nullptr) {
863 return ERR(NULL_POINTER);
864 }
865
866 *classloader_ptr = soa.AddLocalReference<jobject>(klass->GetClassLoader());
867
868 return ERR(NONE);
869}
870
Alex Lightc7588752018-02-20 11:15:54 -0800871// Copies unique class descriptors into the classes list from dex_files.
872static jvmtiError CopyClassDescriptors(jvmtiEnv* env,
873 const std::vector<const art::DexFile*>& dex_files,
874 /*out*/jint* count_ptr,
875 /*out*/char*** classes) {
876 jvmtiError res = OK;
Vladimir Marko2ef01102019-02-05 15:05:10 +0000877 std::set<std::string_view> unique_descriptors;
Alex Lightc7588752018-02-20 11:15:54 -0800878 std::vector<const char*> descriptors;
879 auto add_descriptor = [&](const char* desc) {
880 // Don't add duplicates.
881 if (res == OK && unique_descriptors.find(desc) == unique_descriptors.end()) {
882 // The desc will remain valid since we hold a ref to the class_loader.
883 unique_descriptors.insert(desc);
884 descriptors.push_back(CopyString(env, desc, &res).release());
885 }
886 };
887 for (const art::DexFile* dex_file : dex_files) {
888 uint32_t num_defs = dex_file->NumClassDefs();
889 for (uint32_t i = 0; i < num_defs; i++) {
890 add_descriptor(dex_file->GetClassDescriptor(dex_file->GetClassDef(i)));
891 }
892 }
893 char** out_data = nullptr;
894 if (res == OK) {
895 res = env->Allocate(sizeof(char*) * descriptors.size(),
896 reinterpret_cast<unsigned char**>(&out_data));
897 }
898 if (res != OK) {
899 env->Deallocate(reinterpret_cast<unsigned char*>(out_data));
900 // Failed to allocate. Cleanup everything.
901 for (const char* data : descriptors) {
902 env->Deallocate(reinterpret_cast<unsigned char*>(const_cast<char*>(data)));
903 }
904 descriptors.clear();
905 return res;
906 }
907 // Everything is good.
908 memcpy(out_data, descriptors.data(), sizeof(char*) * descriptors.size());
909 *count_ptr = static_cast<jint>(descriptors.size());
910 *classes = out_data;
911 return OK;
912}
913
914jvmtiError ClassUtil::GetClassLoaderClassDescriptors(jvmtiEnv* env,
915 jobject loader,
916 /*out*/jint* count_ptr,
917 /*out*/char*** classes) {
918 art::Thread* self = art::Thread::Current();
919 if (env == nullptr) {
920 return ERR(INVALID_ENVIRONMENT);
921 } else if (self == nullptr) {
922 return ERR(UNATTACHED_THREAD);
923 } else if (count_ptr == nullptr || classes == nullptr) {
924 return ERR(NULL_POINTER);
925 }
926 art::JNIEnvExt* jnienv = self->GetJniEnv();
927 if (loader == nullptr ||
928 jnienv->IsInstanceOf(loader, art::WellKnownClasses::java_lang_BootClassLoader)) {
929 // We can just get the dex files directly for the boot class path.
930 return CopyClassDescriptors(env,
931 art::Runtime::Current()->GetClassLinker()->GetBootClassPath(),
932 count_ptr,
933 classes);
934 }
935 if (!jnienv->IsInstanceOf(loader, art::WellKnownClasses::java_lang_ClassLoader)) {
936 return ERR(ILLEGAL_ARGUMENT);
937 } else if (!jnienv->IsInstanceOf(loader,
938 art::WellKnownClasses::dalvik_system_BaseDexClassLoader)) {
Alex Lightae45cbb2018-10-18 15:49:56 -0700939 JVMTI_LOG(ERROR, env) << "GetClassLoaderClassDescriptors is only implemented for "
940 << "BootClassPath and dalvik.system.BaseDexClassLoader class loaders";
Alex Lightc7588752018-02-20 11:15:54 -0800941 // TODO Possibly return OK With no classes would be better since these ones cannot have any
942 // real classes associated with them.
943 return ERR(NOT_IMPLEMENTED);
944 }
945
946 art::ScopedObjectAccess soa(self);
947 art::StackHandleScope<1> hs(self);
948 art::Handle<art::mirror::ClassLoader> class_loader(
949 hs.NewHandle(soa.Decode<art::mirror::ClassLoader>(loader)));
950 std::vector<const art::DexFile*> dex_files;
Andreas Gampeb8e7c372018-02-20 18:24:55 -0800951 art::VisitClassLoaderDexFiles(
952 soa,
Alex Lightc7588752018-02-20 11:15:54 -0800953 class_loader,
Andreas Gampeb8e7c372018-02-20 18:24:55 -0800954 [&](const art::DexFile* dex_file) {
955 dex_files.push_back(dex_file);
956 return true; // Continue with other dex files.
Alex Lightc7588752018-02-20 11:15:54 -0800957 });
958 // We hold the loader so the dex files won't go away until after this call at worst.
959 return CopyClassDescriptors(env, dex_files, count_ptr, classes);
960}
961
Andreas Gampe70f16392017-01-16 14:20:10 -0800962jvmtiError ClassUtil::GetClassLoaderClasses(jvmtiEnv* env,
963 jobject initiating_loader,
964 jint* class_count_ptr,
965 jclass** classes_ptr) {
966 UNUSED(env, initiating_loader, class_count_ptr, classes_ptr);
967
968 if (class_count_ptr == nullptr || classes_ptr == nullptr) {
969 return ERR(NULL_POINTER);
970 }
971 art::Thread* self = art::Thread::Current();
972 if (!self->GetJniEnv()->IsInstanceOf(initiating_loader,
973 art::WellKnownClasses::java_lang_ClassLoader)) {
974 return ERR(ILLEGAL_ARGUMENT);
975 }
976 if (self->GetJniEnv()->IsInstanceOf(initiating_loader,
977 art::WellKnownClasses::java_lang_BootClassLoader)) {
978 // Need to use null for the BootClassLoader.
979 initiating_loader = nullptr;
980 }
981
982 art::ScopedObjectAccess soa(self);
983 art::ObjPtr<art::mirror::ClassLoader> class_loader =
984 soa.Decode<art::mirror::ClassLoader>(initiating_loader);
985
986 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
987
988 art::ReaderMutexLock mu(self, *art::Locks::classlinker_classes_lock_);
989
990 art::ClassTable* class_table = class_linker->ClassTableForClassLoader(class_loader);
991 if (class_table == nullptr) {
992 // Nothing loaded.
993 *class_count_ptr = 0;
994 *classes_ptr = nullptr;
995 return ERR(NONE);
996 }
997
998 struct ClassTableCount {
999 bool operator()(art::ObjPtr<art::mirror::Class> klass) {
1000 DCHECK(klass != nullptr);
1001 ++count;
1002 return true;
1003 }
1004
1005 size_t count = 0;
1006 };
1007 ClassTableCount ctc;
1008 class_table->Visit(ctc);
1009
1010 if (ctc.count == 0) {
1011 // Nothing loaded.
1012 *class_count_ptr = 0;
1013 *classes_ptr = nullptr;
1014 return ERR(NONE);
1015 }
1016
1017 unsigned char* data;
1018 jvmtiError data_result = env->Allocate(ctc.count * sizeof(jclass), &data);
1019 if (data_result != ERR(NONE)) {
1020 return data_result;
1021 }
1022 jclass* class_array = reinterpret_cast<jclass*>(data);
1023
1024 struct ClassTableFill {
1025 bool operator()(art::ObjPtr<art::mirror::Class> klass)
1026 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1027 DCHECK(klass != nullptr);
1028 DCHECK_LT(count, ctc_ref.count);
1029 local_class_array[count++] = soa_ptr->AddLocalReference<jclass>(klass);
1030 return true;
1031 }
1032
1033 jclass* local_class_array;
1034 const ClassTableCount& ctc_ref;
1035 art::ScopedObjectAccess* soa_ptr;
1036 size_t count;
1037 };
1038 ClassTableFill ctf = { class_array, ctc, &soa, 0 };
1039 class_table->Visit(ctf);
1040 DCHECK_EQ(ctc.count, ctf.count);
1041
1042 *class_count_ptr = ctc.count;
1043 *classes_ptr = class_array;
1044
1045 return ERR(NONE);
1046}
1047
Andreas Gampe812a2442017-01-19 22:04:46 -08001048jvmtiError ClassUtil::GetClassVersionNumbers(jvmtiEnv* env ATTRIBUTE_UNUSED,
1049 jclass jklass,
1050 jint* minor_version_ptr,
1051 jint* major_version_ptr) {
1052 art::ScopedObjectAccess soa(art::Thread::Current());
1053 if (jklass == nullptr) {
1054 return ERR(INVALID_CLASS);
1055 }
1056 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1057 if (!jklass_obj->IsClass()) {
1058 return ERR(INVALID_CLASS);
1059 }
1060 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
1061 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1062 return ERR(INVALID_CLASS);
1063 }
1064
1065 if (minor_version_ptr == nullptr || major_version_ptr == nullptr) {
1066 return ERR(NULL_POINTER);
1067 }
1068
1069 // Note: proxies will show the dex file version of java.lang.reflect.Proxy, as that is
1070 // what their dex cache copies from.
1071 uint32_t version = klass->GetDexFile().GetHeader().GetVersion();
1072
1073 *major_version_ptr = static_cast<jint>(version);
1074 *minor_version_ptr = 0;
1075
1076 return ERR(NONE);
1077}
1078
Alex Light6fa7b812017-06-16 09:04:29 -07001079jvmtiError ClassUtil::GetSourceFileName(jvmtiEnv* env, jclass jklass, char** source_name_ptr) {
1080 art::ScopedObjectAccess soa(art::Thread::Current());
1081 if (jklass == nullptr) {
1082 return ERR(INVALID_CLASS);
1083 }
1084 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1085 if (!jklass_obj->IsClass()) {
1086 return ERR(INVALID_CLASS);
1087 }
1088 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
1089 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1090 return ERR(ABSENT_INFORMATION);
1091 }
1092 JvmtiUniquePtr<char[]> source_copy;
1093 const char* file_name = klass->GetSourceFile();
1094 if (file_name == nullptr) {
1095 return ERR(ABSENT_INFORMATION);
1096 }
1097 jvmtiError ret;
1098 source_copy = CopyString(env, file_name, &ret);
1099 if (source_copy == nullptr) {
1100 return ret;
1101 }
1102 *source_name_ptr = source_copy.release();
1103 return OK;
1104}
1105
1106jvmtiError ClassUtil::GetSourceDebugExtension(jvmtiEnv* env,
1107 jclass jklass,
1108 char** source_debug_extension_ptr) {
1109 art::ScopedObjectAccess soa(art::Thread::Current());
1110 if (jklass == nullptr) {
1111 return ERR(INVALID_CLASS);
1112 }
1113 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1114 if (!jklass_obj->IsClass()) {
1115 return ERR(INVALID_CLASS);
1116 }
1117 art::StackHandleScope<1> hs(art::Thread::Current());
1118 art::Handle<art::mirror::Class> klass(hs.NewHandle(jklass_obj->AsClass()));
1119 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1120 return ERR(ABSENT_INFORMATION);
1121 }
1122 JvmtiUniquePtr<char[]> ext_copy;
1123 const char* data = art::annotations::GetSourceDebugExtension(klass);
1124 if (data == nullptr) {
1125 return ERR(ABSENT_INFORMATION);
1126 }
1127 jvmtiError ret;
1128 ext_copy = CopyString(env, data, &ret);
1129 if (ext_copy == nullptr) {
1130 return ret;
1131 }
1132 *source_debug_extension_ptr = ext_copy.release();
1133 return OK;
1134}
1135
Andreas Gampee492ae32016-10-28 19:34:57 -07001136} // namespace openjdkjvmti