blob: 60ab0a50e6379f084024500e9bd7612160d79ad1 [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"
Andreas Gampe70f16392017-01-16 14:20:10 -080042#include "class_linker.h"
Steven Morelande431e272017-07-18 16:53:49 -070043#include "class_table-inl.h"
Alex Light440b5d92017-01-24 15:32:25 -080044#include "common_throws.h"
Andreas Gampe0eb36432017-02-15 18:36:14 -080045#include "dex_file_annotations.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070046#include "dex_file_loader.h"
Andreas Gampee6377462017-01-20 17:37:50 -080047#include "events-inl.h"
Alex Light40528472017-03-28 09:07:36 -070048#include "fixed_up_dex_file.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070049#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070050#include "gc/heap.h"
Andreas Gampe691051b2017-02-09 09:15:24 -080051#include "gc_root.h"
Andreas Gampee6377462017-01-20 17:37:50 -080052#include "handle.h"
53#include "jni_env_ext-inl.h"
Andreas Gampeac587272017-01-05 15:21:34 -080054#include "jni_internal.h"
Alex Light440b5d92017-01-24 15:32:25 -080055#include "mirror/array-inl.h"
56#include "mirror/class-inl.h"
57#include "mirror/class_ext.h"
Andreas Gampea67354b2017-02-10 16:18:30 -080058#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080059#include "mirror/object-refvisitor-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070060#include "mirror/object_array-inl.h"
61#include "mirror/object_reference.h"
Andreas Gampe52784ac2017-02-13 18:10:09 -080062#include "mirror/reference.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070063#include "nativehelper/scoped_local_ref.h"
Alex Light6a656312017-03-29 17:18:00 -070064#include "primitive.h"
65#include "reflection.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080066#include "runtime.h"
Andreas Gampee6377462017-01-20 17:37:50 -080067#include "runtime_callbacks.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070068#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070069#include "thread-current-inl.h"
Andreas Gampee6377462017-01-20 17:37:50 -080070#include "thread_list.h"
Alex Lighteb98b082017-01-25 13:02:32 -080071#include "ti_class_loader.h"
Alex Lightd8ce4e72017-02-27 10:52:29 -080072#include "ti_phase.h"
Alex Light440b5d92017-01-24 15:32:25 -080073#include "ti_redefine.h"
74#include "utils.h"
Andreas Gampea1d2f952017-04-20 22:53:58 -070075#include "well_known_classes.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070076
77namespace openjdkjvmti {
78
Alex Light440b5d92017-01-24 15:32:25 -080079using android::base::StringPrintf;
80
81static std::unique_ptr<const art::DexFile> MakeSingleDexFile(art::Thread* self,
82 const char* descriptor,
83 const std::string& orig_location,
84 jint final_len,
85 const unsigned char* final_dex_data)
86 REQUIRES_SHARED(art::Locks::mutator_lock_) {
87 // Make the mmap
88 std::string error_msg;
Vladimir Markoe1993c72017-06-14 17:01:38 +010089 art::ArrayRef<const unsigned char> final_data(final_dex_data, final_len);
Alex Light440b5d92017-01-24 15:32:25 -080090 std::unique_ptr<art::MemMap> map(Redefiner::MoveDataToMemMap(orig_location,
Alex Lightb7354d52017-03-30 15:17:01 -070091 final_data,
Alex Light440b5d92017-01-24 15:32:25 -080092 &error_msg));
93 if (map.get() == nullptr) {
94 LOG(WARNING) << "Unable to allocate mmap for redefined dex file! Error was: " << error_msg;
95 self->ThrowOutOfMemoryError(StringPrintf(
96 "Unable to allocate dex file for transformation of %s", descriptor).c_str());
97 return nullptr;
98 }
99
100 // Make a dex-file
101 if (map->Size() < sizeof(art::DexFile::Header)) {
102 LOG(WARNING) << "Could not read dex file header because dex_data was too short";
103 art::ThrowClassFormatError(nullptr,
104 "Unable to read transformed dex file of %s",
105 descriptor);
106 return nullptr;
107 }
108 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
Andreas Gampef45d61c2017-06-07 10:29:33 -0700109 std::string map_name = map->GetName();
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700110 std::unique_ptr<const art::DexFile> dex_file(art::DexFileLoader::Open(map_name,
111 checksum,
112 std::move(map),
113 /*verify*/true,
114 /*verify_checksum*/true,
115 &error_msg));
Alex Light440b5d92017-01-24 15:32:25 -0800116 if (dex_file.get() == nullptr) {
117 LOG(WARNING) << "Unable to load modified dex file for " << descriptor << ": " << error_msg;
118 art::ThrowClassFormatError(nullptr,
119 "Unable to read transformed dex file of %s because %s",
120 descriptor,
121 error_msg.c_str());
122 return nullptr;
123 }
124 if (dex_file->NumClassDefs() != 1) {
125 LOG(WARNING) << "Dex file contains more than 1 class_def. Ignoring.";
126 // TODO Throw some other sort of error here maybe?
127 art::ThrowClassFormatError(
128 nullptr,
129 "Unable to use transformed dex file of %s because it contained too many classes",
130 descriptor);
131 return nullptr;
132 }
133 return dex_file;
134}
135
Alex Light28b6e7e2017-05-22 16:05:59 -0700136// A deleter that acts like the jvmtiEnv->Deallocate so that asan does not get tripped up.
137// TODO We should everything use the actual jvmtiEnv->Allocate/Deallocate functions once we can
138// figure out which env to use.
139template <typename T>
140class FakeJvmtiDeleter {
141 public:
142 FakeJvmtiDeleter() {}
143
144 FakeJvmtiDeleter(FakeJvmtiDeleter&) = default;
145 FakeJvmtiDeleter(FakeJvmtiDeleter&&) = default;
146 FakeJvmtiDeleter& operator=(const FakeJvmtiDeleter&) = default;
147
148 template <typename U> void operator()(const U* ptr) const {
149 if (ptr != nullptr) {
150 free(const_cast<U*>(ptr));
151 }
152 }
153};
154
Andreas Gampee6377462017-01-20 17:37:50 -0800155struct ClassCallback : public art::ClassLoadCallback {
Alex Light440b5d92017-01-24 15:32:25 -0800156 void ClassPreDefine(const char* descriptor,
157 art::Handle<art::mirror::Class> klass,
158 art::Handle<art::mirror::ClassLoader> class_loader,
159 const art::DexFile& initial_dex_file,
160 const art::DexFile::ClassDef& initial_class_def ATTRIBUTE_UNUSED,
161 /*out*/art::DexFile const** final_dex_file,
162 /*out*/art::DexFile::ClassDef const** final_class_def)
163 OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
164 bool is_enabled =
165 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookRetransformable) ||
166 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookNonRetransformable);
167 if (!is_enabled) {
168 return;
169 }
170 if (descriptor[0] != 'L') {
171 // It is a primitive or array. Just return
172 return;
173 }
Alex Lightd8ce4e72017-02-27 10:52:29 -0800174 jvmtiPhase phase = PhaseUtil::GetPhaseUnchecked();
175 if (UNLIKELY(phase != JVMTI_PHASE_START && phase != JVMTI_PHASE_LIVE)) {
176 // We want to wait until we are at least in the START phase so that all WellKnownClasses and
177 // mirror classes have been initialized and loaded. The runtime relies on these classes having
178 // specific fields and methods present. Since PreDefine hooks don't need to abide by this
179 // restriction we will simply not send the event for these classes.
180 LOG(WARNING) << "Ignoring load of class <" << descriptor << "> as it is being loaded during "
181 << "runtime initialization.";
182 return;
183 }
184
185 // Strip the 'L' and ';' from the descriptor
Alex Light28027122017-01-26 17:21:51 -0800186 std::string name(std::string(descriptor).substr(1, strlen(descriptor) - 2));
Alex Light440b5d92017-01-24 15:32:25 -0800187
188 art::Thread* self = art::Thread::Current();
189 art::JNIEnvExt* env = self->GetJniEnv();
190 ScopedLocalRef<jobject> loader(
191 env, class_loader.IsNull() ? nullptr : env->AddLocalReference<jobject>(class_loader.Get()));
Alex Light40528472017-03-28 09:07:36 -0700192 std::unique_ptr<FixedUpDexFile> dex_file_copy(FixedUpDexFile::Create(initial_dex_file));
193
Alex Light440b5d92017-01-24 15:32:25 -0800194 // Go back to native.
195 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
196 // Call all Non-retransformable agents.
197 jint post_no_redefine_len = 0;
198 unsigned char* post_no_redefine_dex_data = nullptr;
Alex Light28b6e7e2017-05-22 16:05:59 -0700199 std::unique_ptr<const unsigned char, FakeJvmtiDeleter<const unsigned char>>
200 post_no_redefine_unique_ptr(nullptr, FakeJvmtiDeleter<const unsigned char>());
Alex Light440b5d92017-01-24 15:32:25 -0800201 event_handler->DispatchEvent<ArtJvmtiEvent::kClassFileLoadHookNonRetransformable>(
202 self,
203 static_cast<JNIEnv*>(env),
204 static_cast<jclass>(nullptr), // The class doesn't really exist yet so send null.
205 loader.get(),
206 name.c_str(),
207 static_cast<jobject>(nullptr), // Android doesn't seem to have protection domains
Alex Light40528472017-03-28 09:07:36 -0700208 static_cast<jint>(dex_file_copy->Size()),
209 static_cast<const unsigned char*>(dex_file_copy->Begin()),
Alex Light440b5d92017-01-24 15:32:25 -0800210 static_cast<jint*>(&post_no_redefine_len),
211 static_cast<unsigned char**>(&post_no_redefine_dex_data));
212 if (post_no_redefine_dex_data == nullptr) {
213 DCHECK_EQ(post_no_redefine_len, 0);
Alex Light40528472017-03-28 09:07:36 -0700214 post_no_redefine_dex_data = const_cast<unsigned char*>(dex_file_copy->Begin());
215 post_no_redefine_len = dex_file_copy->Size();
Alex Light440b5d92017-01-24 15:32:25 -0800216 } else {
Alex Light28b6e7e2017-05-22 16:05:59 -0700217 post_no_redefine_unique_ptr =
218 std::unique_ptr<const unsigned char, FakeJvmtiDeleter<const unsigned char>>(
219 post_no_redefine_dex_data, FakeJvmtiDeleter<const unsigned char>());
Alex Light440b5d92017-01-24 15:32:25 -0800220 DCHECK_GT(post_no_redefine_len, 0);
221 }
222 // Call all retransformable agents.
223 jint final_len = 0;
224 unsigned char* final_dex_data = nullptr;
Alex Light28b6e7e2017-05-22 16:05:59 -0700225 std::unique_ptr<const unsigned char, FakeJvmtiDeleter<const unsigned char>>
226 final_dex_unique_ptr(nullptr, FakeJvmtiDeleter<const unsigned char>());
Alex Light440b5d92017-01-24 15:32:25 -0800227 event_handler->DispatchEvent<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
228 self,
229 static_cast<JNIEnv*>(env),
230 static_cast<jclass>(nullptr), // The class doesn't really exist yet so send null.
231 loader.get(),
232 name.c_str(),
233 static_cast<jobject>(nullptr), // Android doesn't seem to have protection domains
234 static_cast<jint>(post_no_redefine_len),
235 static_cast<const unsigned char*>(post_no_redefine_dex_data),
236 static_cast<jint*>(&final_len),
237 static_cast<unsigned char**>(&final_dex_data));
238 if (final_dex_data == nullptr) {
239 DCHECK_EQ(final_len, 0);
240 final_dex_data = post_no_redefine_dex_data;
241 final_len = post_no_redefine_len;
242 } else {
Alex Light28b6e7e2017-05-22 16:05:59 -0700243 final_dex_unique_ptr =
244 std::unique_ptr<const unsigned char, FakeJvmtiDeleter<const unsigned char>>(
245 final_dex_data, FakeJvmtiDeleter<const unsigned char>());
Alex Light440b5d92017-01-24 15:32:25 -0800246 DCHECK_GT(final_len, 0);
247 }
248
Alex Light40528472017-03-28 09:07:36 -0700249 if (final_dex_data != dex_file_copy->Begin()) {
Alex Light440b5d92017-01-24 15:32:25 -0800250 LOG(WARNING) << "Changing class " << descriptor;
251 art::ScopedObjectAccess soa(self);
252 art::StackHandleScope<2> hs(self);
253 // Save the results of all the non-retransformable agents.
254 // First allocate the ClassExt
255 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(self)));
256 // Make sure we have a ClassExt. This is fine even though we are a temporary since it will
257 // get copied.
258 if (ext.IsNull()) {
259 // We will just return failure if we fail to allocate
260 LOG(WARNING) << "Could not allocate ext-data for class '" << descriptor << "'. "
261 << "Aborting transformation since we will be unable to store it.";
262 self->AssertPendingOOMException();
263 return;
264 }
265
266 // Allocate the byte array to store the dex file bytes in.
Alex Light6a656312017-03-29 17:18:00 -0700267 art::MutableHandle<art::mirror::Object> arr(hs.NewHandle<art::mirror::Object>(nullptr));
268 if (post_no_redefine_dex_data == dex_file_copy->Begin() && name != "java/lang/Long") {
269 // we didn't have any non-retransformable agents. We can just cache a pointer to the
270 // initial_dex_file. It will be kept live by the class_loader.
271 jlong dex_ptr = reinterpret_cast<uintptr_t>(&initial_dex_file);
272 art::JValue val;
273 val.SetJ(dex_ptr);
274 arr.Assign(art::BoxPrimitive(art::Primitive::kPrimLong, val));
275 } else {
276 arr.Assign(art::mirror::ByteArray::AllocateAndFill(
277 self,
278 reinterpret_cast<const signed char*>(post_no_redefine_dex_data),
279 post_no_redefine_len));
280 }
Alex Light440b5d92017-01-24 15:32:25 -0800281 if (arr.IsNull()) {
Alex Light6a656312017-03-29 17:18:00 -0700282 LOG(WARNING) << "Unable to allocate memory for initial dex-file. Aborting transformation";
Alex Light440b5d92017-01-24 15:32:25 -0800283 self->AssertPendingOOMException();
284 return;
285 }
286
287 std::unique_ptr<const art::DexFile> dex_file(MakeSingleDexFile(self,
288 descriptor,
289 initial_dex_file.GetLocation(),
290 final_len,
291 final_dex_data));
292 if (dex_file.get() == nullptr) {
293 return;
294 }
295
Alex Lighteb98b082017-01-25 13:02:32 -0800296 // TODO Check Redefined dex file for all invariants.
Alex Light440b5d92017-01-24 15:32:25 -0800297 LOG(WARNING) << "Dex file created by class-definition time transformation of "
298 << descriptor << " is not checked for all retransformation invariants.";
Alex Lighteb98b082017-01-25 13:02:32 -0800299
300 if (!ClassLoaderHelper::AddToClassLoader(self, class_loader, dex_file.get())) {
301 LOG(ERROR) << "Unable to add " << descriptor << " to class loader!";
302 return;
303 }
304
Alex Light440b5d92017-01-24 15:32:25 -0800305 // Actually set the ClassExt's original bytes once we have actually succeeded.
Alex Light2f814aa2017-03-24 15:21:34 +0000306 ext->SetOriginalDexFile(arr.Get());
Alex Light440b5d92017-01-24 15:32:25 -0800307 // Set the return values
308 *final_class_def = &dex_file->GetClassDef(0);
309 *final_dex_file = dex_file.release();
310 }
311 }
312
Andreas Gampee6377462017-01-20 17:37:50 -0800313 void ClassLoad(art::Handle<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
314 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassLoad)) {
315 art::Thread* thread = art::Thread::Current();
316 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
317 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700318 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800319 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700320 thread->GetJniEnv(),
321 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Alex Light9df79b72017-09-12 08:57:31 -0700322 event_handler->DispatchEvent<ArtJvmtiEvent::kClassLoad>(
323 thread,
324 static_cast<JNIEnv*>(thread->GetJniEnv()),
325 thread_jni.get(),
326 jklass.get());
Andreas Gampe691051b2017-02-09 09:15:24 -0800327 if (klass->IsTemp()) {
328 AddTempClass(thread, jklass.get());
329 }
Andreas Gampee6377462017-01-20 17:37:50 -0800330 }
331 }
332
Andreas Gampe691051b2017-02-09 09:15:24 -0800333 void ClassPrepare(art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800334 art::Handle<art::mirror::Class> klass)
335 REQUIRES_SHARED(art::Locks::mutator_lock_) {
336 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassPrepare)) {
337 art::Thread* thread = art::Thread::Current();
Andreas Gampe691051b2017-02-09 09:15:24 -0800338 if (temp_klass.Get() != klass.Get()) {
339 DCHECK(temp_klass->IsTemp());
340 DCHECK(temp_klass->IsRetired());
341 HandleTempClass(thread, temp_klass, klass);
342 }
Andreas Gampee6377462017-01-20 17:37:50 -0800343 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
344 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700345 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800346 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700347 thread->GetJniEnv(),
348 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Andreas Gampe983c1752017-01-23 19:46:56 -0800349 event_handler->DispatchEvent<ArtJvmtiEvent::kClassPrepare>(
350 thread,
351 static_cast<JNIEnv*>(thread->GetJniEnv()),
352 thread_jni.get(),
353 jklass.get());
Andreas Gampee6377462017-01-20 17:37:50 -0800354 }
355 }
356
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800357 // To support parallel class-loading, we need to perform some locking dances here. Namely,
358 // the fixup stage must not be holding the temp_classes lock when it fixes up the system
359 // (as that requires suspending all mutators).
360
Andreas Gampee6377462017-01-20 17:37:50 -0800361 void AddTempClass(art::Thread* self, jclass klass) {
362 std::unique_lock<std::mutex> mu(temp_classes_lock);
Andreas Gampe691051b2017-02-09 09:15:24 -0800363 jclass global_klass = reinterpret_cast<jclass>(self->GetJniEnv()->NewGlobalRef(klass));
364 temp_classes.push_back(global_klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800365 }
366
Andreas Gampe691051b2017-02-09 09:15:24 -0800367 void HandleTempClass(art::Thread* self,
368 art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800369 art::Handle<art::mirror::Class> klass)
370 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800371 bool requires_fixup = false;
372 {
373 std::unique_lock<std::mutex> mu(temp_classes_lock);
374 if (temp_classes.empty()) {
375 return;
Andreas Gampee6377462017-01-20 17:37:50 -0800376 }
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800377
378 for (auto it = temp_classes.begin(); it != temp_classes.end(); ++it) {
379 if (temp_klass.Get() == art::ObjPtr<art::mirror::Class>::DownCast(self->DecodeJObject(*it))) {
380 self->GetJniEnv()->DeleteGlobalRef(*it);
381 temp_classes.erase(it);
382 requires_fixup = true;
383 break;
384 }
385 }
386 }
387 if (requires_fixup) {
388 FixupTempClass(self, temp_klass, klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800389 }
390 }
391
Andreas Gampe691051b2017-02-09 09:15:24 -0800392 void FixupTempClass(art::Thread* self,
393 art::Handle<art::mirror::Class> temp_klass,
394 art::Handle<art::mirror::Class> klass)
Andreas Gampee6377462017-01-20 17:37:50 -0800395 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe691051b2017-02-09 09:15:24 -0800396 // Suspend everything.
397 art::gc::Heap* heap = art::Runtime::Current()->GetHeap();
398 if (heap->IsGcConcurrentAndMoving()) {
399 // Need to take a heap dump while GC isn't running. See the
400 // comment in Heap::VisitObjects().
401 heap->IncrementDisableMovingGC(self);
402 }
403 {
404 art::ScopedThreadSuspension sts(self, art::kWaitingForVisitObjects);
405 art::ScopedSuspendAll ssa("FixupTempClass");
406
407 art::mirror::Class* input = temp_klass.Get();
408 art::mirror::Class* output = klass.Get();
409
410 FixupGlobalReferenceTables(input, output);
Andreas Gampe94dda932017-02-09 18:19:21 -0800411 FixupLocalReferenceTables(self, input, output);
Andreas Gampea67354b2017-02-10 16:18:30 -0800412 FixupHeap(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800413 }
414 if (heap->IsGcConcurrentAndMoving()) {
415 heap->DecrementDisableMovingGC(self);
416 }
417 }
418
Andreas Gampe94dda932017-02-09 18:19:21 -0800419 class RootUpdater : public art::RootVisitor {
420 public:
421 RootUpdater(const art::mirror::Class* input, art::mirror::Class* output)
422 : input_(input), output_(output) {}
423
424 void VisitRoots(art::mirror::Object*** roots,
425 size_t count,
426 const art::RootInfo& info ATTRIBUTE_UNUSED)
427 OVERRIDE {
428 for (size_t i = 0; i != count; ++i) {
429 if (*roots[i] == input_) {
430 *roots[i] = output_;
431 }
432 }
433 }
434
435 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
436 size_t count,
437 const art::RootInfo& info ATTRIBUTE_UNUSED)
438 OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
439 for (size_t i = 0; i != count; ++i) {
440 if (roots[i]->AsMirrorPtr() == input_) {
441 roots[i]->Assign(output_);
442 }
443 }
444 }
445
446 private:
447 const art::mirror::Class* input_;
448 art::mirror::Class* output_;
449 };
450
Andreas Gampea67354b2017-02-10 16:18:30 -0800451 void FixupGlobalReferenceTables(art::mirror::Class* input, art::mirror::Class* output)
Andreas Gampe691051b2017-02-09 09:15:24 -0800452 REQUIRES(art::Locks::mutator_lock_) {
453 art::JavaVMExt* java_vm = art::Runtime::Current()->GetJavaVM();
454
455 // Fix up the global table with a root visitor.
Andreas Gampe94dda932017-02-09 18:19:21 -0800456 RootUpdater global_update(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800457 java_vm->VisitRoots(&global_update);
458
459 class WeakGlobalUpdate : public art::IsMarkedVisitor {
460 public:
461 WeakGlobalUpdate(art::mirror::Class* root_input, art::mirror::Class* root_output)
462 : input_(root_input), output_(root_output) {}
463
464 art::mirror::Object* IsMarked(art::mirror::Object* obj) OVERRIDE {
465 if (obj == input_) {
466 return output_;
467 }
468 return obj;
469 }
470
471 private:
472 const art::mirror::Class* input_;
473 art::mirror::Class* output_;
474 };
475 WeakGlobalUpdate weak_global_update(input, output);
476 java_vm->SweepJniWeakGlobals(&weak_global_update);
Andreas Gampee6377462017-01-20 17:37:50 -0800477 }
478
Andreas Gampe94dda932017-02-09 18:19:21 -0800479 void FixupLocalReferenceTables(art::Thread* self,
480 art::mirror::Class* input,
481 art::mirror::Class* output)
482 REQUIRES(art::Locks::mutator_lock_) {
483 class LocalUpdate {
484 public:
485 LocalUpdate(const art::mirror::Class* root_input, art::mirror::Class* root_output)
486 : input_(root_input), output_(root_output) {}
487
488 static void Callback(art::Thread* t, void* arg) REQUIRES(art::Locks::mutator_lock_) {
489 LocalUpdate* local = reinterpret_cast<LocalUpdate*>(arg);
490
491 // Fix up the local table with a root visitor.
492 RootUpdater local_update(local->input_, local->output_);
Ian Rogers55256cb2017-12-21 17:07:11 -0800493 t->GetJniEnv()->VisitJniLocalRoots(
Andreas Gampe94dda932017-02-09 18:19:21 -0800494 &local_update, art::RootInfo(art::kRootJNILocal, t->GetThreadId()));
495 }
496
497 private:
498 const art::mirror::Class* input_;
499 art::mirror::Class* output_;
500 };
501 LocalUpdate local_upd(input, output);
502 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
503 art::Runtime::Current()->GetThreadList()->ForEach(LocalUpdate::Callback, &local_upd);
504 }
505
Andreas Gampea67354b2017-02-10 16:18:30 -0800506 void FixupHeap(art::mirror::Class* input, art::mirror::Class* output)
507 REQUIRES(art::Locks::mutator_lock_) {
508 class HeapFixupVisitor {
509 public:
510 HeapFixupVisitor(const art::mirror::Class* root_input, art::mirror::Class* root_output)
511 : input_(root_input), output_(root_output) {}
512
513 void operator()(art::mirror::Object* src,
514 art::MemberOffset field_offset,
515 bool is_static ATTRIBUTE_UNUSED) const
516 REQUIRES_SHARED(art::Locks::mutator_lock_) {
517 art::mirror::HeapReference<art::mirror::Object>* trg =
518 src->GetFieldObjectReferenceAddr(field_offset);
519 if (trg->AsMirrorPtr() == input_) {
520 DCHECK_NE(field_offset.Uint32Value(), 0u); // This shouldn't be the class field of
521 // an object.
522 trg->Assign(output_);
523 }
524 }
525
Andreas Gampe52784ac2017-02-13 18:10:09 -0800526 void operator()(art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
527 art::ObjPtr<art::mirror::Reference> reference) const
528 REQUIRES_SHARED(art::Locks::mutator_lock_) {
529 art::mirror::Object* val = reference->GetReferent();
530 if (val == input_) {
531 reference->SetReferent<false>(output_);
532 }
533 }
534
Andreas Gampea67354b2017-02-10 16:18:30 -0800535 void VisitRoot(art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED)
Andreas Gampe52784ac2017-02-13 18:10:09 -0800536 const {
Andreas Gampea67354b2017-02-10 16:18:30 -0800537 LOG(FATAL) << "Unreachable";
538 }
539
540 void VisitRootIfNonNull(
541 art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED) const {
542 LOG(FATAL) << "Unreachable";
543 }
544
Andreas Gampea67354b2017-02-10 16:18:30 -0800545 private:
546 const art::mirror::Class* input_;
547 art::mirror::Class* output_;
548 };
549 HeapFixupVisitor hfv(input, output);
Andreas Gampe1c158a02017-07-13 17:26:19 -0700550 auto object_visitor = [&](art::mirror::Object* obj) {
551 obj->VisitReferences<false>(hfv, hfv); // Visit references, not native roots.
552 };
553 art::Runtime::Current()->GetHeap()->VisitObjectsPaused(object_visitor);
Andreas Gampea67354b2017-02-10 16:18:30 -0800554 }
555
Andreas Gampee6377462017-01-20 17:37:50 -0800556 // A set of all the temp classes we have handed out. We have to fix up references to these.
557 // For simplicity, we store the temp classes as JNI global references in a vector. Normally a
558 // Prepare event will closely follow, so the vector should be small.
559 std::mutex temp_classes_lock;
560 std::vector<jclass> temp_classes;
561
562 EventHandler* event_handler = nullptr;
563};
564
565ClassCallback gClassCallback;
566
567void ClassUtil::Register(EventHandler* handler) {
568 gClassCallback.event_handler = handler;
569 art::ScopedThreadStateChange stsc(art::Thread::Current(),
570 art::ThreadState::kWaitingForDebuggerToAttach);
571 art::ScopedSuspendAll ssa("Add load callback");
572 art::Runtime::Current()->GetRuntimeCallbacks()->AddClassLoadCallback(&gClassCallback);
573}
574
575void ClassUtil::Unregister() {
576 art::ScopedThreadStateChange stsc(art::Thread::Current(),
577 art::ThreadState::kWaitingForDebuggerToAttach);
578 art::ScopedSuspendAll ssa("Remove thread callback");
579 art::Runtime* runtime = art::Runtime::Current();
580 runtime->GetRuntimeCallbacks()->RemoveClassLoadCallback(&gClassCallback);
581}
582
Andreas Gampeac587272017-01-05 15:21:34 -0800583jvmtiError ClassUtil::GetClassFields(jvmtiEnv* env,
584 jclass jklass,
585 jint* field_count_ptr,
586 jfieldID** fields_ptr) {
587 art::ScopedObjectAccess soa(art::Thread::Current());
588 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
589 if (klass == nullptr) {
590 return ERR(INVALID_CLASS);
591 }
592
Alex Light2c6cd692017-06-30 07:34:40 -0700593 // Check if this class is a temporary class object used for loading. Since we are seeing it the
594 // class must not have been prepared yet since otherwise the fixup would have gotten the jobject
595 // to point to the final class object.
596 if (klass->IsTemp() || klass->IsRetired()) {
597 return ERR(CLASS_NOT_PREPARED);
598 }
599
Andreas Gampeac587272017-01-05 15:21:34 -0800600 if (field_count_ptr == nullptr || fields_ptr == nullptr) {
601 return ERR(NULL_POINTER);
602 }
603
Andreas Gampeac587272017-01-05 15:21:34 -0800604 art::IterationRange<art::StrideIterator<art::ArtField>> ifields = klass->GetIFields();
605 art::IterationRange<art::StrideIterator<art::ArtField>> sfields = klass->GetSFields();
606 size_t array_size = klass->NumInstanceFields() + klass->NumStaticFields();
607
608 unsigned char* out_ptr;
609 jvmtiError allocError = env->Allocate(array_size * sizeof(jfieldID), &out_ptr);
610 if (allocError != ERR(NONE)) {
611 return allocError;
612 }
613 jfieldID* field_array = reinterpret_cast<jfieldID*>(out_ptr);
614
615 size_t array_idx = 0;
616 for (art::ArtField& field : sfields) {
617 field_array[array_idx] = art::jni::EncodeArtField(&field);
618 ++array_idx;
619 }
620 for (art::ArtField& field : ifields) {
621 field_array[array_idx] = art::jni::EncodeArtField(&field);
622 ++array_idx;
623 }
624
625 *field_count_ptr = static_cast<jint>(array_size);
626 *fields_ptr = field_array;
627
628 return ERR(NONE);
629}
630
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800631jvmtiError ClassUtil::GetClassMethods(jvmtiEnv* env,
632 jclass jklass,
633 jint* method_count_ptr,
634 jmethodID** methods_ptr) {
635 art::ScopedObjectAccess soa(art::Thread::Current());
636 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
637 if (klass == nullptr) {
638 return ERR(INVALID_CLASS);
639 }
640
Alex Light2c6cd692017-06-30 07:34:40 -0700641 // Check if this class is a temporary class object used for loading. Since we are seeing it the
642 // class must not have been prepared yet since otherwise the fixup would have gotten the jobject
643 // to point to the final class object.
644 if (klass->IsTemp() || klass->IsRetired()) {
645 return ERR(CLASS_NOT_PREPARED);
646 }
647
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800648 if (method_count_ptr == nullptr || methods_ptr == nullptr) {
649 return ERR(NULL_POINTER);
650 }
651
652 size_t array_size = klass->NumDeclaredVirtualMethods() + klass->NumDirectMethods();
653 unsigned char* out_ptr;
654 jvmtiError allocError = env->Allocate(array_size * sizeof(jmethodID), &out_ptr);
655 if (allocError != ERR(NONE)) {
656 return allocError;
657 }
658 jmethodID* method_array = reinterpret_cast<jmethodID*>(out_ptr);
659
660 if (art::kIsDebugBuild) {
661 size_t count = 0;
662 for (auto& m ATTRIBUTE_UNUSED : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
663 count++;
664 }
665 CHECK_EQ(count, klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods());
666 }
667
668 size_t array_idx = 0;
669 for (auto& m : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
670 method_array[array_idx] = art::jni::EncodeArtMethod(&m);
671 ++array_idx;
672 }
673
674 *method_count_ptr = static_cast<jint>(array_size);
675 *methods_ptr = method_array;
676
677 return ERR(NONE);
678}
679
Andreas Gampe8b07e472017-01-06 14:20:39 -0800680jvmtiError ClassUtil::GetImplementedInterfaces(jvmtiEnv* env,
681 jclass jklass,
682 jint* interface_count_ptr,
683 jclass** interfaces_ptr) {
684 art::ScopedObjectAccess soa(art::Thread::Current());
685 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
686 if (klass == nullptr) {
687 return ERR(INVALID_CLASS);
688 }
689
690 if (interface_count_ptr == nullptr || interfaces_ptr == nullptr) {
691 return ERR(NULL_POINTER);
692 }
693
694 // Need to handle array specifically. Arrays implement Serializable and Cloneable, but the
695 // spec says these should not be reported.
696 if (klass->IsArrayClass()) {
697 *interface_count_ptr = 0;
698 *interfaces_ptr = nullptr; // TODO: Should we allocate a dummy here?
699 return ERR(NONE);
700 }
701
702 size_t array_size = klass->NumDirectInterfaces();
703 unsigned char* out_ptr;
704 jvmtiError allocError = env->Allocate(array_size * sizeof(jclass), &out_ptr);
705 if (allocError != ERR(NONE)) {
706 return allocError;
707 }
708 jclass* interface_array = reinterpret_cast<jclass*>(out_ptr);
709
710 art::StackHandleScope<1> hs(soa.Self());
711 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
712
713 for (uint32_t idx = 0; idx != array_size; ++idx) {
714 art::ObjPtr<art::mirror::Class> inf_klass =
715 art::mirror::Class::ResolveDirectInterface(soa.Self(), h_klass, idx);
716 if (inf_klass == nullptr) {
717 soa.Self()->ClearException();
718 env->Deallocate(out_ptr);
719 // TODO: What is the right error code here?
720 return ERR(INTERNAL);
721 }
722 interface_array[idx] = soa.AddLocalReference<jclass>(inf_klass);
723 }
724
725 *interface_count_ptr = static_cast<jint>(array_size);
726 *interfaces_ptr = interface_array;
727
728 return ERR(NONE);
729}
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800730
Andreas Gampee492ae32016-10-28 19:34:57 -0700731jvmtiError ClassUtil::GetClassSignature(jvmtiEnv* env,
732 jclass jklass,
733 char** signature_ptr,
734 char** generic_ptr) {
735 art::ScopedObjectAccess soa(art::Thread::Current());
736 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
737 if (klass == nullptr) {
738 return ERR(INVALID_CLASS);
739 }
740
Andreas Gampe54711412017-02-21 12:41:43 -0800741 JvmtiUniquePtr<char[]> sig_copy;
Andreas Gampee492ae32016-10-28 19:34:57 -0700742 if (signature_ptr != nullptr) {
743 std::string storage;
744 const char* descriptor = klass->GetDescriptor(&storage);
745
Andreas Gampe54711412017-02-21 12:41:43 -0800746 jvmtiError ret;
747 sig_copy = CopyString(env, descriptor, &ret);
748 if (sig_copy == nullptr) {
Andreas Gampee492ae32016-10-28 19:34:57 -0700749 return ret;
750 }
Andreas Gampe54711412017-02-21 12:41:43 -0800751 *signature_ptr = sig_copy.get();
Andreas Gampee492ae32016-10-28 19:34:57 -0700752 }
753
Andreas Gampee6377462017-01-20 17:37:50 -0800754 if (generic_ptr != nullptr) {
755 *generic_ptr = nullptr;
Andreas Gampe0eb36432017-02-15 18:36:14 -0800756 if (!klass->IsProxyClass() && klass->GetDexCache() != nullptr) {
757 art::StackHandleScope<1> hs(soa.Self());
758 art::Handle<art::mirror::Class> h_klass = hs.NewHandle(klass);
759 art::mirror::ObjectArray<art::mirror::String>* str_array =
760 art::annotations::GetSignatureAnnotationForClass(h_klass);
761 if (str_array != nullptr) {
762 std::ostringstream oss;
763 for (int32_t i = 0; i != str_array->GetLength(); ++i) {
764 oss << str_array->Get(i)->ToModifiedUtf8();
765 }
766 std::string output_string = oss.str();
Andreas Gampe54711412017-02-21 12:41:43 -0800767 jvmtiError ret;
768 JvmtiUniquePtr<char[]> copy = CopyString(env, output_string.c_str(), &ret);
769 if (copy == nullptr) {
Andreas Gampe0eb36432017-02-15 18:36:14 -0800770 return ret;
771 }
Andreas Gampe54711412017-02-21 12:41:43 -0800772 *generic_ptr = copy.release();
Andreas Gampe0eb36432017-02-15 18:36:14 -0800773 } else if (soa.Self()->IsExceptionPending()) {
774 // TODO: Should we report an error here?
775 soa.Self()->ClearException();
776 }
777 }
Andreas Gampee6377462017-01-20 17:37:50 -0800778 }
Andreas Gampee492ae32016-10-28 19:34:57 -0700779
780 // Everything is fine, release the buffers.
781 sig_copy.release();
782
783 return ERR(NONE);
784}
785
Andreas Gampeff9d2092017-01-06 09:12:49 -0800786jvmtiError ClassUtil::GetClassStatus(jvmtiEnv* env ATTRIBUTE_UNUSED,
787 jclass jklass,
788 jint* status_ptr) {
789 art::ScopedObjectAccess soa(art::Thread::Current());
790 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
791 if (klass == nullptr) {
792 return ERR(INVALID_CLASS);
793 }
794
795 if (status_ptr == nullptr) {
796 return ERR(NULL_POINTER);
797 }
798
799 if (klass->IsArrayClass()) {
800 *status_ptr = JVMTI_CLASS_STATUS_ARRAY;
801 } else if (klass->IsPrimitive()) {
802 *status_ptr = JVMTI_CLASS_STATUS_PRIMITIVE;
803 } else {
804 *status_ptr = JVMTI_CLASS_STATUS_VERIFIED; // All loaded classes are structurally verified.
805 // This is finicky. If there's an error, we'll say it wasn't prepared.
806 if (klass->IsResolved()) {
807 *status_ptr |= JVMTI_CLASS_STATUS_PREPARED;
808 }
809 if (klass->IsInitialized()) {
810 *status_ptr |= JVMTI_CLASS_STATUS_INITIALIZED;
811 }
812 // Technically the class may be erroneous for other reasons, but we do not have enough info.
813 if (klass->IsErroneous()) {
814 *status_ptr |= JVMTI_CLASS_STATUS_ERROR;
815 }
816 }
817
818 return ERR(NONE);
819}
820
Andreas Gampe4fd66ec2017-01-05 14:42:13 -0800821template <typename T>
822static jvmtiError ClassIsT(jclass jklass, T test, jboolean* is_t_ptr) {
823 art::ScopedObjectAccess soa(art::Thread::Current());
824 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
825 if (klass == nullptr) {
826 return ERR(INVALID_CLASS);
827 }
828
829 if (is_t_ptr == nullptr) {
830 return ERR(NULL_POINTER);
831 }
832
833 *is_t_ptr = test(klass) ? JNI_TRUE : JNI_FALSE;
834 return ERR(NONE);
835}
836
837jvmtiError ClassUtil::IsInterface(jvmtiEnv* env ATTRIBUTE_UNUSED,
838 jclass jklass,
839 jboolean* is_interface_ptr) {
840 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
841 return klass->IsInterface();
842 };
843 return ClassIsT(jklass, test, is_interface_ptr);
844}
845
846jvmtiError ClassUtil::IsArrayClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
847 jclass jklass,
848 jboolean* is_array_class_ptr) {
849 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
850 return klass->IsArrayClass();
851 };
852 return ClassIsT(jklass, test, is_array_class_ptr);
853}
854
Andreas Gampe64013e52017-01-06 13:07:19 -0800855// Keep this in sync with Class.getModifiers().
856static uint32_t ClassGetModifiers(art::Thread* self, art::ObjPtr<art::mirror::Class> klass)
857 REQUIRES_SHARED(art::Locks::mutator_lock_) {
858 if (klass->IsArrayClass()) {
859 uint32_t component_modifiers = ClassGetModifiers(self, klass->GetComponentType());
860 if ((component_modifiers & art::kAccInterface) != 0) {
861 component_modifiers &= ~(art::kAccInterface | art::kAccStatic);
862 }
863 return art::kAccAbstract | art::kAccFinal | component_modifiers;
864 }
865
866 uint32_t modifiers = klass->GetAccessFlags() & art::kAccJavaFlagsMask;
867
868 art::StackHandleScope<1> hs(self);
869 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
870 return art::mirror::Class::GetInnerClassFlags(h_klass, modifiers);
871}
872
873jvmtiError ClassUtil::GetClassModifiers(jvmtiEnv* env ATTRIBUTE_UNUSED,
874 jclass jklass,
875 jint* modifiers_ptr) {
876 art::ScopedObjectAccess soa(art::Thread::Current());
877 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
878 if (klass == nullptr) {
879 return ERR(INVALID_CLASS);
880 }
881
882 if (modifiers_ptr == nullptr) {
883 return ERR(NULL_POINTER);
884 }
885
886 *modifiers_ptr = ClassGetModifiers(soa.Self(), klass);
887
888 return ERR(NONE);
889}
890
Andreas Gampe8f5b6032017-01-06 15:50:55 -0800891jvmtiError ClassUtil::GetClassLoader(jvmtiEnv* env ATTRIBUTE_UNUSED,
892 jclass jklass,
893 jobject* classloader_ptr) {
894 art::ScopedObjectAccess soa(art::Thread::Current());
895 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
896 if (klass == nullptr) {
897 return ERR(INVALID_CLASS);
898 }
899
900 if (classloader_ptr == nullptr) {
901 return ERR(NULL_POINTER);
902 }
903
904 *classloader_ptr = soa.AddLocalReference<jobject>(klass->GetClassLoader());
905
906 return ERR(NONE);
907}
908
Andreas Gampe70f16392017-01-16 14:20:10 -0800909jvmtiError ClassUtil::GetClassLoaderClasses(jvmtiEnv* env,
910 jobject initiating_loader,
911 jint* class_count_ptr,
912 jclass** classes_ptr) {
913 UNUSED(env, initiating_loader, class_count_ptr, classes_ptr);
914
915 if (class_count_ptr == nullptr || classes_ptr == nullptr) {
916 return ERR(NULL_POINTER);
917 }
918 art::Thread* self = art::Thread::Current();
919 if (!self->GetJniEnv()->IsInstanceOf(initiating_loader,
920 art::WellKnownClasses::java_lang_ClassLoader)) {
921 return ERR(ILLEGAL_ARGUMENT);
922 }
923 if (self->GetJniEnv()->IsInstanceOf(initiating_loader,
924 art::WellKnownClasses::java_lang_BootClassLoader)) {
925 // Need to use null for the BootClassLoader.
926 initiating_loader = nullptr;
927 }
928
929 art::ScopedObjectAccess soa(self);
930 art::ObjPtr<art::mirror::ClassLoader> class_loader =
931 soa.Decode<art::mirror::ClassLoader>(initiating_loader);
932
933 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
934
935 art::ReaderMutexLock mu(self, *art::Locks::classlinker_classes_lock_);
936
937 art::ClassTable* class_table = class_linker->ClassTableForClassLoader(class_loader);
938 if (class_table == nullptr) {
939 // Nothing loaded.
940 *class_count_ptr = 0;
941 *classes_ptr = nullptr;
942 return ERR(NONE);
943 }
944
945 struct ClassTableCount {
946 bool operator()(art::ObjPtr<art::mirror::Class> klass) {
947 DCHECK(klass != nullptr);
948 ++count;
949 return true;
950 }
951
952 size_t count = 0;
953 };
954 ClassTableCount ctc;
955 class_table->Visit(ctc);
956
957 if (ctc.count == 0) {
958 // Nothing loaded.
959 *class_count_ptr = 0;
960 *classes_ptr = nullptr;
961 return ERR(NONE);
962 }
963
964 unsigned char* data;
965 jvmtiError data_result = env->Allocate(ctc.count * sizeof(jclass), &data);
966 if (data_result != ERR(NONE)) {
967 return data_result;
968 }
969 jclass* class_array = reinterpret_cast<jclass*>(data);
970
971 struct ClassTableFill {
972 bool operator()(art::ObjPtr<art::mirror::Class> klass)
973 REQUIRES_SHARED(art::Locks::mutator_lock_) {
974 DCHECK(klass != nullptr);
975 DCHECK_LT(count, ctc_ref.count);
976 local_class_array[count++] = soa_ptr->AddLocalReference<jclass>(klass);
977 return true;
978 }
979
980 jclass* local_class_array;
981 const ClassTableCount& ctc_ref;
982 art::ScopedObjectAccess* soa_ptr;
983 size_t count;
984 };
985 ClassTableFill ctf = { class_array, ctc, &soa, 0 };
986 class_table->Visit(ctf);
987 DCHECK_EQ(ctc.count, ctf.count);
988
989 *class_count_ptr = ctc.count;
990 *classes_ptr = class_array;
991
992 return ERR(NONE);
993}
994
Andreas Gampe812a2442017-01-19 22:04:46 -0800995jvmtiError ClassUtil::GetClassVersionNumbers(jvmtiEnv* env ATTRIBUTE_UNUSED,
996 jclass jklass,
997 jint* minor_version_ptr,
998 jint* major_version_ptr) {
999 art::ScopedObjectAccess soa(art::Thread::Current());
1000 if (jklass == nullptr) {
1001 return ERR(INVALID_CLASS);
1002 }
1003 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1004 if (!jklass_obj->IsClass()) {
1005 return ERR(INVALID_CLASS);
1006 }
1007 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
1008 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1009 return ERR(INVALID_CLASS);
1010 }
1011
1012 if (minor_version_ptr == nullptr || major_version_ptr == nullptr) {
1013 return ERR(NULL_POINTER);
1014 }
1015
1016 // Note: proxies will show the dex file version of java.lang.reflect.Proxy, as that is
1017 // what their dex cache copies from.
1018 uint32_t version = klass->GetDexFile().GetHeader().GetVersion();
1019
1020 *major_version_ptr = static_cast<jint>(version);
1021 *minor_version_ptr = 0;
1022
1023 return ERR(NONE);
1024}
1025
Alex Light6fa7b812017-06-16 09:04:29 -07001026jvmtiError ClassUtil::GetSourceFileName(jvmtiEnv* env, jclass jklass, char** source_name_ptr) {
1027 art::ScopedObjectAccess soa(art::Thread::Current());
1028 if (jklass == nullptr) {
1029 return ERR(INVALID_CLASS);
1030 }
1031 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1032 if (!jklass_obj->IsClass()) {
1033 return ERR(INVALID_CLASS);
1034 }
1035 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
1036 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1037 return ERR(ABSENT_INFORMATION);
1038 }
1039 JvmtiUniquePtr<char[]> source_copy;
1040 const char* file_name = klass->GetSourceFile();
1041 if (file_name == nullptr) {
1042 return ERR(ABSENT_INFORMATION);
1043 }
1044 jvmtiError ret;
1045 source_copy = CopyString(env, file_name, &ret);
1046 if (source_copy == nullptr) {
1047 return ret;
1048 }
1049 *source_name_ptr = source_copy.release();
1050 return OK;
1051}
1052
1053jvmtiError ClassUtil::GetSourceDebugExtension(jvmtiEnv* env,
1054 jclass jklass,
1055 char** source_debug_extension_ptr) {
1056 art::ScopedObjectAccess soa(art::Thread::Current());
1057 if (jklass == nullptr) {
1058 return ERR(INVALID_CLASS);
1059 }
1060 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1061 if (!jklass_obj->IsClass()) {
1062 return ERR(INVALID_CLASS);
1063 }
1064 art::StackHandleScope<1> hs(art::Thread::Current());
1065 art::Handle<art::mirror::Class> klass(hs.NewHandle(jklass_obj->AsClass()));
1066 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1067 return ERR(ABSENT_INFORMATION);
1068 }
1069 JvmtiUniquePtr<char[]> ext_copy;
1070 const char* data = art::annotations::GetSourceDebugExtension(klass);
1071 if (data == nullptr) {
1072 return ERR(ABSENT_INFORMATION);
1073 }
1074 jvmtiError ret;
1075 ext_copy = CopyString(env, data, &ret);
1076 if (ext_copy == nullptr) {
1077 return ret;
1078 }
1079 *source_debug_extension_ptr = ext_copy.release();
1080 return OK;
1081}
1082
Andreas Gampee492ae32016-10-28 19:34:57 -07001083} // namespace openjdkjvmti