blob: a8e220cc21369908f316d82363ff83aea6c1abb1 [file] [log] [blame]
Andreas Gampee492ae32016-10-28 19:34:57 -07001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_class.h"
33
Alex Light440b5d92017-01-24 15:32:25 -080034#include "android-base/stringprintf.h"
35
Igor Murashkin5573c372017-11-16 13:34:30 -080036#include <mutex>
Andreas Gampee6377462017-01-20 17:37:50 -080037#include <unordered_set>
38
Andreas Gampee492ae32016-10-28 19:34:57 -070039#include "art_jvmti.h"
Vladimir Markoe1993c72017-06-14 17:01:38 +010040#include "base/array_ref.h"
Andreas Gampee6377462017-01-20 17:37:50 -080041#include "base/macros.h"
David Sehrc431b9d2018-03-02 12:01:51 -080042#include "base/utils.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080043#include "class_linker.h"
Andreas Gampeb8e7c372018-02-20 18:24:55 -080044#include "class_loader_utils.h"
Steven Morelande431e272017-07-18 16:53:49 -070045#include "class_table-inl.h"
Alex Light440b5d92017-01-24 15:32:25 -080046#include "common_throws.h"
David Sehr013fd802018-01-11 22:55:24 -080047#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080048#include "dex/dex_file_annotations.h"
49#include "dex/dex_file_loader.h"
David Sehr67bf42e2018-02-26 16:43:04 -080050#include "dex/primitive.h"
Andreas Gampee6377462017-01-20 17:37:50 -080051#include "events-inl.h"
Alex Light40528472017-03-28 09:07:36 -070052#include "fixed_up_dex_file.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070053#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070054#include "gc/heap.h"
Andreas Gampe691051b2017-02-09 09:15:24 -080055#include "gc_root.h"
Andreas Gampee6377462017-01-20 17:37:50 -080056#include "handle.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010057#include "jni/jni_env_ext-inl.h"
58#include "jni/jni_internal.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070059#include "mirror/array-alloc-inl.h"
Alex Light440b5d92017-01-24 15:32:25 -080060#include "mirror/array-inl.h"
61#include "mirror/class-inl.h"
62#include "mirror/class_ext.h"
Andreas Gampea67354b2017-02-10 16:18:30 -080063#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080064#include "mirror/object-refvisitor-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070065#include "mirror/object_array-inl.h"
66#include "mirror/object_reference.h"
Vladimir Marko6834d342018-05-25 13:12:09 +010067#include "mirror/reference-inl.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070068#include "nativehelper/scoped_local_ref.h"
Alex Light6a656312017-03-29 17:18:00 -070069#include "reflection.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080070#include "runtime.h"
Andreas Gampee6377462017-01-20 17:37:50 -080071#include "runtime_callbacks.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070072#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070073#include "thread-current-inl.h"
Andreas Gampee6377462017-01-20 17:37:50 -080074#include "thread_list.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010075#include "ti_class_definition.h"
Alex Lightc7588752018-02-20 11:15:54 -080076#include "ti_class_loader-inl.h"
Alex Lightae45cbb2018-10-18 15:49:56 -070077#include "ti_logging.h"
Alex Lightd8ce4e72017-02-27 10:52:29 -080078#include "ti_phase.h"
Alex Light440b5d92017-01-24 15:32:25 -080079#include "ti_redefine.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010080#include "transform.h"
Andreas Gampea1d2f952017-04-20 22:53:58 -070081#include "well_known_classes.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070082
83namespace openjdkjvmti {
84
Alex Light440b5d92017-01-24 15:32:25 -080085using android::base::StringPrintf;
86
87static std::unique_ptr<const art::DexFile> MakeSingleDexFile(art::Thread* self,
88 const char* descriptor,
89 const std::string& orig_location,
90 jint final_len,
91 const unsigned char* final_dex_data)
92 REQUIRES_SHARED(art::Locks::mutator_lock_) {
93 // Make the mmap
94 std::string error_msg;
Vladimir Markoe1993c72017-06-14 17:01:38 +010095 art::ArrayRef<const unsigned char> final_data(final_dex_data, final_len);
Vladimir Markoc34bebf2018-08-16 16:12:49 +010096 art::MemMap map = Redefiner::MoveDataToMemMap(orig_location, final_data, &error_msg);
97 if (!map.IsValid()) {
Alex Light440b5d92017-01-24 15:32:25 -080098 LOG(WARNING) << "Unable to allocate mmap for redefined dex file! Error was: " << error_msg;
99 self->ThrowOutOfMemoryError(StringPrintf(
100 "Unable to allocate dex file for transformation of %s", descriptor).c_str());
101 return nullptr;
102 }
103
104 // Make a dex-file
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100105 if (map.Size() < sizeof(art::DexFile::Header)) {
Alex Light440b5d92017-01-24 15:32:25 -0800106 LOG(WARNING) << "Could not read dex file header because dex_data was too short";
107 art::ThrowClassFormatError(nullptr,
108 "Unable to read transformed dex file of %s",
109 descriptor);
110 return nullptr;
111 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100112 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map.Begin())->checksum_;
113 std::string map_name = map.GetName();
David Sehr013fd802018-01-11 22:55:24 -0800114 const art::ArtDexFileLoader dex_file_loader;
115 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(map_name,
116 checksum,
117 std::move(map),
Andreas Gampe6e897762018-10-16 13:09:32 -0700118 /*verify=*/true,
119 /*verify_checksum=*/true,
David Sehr013fd802018-01-11 22:55:24 -0800120 &error_msg));
Alex Light440b5d92017-01-24 15:32:25 -0800121 if (dex_file.get() == nullptr) {
122 LOG(WARNING) << "Unable to load modified dex file for " << descriptor << ": " << error_msg;
123 art::ThrowClassFormatError(nullptr,
124 "Unable to read transformed dex file of %s because %s",
125 descriptor,
126 error_msg.c_str());
127 return nullptr;
128 }
129 if (dex_file->NumClassDefs() != 1) {
130 LOG(WARNING) << "Dex file contains more than 1 class_def. Ignoring.";
131 // TODO Throw some other sort of error here maybe?
132 art::ThrowClassFormatError(
133 nullptr,
134 "Unable to use transformed dex file of %s because it contained too many classes",
135 descriptor);
136 return nullptr;
137 }
138 return dex_file;
139}
140
Alex Light28b6e7e2017-05-22 16:05:59 -0700141// A deleter that acts like the jvmtiEnv->Deallocate so that asan does not get tripped up.
142// TODO We should everything use the actual jvmtiEnv->Allocate/Deallocate functions once we can
143// figure out which env to use.
144template <typename T>
145class FakeJvmtiDeleter {
146 public:
147 FakeJvmtiDeleter() {}
148
149 FakeJvmtiDeleter(FakeJvmtiDeleter&) = default;
Andreas Gampe44b31742018-10-01 19:30:57 -0700150 FakeJvmtiDeleter(FakeJvmtiDeleter&&) noexcept = default;
Alex Light28b6e7e2017-05-22 16:05:59 -0700151 FakeJvmtiDeleter& operator=(const FakeJvmtiDeleter&) = default;
152
153 template <typename U> void operator()(const U* ptr) const {
154 if (ptr != nullptr) {
155 free(const_cast<U*>(ptr));
156 }
157 }
158};
159
Andreas Gampee6377462017-01-20 17:37:50 -0800160struct ClassCallback : public art::ClassLoadCallback {
Alex Light440b5d92017-01-24 15:32:25 -0800161 void ClassPreDefine(const char* descriptor,
162 art::Handle<art::mirror::Class> klass,
163 art::Handle<art::mirror::ClassLoader> class_loader,
164 const art::DexFile& initial_dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800165 const art::dex::ClassDef& initial_class_def ATTRIBUTE_UNUSED,
Alex Light440b5d92017-01-24 15:32:25 -0800166 /*out*/art::DexFile const** final_dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800167 /*out*/art::dex::ClassDef const** final_class_def)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100168 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light440b5d92017-01-24 15:32:25 -0800169 bool is_enabled =
170 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookRetransformable) ||
171 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookNonRetransformable);
172 if (!is_enabled) {
173 return;
174 }
175 if (descriptor[0] != 'L') {
176 // It is a primitive or array. Just return
177 return;
178 }
Alex Lightd8ce4e72017-02-27 10:52:29 -0800179 jvmtiPhase phase = PhaseUtil::GetPhaseUnchecked();
180 if (UNLIKELY(phase != JVMTI_PHASE_START && phase != JVMTI_PHASE_LIVE)) {
181 // We want to wait until we are at least in the START phase so that all WellKnownClasses and
182 // mirror classes have been initialized and loaded. The runtime relies on these classes having
183 // specific fields and methods present. Since PreDefine hooks don't need to abide by this
184 // restriction we will simply not send the event for these classes.
185 LOG(WARNING) << "Ignoring load of class <" << descriptor << "> as it is being loaded during "
186 << "runtime initialization.";
187 return;
188 }
189
Alex Light440b5d92017-01-24 15:32:25 -0800190 art::Thread* self = art::Thread::Current();
Alex Light64e4c142018-01-30 13:46:37 -0800191 ArtClassDefinition def;
192 def.InitFirstLoad(descriptor, class_loader, initial_dex_file);
Alex Light40528472017-03-28 09:07:36 -0700193
Alex Light64e4c142018-01-30 13:46:37 -0800194 // Call all non-retransformable agents.
195 Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookNonRetransformable>(
196 event_handler, self, &def);
197
198 std::vector<unsigned char> post_non_retransform;
199 if (def.IsModified()) {
200 // Copy the dex data after the non-retransformable events.
201 post_non_retransform.resize(def.GetDexData().size());
202 memcpy(post_non_retransform.data(), def.GetDexData().data(), post_non_retransform.size());
Alex Light440b5d92017-01-24 15:32:25 -0800203 }
Alex Light64e4c142018-01-30 13:46:37 -0800204
Alex Light440b5d92017-01-24 15:32:25 -0800205 // Call all retransformable agents.
Alex Light64e4c142018-01-30 13:46:37 -0800206 Transformer::TransformSingleClassDirect<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
207 event_handler, self, &def);
Alex Light440b5d92017-01-24 15:32:25 -0800208
Alex Light64e4c142018-01-30 13:46:37 -0800209 if (def.IsModified()) {
Alex Light440b5d92017-01-24 15:32:25 -0800210 LOG(WARNING) << "Changing class " << descriptor;
Alex Light440b5d92017-01-24 15:32:25 -0800211 art::StackHandleScope<2> hs(self);
212 // Save the results of all the non-retransformable agents.
213 // First allocate the ClassExt
214 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(self)));
215 // Make sure we have a ClassExt. This is fine even though we are a temporary since it will
216 // get copied.
217 if (ext.IsNull()) {
218 // We will just return failure if we fail to allocate
219 LOG(WARNING) << "Could not allocate ext-data for class '" << descriptor << "'. "
220 << "Aborting transformation since we will be unable to store it.";
221 self->AssertPendingOOMException();
222 return;
223 }
224
225 // Allocate the byte array to store the dex file bytes in.
Alex Light6a656312017-03-29 17:18:00 -0700226 art::MutableHandle<art::mirror::Object> arr(hs.NewHandle<art::mirror::Object>(nullptr));
Alex Light64e4c142018-01-30 13:46:37 -0800227 if (post_non_retransform.empty() && strcmp(descriptor, "Ljava/lang/Long;") != 0) {
Alex Light6a656312017-03-29 17:18:00 -0700228 // we didn't have any non-retransformable agents. We can just cache a pointer to the
229 // initial_dex_file. It will be kept live by the class_loader.
230 jlong dex_ptr = reinterpret_cast<uintptr_t>(&initial_dex_file);
231 art::JValue val;
232 val.SetJ(dex_ptr);
233 arr.Assign(art::BoxPrimitive(art::Primitive::kPrimLong, val));
234 } else {
235 arr.Assign(art::mirror::ByteArray::AllocateAndFill(
236 self,
Alex Light64e4c142018-01-30 13:46:37 -0800237 reinterpret_cast<const signed char*>(post_non_retransform.data()),
238 post_non_retransform.size()));
Alex Light6a656312017-03-29 17:18:00 -0700239 }
Alex Light440b5d92017-01-24 15:32:25 -0800240 if (arr.IsNull()) {
Alex Light6a656312017-03-29 17:18:00 -0700241 LOG(WARNING) << "Unable to allocate memory for initial dex-file. Aborting transformation";
Alex Light440b5d92017-01-24 15:32:25 -0800242 self->AssertPendingOOMException();
243 return;
244 }
245
246 std::unique_ptr<const art::DexFile> dex_file(MakeSingleDexFile(self,
247 descriptor,
248 initial_dex_file.GetLocation(),
Alex Light64e4c142018-01-30 13:46:37 -0800249 def.GetDexData().size(),
250 def.GetDexData().data()));
Alex Light440b5d92017-01-24 15:32:25 -0800251 if (dex_file.get() == nullptr) {
252 return;
253 }
254
Alex Lighteb98b082017-01-25 13:02:32 -0800255 // TODO Check Redefined dex file for all invariants.
Alex Light440b5d92017-01-24 15:32:25 -0800256 LOG(WARNING) << "Dex file created by class-definition time transformation of "
257 << descriptor << " is not checked for all retransformation invariants.";
Alex Lighteb98b082017-01-25 13:02:32 -0800258
259 if (!ClassLoaderHelper::AddToClassLoader(self, class_loader, dex_file.get())) {
260 LOG(ERROR) << "Unable to add " << descriptor << " to class loader!";
261 return;
262 }
263
Alex Light440b5d92017-01-24 15:32:25 -0800264 // Actually set the ClassExt's original bytes once we have actually succeeded.
Alex Light2f814aa2017-03-24 15:21:34 +0000265 ext->SetOriginalDexFile(arr.Get());
Alex Light440b5d92017-01-24 15:32:25 -0800266 // Set the return values
267 *final_class_def = &dex_file->GetClassDef(0);
268 *final_dex_file = dex_file.release();
269 }
270 }
271
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700272 void ClassLoad(art::Handle<art::mirror::Class> klass) override
273 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampee6377462017-01-20 17:37:50 -0800274 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassLoad)) {
275 art::Thread* thread = art::Thread::Current();
276 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
277 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700278 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800279 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700280 thread->GetJniEnv(),
281 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Alex Light9df79b72017-09-12 08:57:31 -0700282 event_handler->DispatchEvent<ArtJvmtiEvent::kClassLoad>(
283 thread,
284 static_cast<JNIEnv*>(thread->GetJniEnv()),
285 thread_jni.get(),
286 jklass.get());
Andreas Gampe691051b2017-02-09 09:15:24 -0800287 if (klass->IsTemp()) {
288 AddTempClass(thread, jklass.get());
289 }
Andreas Gampee6377462017-01-20 17:37:50 -0800290 }
291 }
292
Andreas Gampe691051b2017-02-09 09:15:24 -0800293 void ClassPrepare(art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800294 art::Handle<art::mirror::Class> klass)
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700295 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampee6377462017-01-20 17:37:50 -0800296 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassPrepare)) {
297 art::Thread* thread = art::Thread::Current();
Andreas Gampe691051b2017-02-09 09:15:24 -0800298 if (temp_klass.Get() != klass.Get()) {
299 DCHECK(temp_klass->IsTemp());
300 DCHECK(temp_klass->IsRetired());
301 HandleTempClass(thread, temp_klass, klass);
302 }
Andreas Gampee6377462017-01-20 17:37:50 -0800303 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
304 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700305 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800306 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700307 thread->GetJniEnv(),
308 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Andreas Gampe983c1752017-01-23 19:46:56 -0800309 event_handler->DispatchEvent<ArtJvmtiEvent::kClassPrepare>(
310 thread,
311 static_cast<JNIEnv*>(thread->GetJniEnv()),
312 thread_jni.get(),
313 jklass.get());
Andreas Gampee6377462017-01-20 17:37:50 -0800314 }
315 }
316
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800317 // To support parallel class-loading, we need to perform some locking dances here. Namely,
318 // the fixup stage must not be holding the temp_classes lock when it fixes up the system
319 // (as that requires suspending all mutators).
320
Andreas Gampee6377462017-01-20 17:37:50 -0800321 void AddTempClass(art::Thread* self, jclass klass) {
322 std::unique_lock<std::mutex> mu(temp_classes_lock);
Andreas Gampe691051b2017-02-09 09:15:24 -0800323 jclass global_klass = reinterpret_cast<jclass>(self->GetJniEnv()->NewGlobalRef(klass));
324 temp_classes.push_back(global_klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800325 }
326
Andreas Gampe691051b2017-02-09 09:15:24 -0800327 void HandleTempClass(art::Thread* self,
328 art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800329 art::Handle<art::mirror::Class> klass)
330 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800331 bool requires_fixup = false;
332 {
333 std::unique_lock<std::mutex> mu(temp_classes_lock);
334 if (temp_classes.empty()) {
335 return;
Andreas Gampee6377462017-01-20 17:37:50 -0800336 }
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800337
338 for (auto it = temp_classes.begin(); it != temp_classes.end(); ++it) {
339 if (temp_klass.Get() == art::ObjPtr<art::mirror::Class>::DownCast(self->DecodeJObject(*it))) {
340 self->GetJniEnv()->DeleteGlobalRef(*it);
341 temp_classes.erase(it);
342 requires_fixup = true;
343 break;
344 }
345 }
346 }
347 if (requires_fixup) {
348 FixupTempClass(self, temp_klass, klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800349 }
350 }
351
Andreas Gampe691051b2017-02-09 09:15:24 -0800352 void FixupTempClass(art::Thread* self,
353 art::Handle<art::mirror::Class> temp_klass,
354 art::Handle<art::mirror::Class> klass)
Andreas Gampee6377462017-01-20 17:37:50 -0800355 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe691051b2017-02-09 09:15:24 -0800356 // Suspend everything.
357 art::gc::Heap* heap = art::Runtime::Current()->GetHeap();
358 if (heap->IsGcConcurrentAndMoving()) {
359 // Need to take a heap dump while GC isn't running. See the
360 // comment in Heap::VisitObjects().
361 heap->IncrementDisableMovingGC(self);
362 }
363 {
364 art::ScopedThreadSuspension sts(self, art::kWaitingForVisitObjects);
365 art::ScopedSuspendAll ssa("FixupTempClass");
366
367 art::mirror::Class* input = temp_klass.Get();
368 art::mirror::Class* output = klass.Get();
369
370 FixupGlobalReferenceTables(input, output);
Andreas Gampe94dda932017-02-09 18:19:21 -0800371 FixupLocalReferenceTables(self, input, output);
Andreas Gampea67354b2017-02-10 16:18:30 -0800372 FixupHeap(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800373 }
374 if (heap->IsGcConcurrentAndMoving()) {
375 heap->DecrementDisableMovingGC(self);
376 }
377 }
378
Andreas Gampe94dda932017-02-09 18:19:21 -0800379 class RootUpdater : public art::RootVisitor {
380 public:
381 RootUpdater(const art::mirror::Class* input, art::mirror::Class* output)
382 : input_(input), output_(output) {}
383
384 void VisitRoots(art::mirror::Object*** roots,
385 size_t count,
386 const art::RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100387 override {
Andreas Gampe94dda932017-02-09 18:19:21 -0800388 for (size_t i = 0; i != count; ++i) {
389 if (*roots[i] == input_) {
390 *roots[i] = output_;
391 }
392 }
393 }
394
395 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
396 size_t count,
397 const art::RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100398 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe94dda932017-02-09 18:19:21 -0800399 for (size_t i = 0; i != count; ++i) {
400 if (roots[i]->AsMirrorPtr() == input_) {
401 roots[i]->Assign(output_);
402 }
403 }
404 }
405
406 private:
407 const art::mirror::Class* input_;
408 art::mirror::Class* output_;
409 };
410
Andreas Gampea67354b2017-02-10 16:18:30 -0800411 void FixupGlobalReferenceTables(art::mirror::Class* input, art::mirror::Class* output)
Andreas Gampe691051b2017-02-09 09:15:24 -0800412 REQUIRES(art::Locks::mutator_lock_) {
413 art::JavaVMExt* java_vm = art::Runtime::Current()->GetJavaVM();
414
415 // Fix up the global table with a root visitor.
Andreas Gampe94dda932017-02-09 18:19:21 -0800416 RootUpdater global_update(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800417 java_vm->VisitRoots(&global_update);
418
419 class WeakGlobalUpdate : public art::IsMarkedVisitor {
420 public:
421 WeakGlobalUpdate(art::mirror::Class* root_input, art::mirror::Class* root_output)
422 : input_(root_input), output_(root_output) {}
423
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100424 art::mirror::Object* IsMarked(art::mirror::Object* obj) override {
Andreas Gampe691051b2017-02-09 09:15:24 -0800425 if (obj == input_) {
426 return output_;
427 }
428 return obj;
429 }
430
431 private:
432 const art::mirror::Class* input_;
433 art::mirror::Class* output_;
434 };
435 WeakGlobalUpdate weak_global_update(input, output);
436 java_vm->SweepJniWeakGlobals(&weak_global_update);
Andreas Gampee6377462017-01-20 17:37:50 -0800437 }
438
Andreas Gampe94dda932017-02-09 18:19:21 -0800439 void FixupLocalReferenceTables(art::Thread* self,
440 art::mirror::Class* input,
441 art::mirror::Class* output)
442 REQUIRES(art::Locks::mutator_lock_) {
443 class LocalUpdate {
444 public:
445 LocalUpdate(const art::mirror::Class* root_input, art::mirror::Class* root_output)
446 : input_(root_input), output_(root_output) {}
447
448 static void Callback(art::Thread* t, void* arg) REQUIRES(art::Locks::mutator_lock_) {
449 LocalUpdate* local = reinterpret_cast<LocalUpdate*>(arg);
450
451 // Fix up the local table with a root visitor.
452 RootUpdater local_update(local->input_, local->output_);
Ian Rogers55256cb2017-12-21 17:07:11 -0800453 t->GetJniEnv()->VisitJniLocalRoots(
Andreas Gampe94dda932017-02-09 18:19:21 -0800454 &local_update, art::RootInfo(art::kRootJNILocal, t->GetThreadId()));
455 }
456
457 private:
458 const art::mirror::Class* input_;
459 art::mirror::Class* output_;
460 };
461 LocalUpdate local_upd(input, output);
462 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
463 art::Runtime::Current()->GetThreadList()->ForEach(LocalUpdate::Callback, &local_upd);
464 }
465
Andreas Gampea67354b2017-02-10 16:18:30 -0800466 void FixupHeap(art::mirror::Class* input, art::mirror::Class* output)
467 REQUIRES(art::Locks::mutator_lock_) {
468 class HeapFixupVisitor {
469 public:
470 HeapFixupVisitor(const art::mirror::Class* root_input, art::mirror::Class* root_output)
471 : input_(root_input), output_(root_output) {}
472
473 void operator()(art::mirror::Object* src,
474 art::MemberOffset field_offset,
475 bool is_static ATTRIBUTE_UNUSED) const
476 REQUIRES_SHARED(art::Locks::mutator_lock_) {
477 art::mirror::HeapReference<art::mirror::Object>* trg =
478 src->GetFieldObjectReferenceAddr(field_offset);
479 if (trg->AsMirrorPtr() == input_) {
480 DCHECK_NE(field_offset.Uint32Value(), 0u); // This shouldn't be the class field of
481 // an object.
482 trg->Assign(output_);
483 }
484 }
485
Andreas Gampe52784ac2017-02-13 18:10:09 -0800486 void operator()(art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
487 art::ObjPtr<art::mirror::Reference> reference) const
488 REQUIRES_SHARED(art::Locks::mutator_lock_) {
489 art::mirror::Object* val = reference->GetReferent();
490 if (val == input_) {
491 reference->SetReferent<false>(output_);
492 }
493 }
494
Andreas Gampea67354b2017-02-10 16:18:30 -0800495 void VisitRoot(art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED)
Andreas Gampe52784ac2017-02-13 18:10:09 -0800496 const {
Andreas Gampea67354b2017-02-10 16:18:30 -0800497 LOG(FATAL) << "Unreachable";
498 }
499
500 void VisitRootIfNonNull(
501 art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED) const {
502 LOG(FATAL) << "Unreachable";
503 }
504
Andreas Gampea67354b2017-02-10 16:18:30 -0800505 private:
506 const art::mirror::Class* input_;
507 art::mirror::Class* output_;
508 };
509 HeapFixupVisitor hfv(input, output);
Andreas Gampe1c158a02017-07-13 17:26:19 -0700510 auto object_visitor = [&](art::mirror::Object* obj) {
511 obj->VisitReferences<false>(hfv, hfv); // Visit references, not native roots.
512 };
513 art::Runtime::Current()->GetHeap()->VisitObjectsPaused(object_visitor);
Andreas Gampea67354b2017-02-10 16:18:30 -0800514 }
515
Andreas Gampee6377462017-01-20 17:37:50 -0800516 // A set of all the temp classes we have handed out. We have to fix up references to these.
517 // For simplicity, we store the temp classes as JNI global references in a vector. Normally a
518 // Prepare event will closely follow, so the vector should be small.
519 std::mutex temp_classes_lock;
520 std::vector<jclass> temp_classes;
521
522 EventHandler* event_handler = nullptr;
523};
524
525ClassCallback gClassCallback;
526
527void ClassUtil::Register(EventHandler* handler) {
528 gClassCallback.event_handler = handler;
529 art::ScopedThreadStateChange stsc(art::Thread::Current(),
530 art::ThreadState::kWaitingForDebuggerToAttach);
531 art::ScopedSuspendAll ssa("Add load callback");
532 art::Runtime::Current()->GetRuntimeCallbacks()->AddClassLoadCallback(&gClassCallback);
533}
534
535void ClassUtil::Unregister() {
536 art::ScopedThreadStateChange stsc(art::Thread::Current(),
537 art::ThreadState::kWaitingForDebuggerToAttach);
538 art::ScopedSuspendAll ssa("Remove thread callback");
539 art::Runtime* runtime = art::Runtime::Current();
540 runtime->GetRuntimeCallbacks()->RemoveClassLoadCallback(&gClassCallback);
541}
542
Andreas Gampeac587272017-01-05 15:21:34 -0800543jvmtiError ClassUtil::GetClassFields(jvmtiEnv* env,
544 jclass jklass,
545 jint* field_count_ptr,
546 jfieldID** fields_ptr) {
547 art::ScopedObjectAccess soa(art::Thread::Current());
548 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
549 if (klass == nullptr) {
550 return ERR(INVALID_CLASS);
551 }
552
Alex Light2c6cd692017-06-30 07:34:40 -0700553 // Check if this class is a temporary class object used for loading. Since we are seeing it the
554 // class must not have been prepared yet since otherwise the fixup would have gotten the jobject
555 // to point to the final class object.
556 if (klass->IsTemp() || klass->IsRetired()) {
557 return ERR(CLASS_NOT_PREPARED);
558 }
559
Andreas Gampeac587272017-01-05 15:21:34 -0800560 if (field_count_ptr == nullptr || fields_ptr == nullptr) {
561 return ERR(NULL_POINTER);
562 }
563
Andreas Gampeac587272017-01-05 15:21:34 -0800564 art::IterationRange<art::StrideIterator<art::ArtField>> ifields = klass->GetIFields();
565 art::IterationRange<art::StrideIterator<art::ArtField>> sfields = klass->GetSFields();
566 size_t array_size = klass->NumInstanceFields() + klass->NumStaticFields();
567
568 unsigned char* out_ptr;
569 jvmtiError allocError = env->Allocate(array_size * sizeof(jfieldID), &out_ptr);
570 if (allocError != ERR(NONE)) {
571 return allocError;
572 }
573 jfieldID* field_array = reinterpret_cast<jfieldID*>(out_ptr);
574
575 size_t array_idx = 0;
576 for (art::ArtField& field : sfields) {
577 field_array[array_idx] = art::jni::EncodeArtField(&field);
578 ++array_idx;
579 }
580 for (art::ArtField& field : ifields) {
581 field_array[array_idx] = art::jni::EncodeArtField(&field);
582 ++array_idx;
583 }
584
585 *field_count_ptr = static_cast<jint>(array_size);
586 *fields_ptr = field_array;
587
588 return ERR(NONE);
589}
590
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800591jvmtiError ClassUtil::GetClassMethods(jvmtiEnv* env,
592 jclass jklass,
593 jint* method_count_ptr,
594 jmethodID** methods_ptr) {
595 art::ScopedObjectAccess soa(art::Thread::Current());
596 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
597 if (klass == nullptr) {
598 return ERR(INVALID_CLASS);
599 }
600
Alex Light2c6cd692017-06-30 07:34:40 -0700601 // Check if this class is a temporary class object used for loading. Since we are seeing it the
602 // class must not have been prepared yet since otherwise the fixup would have gotten the jobject
603 // to point to the final class object.
604 if (klass->IsTemp() || klass->IsRetired()) {
605 return ERR(CLASS_NOT_PREPARED);
606 }
607
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800608 if (method_count_ptr == nullptr || methods_ptr == nullptr) {
609 return ERR(NULL_POINTER);
610 }
611
612 size_t array_size = klass->NumDeclaredVirtualMethods() + klass->NumDirectMethods();
613 unsigned char* out_ptr;
614 jvmtiError allocError = env->Allocate(array_size * sizeof(jmethodID), &out_ptr);
615 if (allocError != ERR(NONE)) {
616 return allocError;
617 }
618 jmethodID* method_array = reinterpret_cast<jmethodID*>(out_ptr);
619
620 if (art::kIsDebugBuild) {
621 size_t count = 0;
622 for (auto& m ATTRIBUTE_UNUSED : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
623 count++;
624 }
625 CHECK_EQ(count, klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods());
626 }
627
628 size_t array_idx = 0;
629 for (auto& m : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
630 method_array[array_idx] = art::jni::EncodeArtMethod(&m);
631 ++array_idx;
632 }
633
634 *method_count_ptr = static_cast<jint>(array_size);
635 *methods_ptr = method_array;
636
637 return ERR(NONE);
638}
639
Andreas Gampe8b07e472017-01-06 14:20:39 -0800640jvmtiError ClassUtil::GetImplementedInterfaces(jvmtiEnv* env,
641 jclass jklass,
642 jint* interface_count_ptr,
643 jclass** interfaces_ptr) {
644 art::ScopedObjectAccess soa(art::Thread::Current());
645 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
646 if (klass == nullptr) {
647 return ERR(INVALID_CLASS);
648 }
649
650 if (interface_count_ptr == nullptr || interfaces_ptr == nullptr) {
651 return ERR(NULL_POINTER);
652 }
653
654 // Need to handle array specifically. Arrays implement Serializable and Cloneable, but the
655 // spec says these should not be reported.
656 if (klass->IsArrayClass()) {
657 *interface_count_ptr = 0;
658 *interfaces_ptr = nullptr; // TODO: Should we allocate a dummy here?
659 return ERR(NONE);
660 }
661
662 size_t array_size = klass->NumDirectInterfaces();
663 unsigned char* out_ptr;
664 jvmtiError allocError = env->Allocate(array_size * sizeof(jclass), &out_ptr);
665 if (allocError != ERR(NONE)) {
666 return allocError;
667 }
668 jclass* interface_array = reinterpret_cast<jclass*>(out_ptr);
669
670 art::StackHandleScope<1> hs(soa.Self());
671 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
672
673 for (uint32_t idx = 0; idx != array_size; ++idx) {
674 art::ObjPtr<art::mirror::Class> inf_klass =
675 art::mirror::Class::ResolveDirectInterface(soa.Self(), h_klass, idx);
676 if (inf_klass == nullptr) {
677 soa.Self()->ClearException();
678 env->Deallocate(out_ptr);
679 // TODO: What is the right error code here?
680 return ERR(INTERNAL);
681 }
682 interface_array[idx] = soa.AddLocalReference<jclass>(inf_klass);
683 }
684
685 *interface_count_ptr = static_cast<jint>(array_size);
686 *interfaces_ptr = interface_array;
687
688 return ERR(NONE);
689}
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800690
Andreas Gampee492ae32016-10-28 19:34:57 -0700691jvmtiError ClassUtil::GetClassSignature(jvmtiEnv* env,
692 jclass jklass,
693 char** signature_ptr,
694 char** generic_ptr) {
695 art::ScopedObjectAccess soa(art::Thread::Current());
696 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
697 if (klass == nullptr) {
698 return ERR(INVALID_CLASS);
699 }
700
Andreas Gampe54711412017-02-21 12:41:43 -0800701 JvmtiUniquePtr<char[]> sig_copy;
Andreas Gampee492ae32016-10-28 19:34:57 -0700702 if (signature_ptr != nullptr) {
703 std::string storage;
704 const char* descriptor = klass->GetDescriptor(&storage);
705
Andreas Gampe54711412017-02-21 12:41:43 -0800706 jvmtiError ret;
707 sig_copy = CopyString(env, descriptor, &ret);
708 if (sig_copy == nullptr) {
Andreas Gampee492ae32016-10-28 19:34:57 -0700709 return ret;
710 }
Andreas Gampe54711412017-02-21 12:41:43 -0800711 *signature_ptr = sig_copy.get();
Andreas Gampee492ae32016-10-28 19:34:57 -0700712 }
713
Andreas Gampee6377462017-01-20 17:37:50 -0800714 if (generic_ptr != nullptr) {
715 *generic_ptr = nullptr;
Andreas Gampe0eb36432017-02-15 18:36:14 -0800716 if (!klass->IsProxyClass() && klass->GetDexCache() != nullptr) {
717 art::StackHandleScope<1> hs(soa.Self());
718 art::Handle<art::mirror::Class> h_klass = hs.NewHandle(klass);
Vladimir Markoacb906d2018-05-30 10:23:49 +0100719 art::ObjPtr<art::mirror::ObjectArray<art::mirror::String>> str_array =
Andreas Gampe0eb36432017-02-15 18:36:14 -0800720 art::annotations::GetSignatureAnnotationForClass(h_klass);
721 if (str_array != nullptr) {
722 std::ostringstream oss;
723 for (int32_t i = 0; i != str_array->GetLength(); ++i) {
724 oss << str_array->Get(i)->ToModifiedUtf8();
725 }
726 std::string output_string = oss.str();
Andreas Gampe54711412017-02-21 12:41:43 -0800727 jvmtiError ret;
728 JvmtiUniquePtr<char[]> copy = CopyString(env, output_string.c_str(), &ret);
729 if (copy == nullptr) {
Andreas Gampe0eb36432017-02-15 18:36:14 -0800730 return ret;
731 }
Andreas Gampe54711412017-02-21 12:41:43 -0800732 *generic_ptr = copy.release();
Andreas Gampe0eb36432017-02-15 18:36:14 -0800733 } else if (soa.Self()->IsExceptionPending()) {
734 // TODO: Should we report an error here?
735 soa.Self()->ClearException();
736 }
737 }
Andreas Gampee6377462017-01-20 17:37:50 -0800738 }
Andreas Gampee492ae32016-10-28 19:34:57 -0700739
740 // Everything is fine, release the buffers.
741 sig_copy.release();
742
743 return ERR(NONE);
744}
745
Andreas Gampeff9d2092017-01-06 09:12:49 -0800746jvmtiError ClassUtil::GetClassStatus(jvmtiEnv* env ATTRIBUTE_UNUSED,
747 jclass jklass,
748 jint* status_ptr) {
749 art::ScopedObjectAccess soa(art::Thread::Current());
750 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
751 if (klass == nullptr) {
752 return ERR(INVALID_CLASS);
753 }
754
755 if (status_ptr == nullptr) {
756 return ERR(NULL_POINTER);
757 }
758
759 if (klass->IsArrayClass()) {
760 *status_ptr = JVMTI_CLASS_STATUS_ARRAY;
761 } else if (klass->IsPrimitive()) {
762 *status_ptr = JVMTI_CLASS_STATUS_PRIMITIVE;
763 } else {
764 *status_ptr = JVMTI_CLASS_STATUS_VERIFIED; // All loaded classes are structurally verified.
765 // This is finicky. If there's an error, we'll say it wasn't prepared.
766 if (klass->IsResolved()) {
767 *status_ptr |= JVMTI_CLASS_STATUS_PREPARED;
768 }
769 if (klass->IsInitialized()) {
770 *status_ptr |= JVMTI_CLASS_STATUS_INITIALIZED;
771 }
772 // Technically the class may be erroneous for other reasons, but we do not have enough info.
773 if (klass->IsErroneous()) {
774 *status_ptr |= JVMTI_CLASS_STATUS_ERROR;
775 }
776 }
777
778 return ERR(NONE);
779}
780
Andreas Gampe4fd66ec2017-01-05 14:42:13 -0800781template <typename T>
782static jvmtiError ClassIsT(jclass jklass, T test, jboolean* is_t_ptr) {
783 art::ScopedObjectAccess soa(art::Thread::Current());
784 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
785 if (klass == nullptr) {
786 return ERR(INVALID_CLASS);
787 }
788
789 if (is_t_ptr == nullptr) {
790 return ERR(NULL_POINTER);
791 }
792
793 *is_t_ptr = test(klass) ? JNI_TRUE : JNI_FALSE;
794 return ERR(NONE);
795}
796
797jvmtiError ClassUtil::IsInterface(jvmtiEnv* env ATTRIBUTE_UNUSED,
798 jclass jklass,
799 jboolean* is_interface_ptr) {
800 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
801 return klass->IsInterface();
802 };
803 return ClassIsT(jklass, test, is_interface_ptr);
804}
805
806jvmtiError ClassUtil::IsArrayClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
807 jclass jklass,
808 jboolean* is_array_class_ptr) {
809 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
810 return klass->IsArrayClass();
811 };
812 return ClassIsT(jklass, test, is_array_class_ptr);
813}
814
Andreas Gampe64013e52017-01-06 13:07:19 -0800815// Keep this in sync with Class.getModifiers().
816static uint32_t ClassGetModifiers(art::Thread* self, art::ObjPtr<art::mirror::Class> klass)
817 REQUIRES_SHARED(art::Locks::mutator_lock_) {
818 if (klass->IsArrayClass()) {
819 uint32_t component_modifiers = ClassGetModifiers(self, klass->GetComponentType());
820 if ((component_modifiers & art::kAccInterface) != 0) {
821 component_modifiers &= ~(art::kAccInterface | art::kAccStatic);
822 }
823 return art::kAccAbstract | art::kAccFinal | component_modifiers;
824 }
825
826 uint32_t modifiers = klass->GetAccessFlags() & art::kAccJavaFlagsMask;
827
828 art::StackHandleScope<1> hs(self);
829 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
830 return art::mirror::Class::GetInnerClassFlags(h_klass, modifiers);
831}
832
833jvmtiError ClassUtil::GetClassModifiers(jvmtiEnv* env ATTRIBUTE_UNUSED,
834 jclass jklass,
835 jint* modifiers_ptr) {
836 art::ScopedObjectAccess soa(art::Thread::Current());
837 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
838 if (klass == nullptr) {
839 return ERR(INVALID_CLASS);
840 }
841
842 if (modifiers_ptr == nullptr) {
843 return ERR(NULL_POINTER);
844 }
845
846 *modifiers_ptr = ClassGetModifiers(soa.Self(), klass);
847
848 return ERR(NONE);
849}
850
Andreas Gampe8f5b6032017-01-06 15:50:55 -0800851jvmtiError ClassUtil::GetClassLoader(jvmtiEnv* env ATTRIBUTE_UNUSED,
852 jclass jklass,
853 jobject* classloader_ptr) {
854 art::ScopedObjectAccess soa(art::Thread::Current());
855 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
856 if (klass == nullptr) {
857 return ERR(INVALID_CLASS);
858 }
859
860 if (classloader_ptr == nullptr) {
861 return ERR(NULL_POINTER);
862 }
863
864 *classloader_ptr = soa.AddLocalReference<jobject>(klass->GetClassLoader());
865
866 return ERR(NONE);
867}
868
Alex Lightc7588752018-02-20 11:15:54 -0800869// Copies unique class descriptors into the classes list from dex_files.
870static jvmtiError CopyClassDescriptors(jvmtiEnv* env,
871 const std::vector<const art::DexFile*>& dex_files,
872 /*out*/jint* count_ptr,
873 /*out*/char*** classes) {
874 jvmtiError res = OK;
875 std::set<art::StringPiece> unique_descriptors;
876 std::vector<const char*> descriptors;
877 auto add_descriptor = [&](const char* desc) {
878 // Don't add duplicates.
879 if (res == OK && unique_descriptors.find(desc) == unique_descriptors.end()) {
880 // The desc will remain valid since we hold a ref to the class_loader.
881 unique_descriptors.insert(desc);
882 descriptors.push_back(CopyString(env, desc, &res).release());
883 }
884 };
885 for (const art::DexFile* dex_file : dex_files) {
886 uint32_t num_defs = dex_file->NumClassDefs();
887 for (uint32_t i = 0; i < num_defs; i++) {
888 add_descriptor(dex_file->GetClassDescriptor(dex_file->GetClassDef(i)));
889 }
890 }
891 char** out_data = nullptr;
892 if (res == OK) {
893 res = env->Allocate(sizeof(char*) * descriptors.size(),
894 reinterpret_cast<unsigned char**>(&out_data));
895 }
896 if (res != OK) {
897 env->Deallocate(reinterpret_cast<unsigned char*>(out_data));
898 // Failed to allocate. Cleanup everything.
899 for (const char* data : descriptors) {
900 env->Deallocate(reinterpret_cast<unsigned char*>(const_cast<char*>(data)));
901 }
902 descriptors.clear();
903 return res;
904 }
905 // Everything is good.
906 memcpy(out_data, descriptors.data(), sizeof(char*) * descriptors.size());
907 *count_ptr = static_cast<jint>(descriptors.size());
908 *classes = out_data;
909 return OK;
910}
911
912jvmtiError ClassUtil::GetClassLoaderClassDescriptors(jvmtiEnv* env,
913 jobject loader,
914 /*out*/jint* count_ptr,
915 /*out*/char*** classes) {
916 art::Thread* self = art::Thread::Current();
917 if (env == nullptr) {
918 return ERR(INVALID_ENVIRONMENT);
919 } else if (self == nullptr) {
920 return ERR(UNATTACHED_THREAD);
921 } else if (count_ptr == nullptr || classes == nullptr) {
922 return ERR(NULL_POINTER);
923 }
924 art::JNIEnvExt* jnienv = self->GetJniEnv();
925 if (loader == nullptr ||
926 jnienv->IsInstanceOf(loader, art::WellKnownClasses::java_lang_BootClassLoader)) {
927 // We can just get the dex files directly for the boot class path.
928 return CopyClassDescriptors(env,
929 art::Runtime::Current()->GetClassLinker()->GetBootClassPath(),
930 count_ptr,
931 classes);
932 }
933 if (!jnienv->IsInstanceOf(loader, art::WellKnownClasses::java_lang_ClassLoader)) {
934 return ERR(ILLEGAL_ARGUMENT);
935 } else if (!jnienv->IsInstanceOf(loader,
936 art::WellKnownClasses::dalvik_system_BaseDexClassLoader)) {
Alex Lightae45cbb2018-10-18 15:49:56 -0700937 JVMTI_LOG(ERROR, env) << "GetClassLoaderClassDescriptors is only implemented for "
938 << "BootClassPath and dalvik.system.BaseDexClassLoader class loaders";
Alex Lightc7588752018-02-20 11:15:54 -0800939 // TODO Possibly return OK With no classes would be better since these ones cannot have any
940 // real classes associated with them.
941 return ERR(NOT_IMPLEMENTED);
942 }
943
944 art::ScopedObjectAccess soa(self);
945 art::StackHandleScope<1> hs(self);
946 art::Handle<art::mirror::ClassLoader> class_loader(
947 hs.NewHandle(soa.Decode<art::mirror::ClassLoader>(loader)));
948 std::vector<const art::DexFile*> dex_files;
Andreas Gampeb8e7c372018-02-20 18:24:55 -0800949 art::VisitClassLoaderDexFiles(
950 soa,
Alex Lightc7588752018-02-20 11:15:54 -0800951 class_loader,
Andreas Gampeb8e7c372018-02-20 18:24:55 -0800952 [&](const art::DexFile* dex_file) {
953 dex_files.push_back(dex_file);
954 return true; // Continue with other dex files.
Alex Lightc7588752018-02-20 11:15:54 -0800955 });
956 // We hold the loader so the dex files won't go away until after this call at worst.
957 return CopyClassDescriptors(env, dex_files, count_ptr, classes);
958}
959
Andreas Gampe70f16392017-01-16 14:20:10 -0800960jvmtiError ClassUtil::GetClassLoaderClasses(jvmtiEnv* env,
961 jobject initiating_loader,
962 jint* class_count_ptr,
963 jclass** classes_ptr) {
964 UNUSED(env, initiating_loader, class_count_ptr, classes_ptr);
965
966 if (class_count_ptr == nullptr || classes_ptr == nullptr) {
967 return ERR(NULL_POINTER);
968 }
969 art::Thread* self = art::Thread::Current();
970 if (!self->GetJniEnv()->IsInstanceOf(initiating_loader,
971 art::WellKnownClasses::java_lang_ClassLoader)) {
972 return ERR(ILLEGAL_ARGUMENT);
973 }
974 if (self->GetJniEnv()->IsInstanceOf(initiating_loader,
975 art::WellKnownClasses::java_lang_BootClassLoader)) {
976 // Need to use null for the BootClassLoader.
977 initiating_loader = nullptr;
978 }
979
980 art::ScopedObjectAccess soa(self);
981 art::ObjPtr<art::mirror::ClassLoader> class_loader =
982 soa.Decode<art::mirror::ClassLoader>(initiating_loader);
983
984 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
985
986 art::ReaderMutexLock mu(self, *art::Locks::classlinker_classes_lock_);
987
988 art::ClassTable* class_table = class_linker->ClassTableForClassLoader(class_loader);
989 if (class_table == nullptr) {
990 // Nothing loaded.
991 *class_count_ptr = 0;
992 *classes_ptr = nullptr;
993 return ERR(NONE);
994 }
995
996 struct ClassTableCount {
997 bool operator()(art::ObjPtr<art::mirror::Class> klass) {
998 DCHECK(klass != nullptr);
999 ++count;
1000 return true;
1001 }
1002
1003 size_t count = 0;
1004 };
1005 ClassTableCount ctc;
1006 class_table->Visit(ctc);
1007
1008 if (ctc.count == 0) {
1009 // Nothing loaded.
1010 *class_count_ptr = 0;
1011 *classes_ptr = nullptr;
1012 return ERR(NONE);
1013 }
1014
1015 unsigned char* data;
1016 jvmtiError data_result = env->Allocate(ctc.count * sizeof(jclass), &data);
1017 if (data_result != ERR(NONE)) {
1018 return data_result;
1019 }
1020 jclass* class_array = reinterpret_cast<jclass*>(data);
1021
1022 struct ClassTableFill {
1023 bool operator()(art::ObjPtr<art::mirror::Class> klass)
1024 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1025 DCHECK(klass != nullptr);
1026 DCHECK_LT(count, ctc_ref.count);
1027 local_class_array[count++] = soa_ptr->AddLocalReference<jclass>(klass);
1028 return true;
1029 }
1030
1031 jclass* local_class_array;
1032 const ClassTableCount& ctc_ref;
1033 art::ScopedObjectAccess* soa_ptr;
1034 size_t count;
1035 };
1036 ClassTableFill ctf = { class_array, ctc, &soa, 0 };
1037 class_table->Visit(ctf);
1038 DCHECK_EQ(ctc.count, ctf.count);
1039
1040 *class_count_ptr = ctc.count;
1041 *classes_ptr = class_array;
1042
1043 return ERR(NONE);
1044}
1045
Andreas Gampe812a2442017-01-19 22:04:46 -08001046jvmtiError ClassUtil::GetClassVersionNumbers(jvmtiEnv* env ATTRIBUTE_UNUSED,
1047 jclass jklass,
1048 jint* minor_version_ptr,
1049 jint* major_version_ptr) {
1050 art::ScopedObjectAccess soa(art::Thread::Current());
1051 if (jklass == nullptr) {
1052 return ERR(INVALID_CLASS);
1053 }
1054 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1055 if (!jklass_obj->IsClass()) {
1056 return ERR(INVALID_CLASS);
1057 }
1058 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
1059 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1060 return ERR(INVALID_CLASS);
1061 }
1062
1063 if (minor_version_ptr == nullptr || major_version_ptr == nullptr) {
1064 return ERR(NULL_POINTER);
1065 }
1066
1067 // Note: proxies will show the dex file version of java.lang.reflect.Proxy, as that is
1068 // what their dex cache copies from.
1069 uint32_t version = klass->GetDexFile().GetHeader().GetVersion();
1070
1071 *major_version_ptr = static_cast<jint>(version);
1072 *minor_version_ptr = 0;
1073
1074 return ERR(NONE);
1075}
1076
Alex Light6fa7b812017-06-16 09:04:29 -07001077jvmtiError ClassUtil::GetSourceFileName(jvmtiEnv* env, jclass jklass, char** source_name_ptr) {
1078 art::ScopedObjectAccess soa(art::Thread::Current());
1079 if (jklass == nullptr) {
1080 return ERR(INVALID_CLASS);
1081 }
1082 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1083 if (!jklass_obj->IsClass()) {
1084 return ERR(INVALID_CLASS);
1085 }
1086 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
1087 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1088 return ERR(ABSENT_INFORMATION);
1089 }
1090 JvmtiUniquePtr<char[]> source_copy;
1091 const char* file_name = klass->GetSourceFile();
1092 if (file_name == nullptr) {
1093 return ERR(ABSENT_INFORMATION);
1094 }
1095 jvmtiError ret;
1096 source_copy = CopyString(env, file_name, &ret);
1097 if (source_copy == nullptr) {
1098 return ret;
1099 }
1100 *source_name_ptr = source_copy.release();
1101 return OK;
1102}
1103
1104jvmtiError ClassUtil::GetSourceDebugExtension(jvmtiEnv* env,
1105 jclass jklass,
1106 char** source_debug_extension_ptr) {
1107 art::ScopedObjectAccess soa(art::Thread::Current());
1108 if (jklass == nullptr) {
1109 return ERR(INVALID_CLASS);
1110 }
1111 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1112 if (!jklass_obj->IsClass()) {
1113 return ERR(INVALID_CLASS);
1114 }
1115 art::StackHandleScope<1> hs(art::Thread::Current());
1116 art::Handle<art::mirror::Class> klass(hs.NewHandle(jklass_obj->AsClass()));
1117 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1118 return ERR(ABSENT_INFORMATION);
1119 }
1120 JvmtiUniquePtr<char[]> ext_copy;
1121 const char* data = art::annotations::GetSourceDebugExtension(klass);
1122 if (data == nullptr) {
1123 return ERR(ABSENT_INFORMATION);
1124 }
1125 jvmtiError ret;
1126 ext_copy = CopyString(env, data, &ret);
1127 if (ext_copy == nullptr) {
1128 return ret;
1129 }
1130 *source_debug_extension_ptr = ext_copy.release();
1131 return OK;
1132}
1133
Andreas Gampee492ae32016-10-28 19:34:57 -07001134} // namespace openjdkjvmti