blob: 0ac08d9cb849d9e9f7819cba2d7f309e289b1fef [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
Andreas Gampee6377462017-01-20 17:37:50 -080036#include <mutex>
37#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_table-inl.h"
43#include "class_linker.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"
Andreas Gampee6377462017-01-20 17:37:50 -080046#include "events-inl.h"
Alex Light40528472017-03-28 09:07:36 -070047#include "fixed_up_dex_file.h"
Andreas Gampe691051b2017-02-09 09:15:24 -080048#include "gc/heap.h"
49#include "gc_root.h"
Andreas Gampee6377462017-01-20 17:37:50 -080050#include "handle.h"
51#include "jni_env_ext-inl.h"
Andreas Gampeac587272017-01-05 15:21:34 -080052#include "jni_internal.h"
Alex Light440b5d92017-01-24 15:32:25 -080053#include "mirror/array-inl.h"
54#include "mirror/class-inl.h"
55#include "mirror/class_ext.h"
Andreas Gampe0eb36432017-02-15 18:36:14 -080056#include "mirror/object_array-inl.h"
Andreas Gampea67354b2017-02-10 16:18:30 -080057#include "mirror/object_reference.h"
58#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080059#include "mirror/object-refvisitor-inl.h"
Andreas Gampe52784ac2017-02-13 18:10:09 -080060#include "mirror/reference.h"
Alex Light6a656312017-03-29 17:18:00 -070061#include "primitive.h"
62#include "reflection.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080063#include "runtime.h"
Andreas Gampee6377462017-01-20 17:37:50 -080064#include "runtime_callbacks.h"
65#include "ScopedLocalRef.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070066#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070067#include "thread-current-inl.h"
Andreas Gampee6377462017-01-20 17:37:50 -080068#include "thread_list.h"
Alex Lighteb98b082017-01-25 13:02:32 -080069#include "ti_class_loader.h"
Alex Lightd8ce4e72017-02-27 10:52:29 -080070#include "ti_phase.h"
Alex Light440b5d92017-01-24 15:32:25 -080071#include "ti_redefine.h"
72#include "utils.h"
Andreas Gampea1d2f952017-04-20 22:53:58 -070073#include "well_known_classes.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070074
75namespace openjdkjvmti {
76
Alex Light440b5d92017-01-24 15:32:25 -080077using android::base::StringPrintf;
78
79static std::unique_ptr<const art::DexFile> MakeSingleDexFile(art::Thread* self,
80 const char* descriptor,
81 const std::string& orig_location,
82 jint final_len,
83 const unsigned char* final_dex_data)
84 REQUIRES_SHARED(art::Locks::mutator_lock_) {
85 // Make the mmap
86 std::string error_msg;
Vladimir Markoe1993c72017-06-14 17:01:38 +010087 art::ArrayRef<const unsigned char> final_data(final_dex_data, final_len);
Alex Light440b5d92017-01-24 15:32:25 -080088 std::unique_ptr<art::MemMap> map(Redefiner::MoveDataToMemMap(orig_location,
Alex Lightb7354d52017-03-30 15:17:01 -070089 final_data,
Alex Light440b5d92017-01-24 15:32:25 -080090 &error_msg));
91 if (map.get() == nullptr) {
92 LOG(WARNING) << "Unable to allocate mmap for redefined dex file! Error was: " << error_msg;
93 self->ThrowOutOfMemoryError(StringPrintf(
94 "Unable to allocate dex file for transformation of %s", descriptor).c_str());
95 return nullptr;
96 }
97
98 // Make a dex-file
99 if (map->Size() < sizeof(art::DexFile::Header)) {
100 LOG(WARNING) << "Could not read dex file header because dex_data was too short";
101 art::ThrowClassFormatError(nullptr,
102 "Unable to read transformed dex file of %s",
103 descriptor);
104 return nullptr;
105 }
106 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
Andreas Gampef45d61c2017-06-07 10:29:33 -0700107 std::string map_name = map->GetName();
108 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map_name,
Alex Light440b5d92017-01-24 15:32:25 -0800109 checksum,
110 std::move(map),
111 /*verify*/true,
112 /*verify_checksum*/true,
113 &error_msg));
114 if (dex_file.get() == nullptr) {
115 LOG(WARNING) << "Unable to load modified dex file for " << descriptor << ": " << error_msg;
116 art::ThrowClassFormatError(nullptr,
117 "Unable to read transformed dex file of %s because %s",
118 descriptor,
119 error_msg.c_str());
120 return nullptr;
121 }
122 if (dex_file->NumClassDefs() != 1) {
123 LOG(WARNING) << "Dex file contains more than 1 class_def. Ignoring.";
124 // TODO Throw some other sort of error here maybe?
125 art::ThrowClassFormatError(
126 nullptr,
127 "Unable to use transformed dex file of %s because it contained too many classes",
128 descriptor);
129 return nullptr;
130 }
131 return dex_file;
132}
133
Alex Light28b6e7e2017-05-22 16:05:59 -0700134// A deleter that acts like the jvmtiEnv->Deallocate so that asan does not get tripped up.
135// TODO We should everything use the actual jvmtiEnv->Allocate/Deallocate functions once we can
136// figure out which env to use.
137template <typename T>
138class FakeJvmtiDeleter {
139 public:
140 FakeJvmtiDeleter() {}
141
142 FakeJvmtiDeleter(FakeJvmtiDeleter&) = default;
143 FakeJvmtiDeleter(FakeJvmtiDeleter&&) = default;
144 FakeJvmtiDeleter& operator=(const FakeJvmtiDeleter&) = default;
145
146 template <typename U> void operator()(const U* ptr) const {
147 if (ptr != nullptr) {
148 free(const_cast<U*>(ptr));
149 }
150 }
151};
152
Andreas Gampee6377462017-01-20 17:37:50 -0800153struct ClassCallback : public art::ClassLoadCallback {
Alex Light440b5d92017-01-24 15:32:25 -0800154 void ClassPreDefine(const char* descriptor,
155 art::Handle<art::mirror::Class> klass,
156 art::Handle<art::mirror::ClassLoader> class_loader,
157 const art::DexFile& initial_dex_file,
158 const art::DexFile::ClassDef& initial_class_def ATTRIBUTE_UNUSED,
159 /*out*/art::DexFile const** final_dex_file,
160 /*out*/art::DexFile::ClassDef const** final_class_def)
161 OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
162 bool is_enabled =
163 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookRetransformable) ||
164 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookNonRetransformable);
165 if (!is_enabled) {
166 return;
167 }
168 if (descriptor[0] != 'L') {
169 // It is a primitive or array. Just return
170 return;
171 }
Alex Lightd8ce4e72017-02-27 10:52:29 -0800172 jvmtiPhase phase = PhaseUtil::GetPhaseUnchecked();
173 if (UNLIKELY(phase != JVMTI_PHASE_START && phase != JVMTI_PHASE_LIVE)) {
174 // We want to wait until we are at least in the START phase so that all WellKnownClasses and
175 // mirror classes have been initialized and loaded. The runtime relies on these classes having
176 // specific fields and methods present. Since PreDefine hooks don't need to abide by this
177 // restriction we will simply not send the event for these classes.
178 LOG(WARNING) << "Ignoring load of class <" << descriptor << "> as it is being loaded during "
179 << "runtime initialization.";
180 return;
181 }
182
183 // Strip the 'L' and ';' from the descriptor
Alex Light28027122017-01-26 17:21:51 -0800184 std::string name(std::string(descriptor).substr(1, strlen(descriptor) - 2));
Alex Light440b5d92017-01-24 15:32:25 -0800185
186 art::Thread* self = art::Thread::Current();
187 art::JNIEnvExt* env = self->GetJniEnv();
188 ScopedLocalRef<jobject> loader(
189 env, class_loader.IsNull() ? nullptr : env->AddLocalReference<jobject>(class_loader.Get()));
Alex Light40528472017-03-28 09:07:36 -0700190 std::unique_ptr<FixedUpDexFile> dex_file_copy(FixedUpDexFile::Create(initial_dex_file));
191
Alex Light440b5d92017-01-24 15:32:25 -0800192 // Go back to native.
193 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
194 // Call all Non-retransformable agents.
195 jint post_no_redefine_len = 0;
196 unsigned char* post_no_redefine_dex_data = nullptr;
Alex Light28b6e7e2017-05-22 16:05:59 -0700197 std::unique_ptr<const unsigned char, FakeJvmtiDeleter<const unsigned char>>
198 post_no_redefine_unique_ptr(nullptr, FakeJvmtiDeleter<const unsigned char>());
Alex Light440b5d92017-01-24 15:32:25 -0800199 event_handler->DispatchEvent<ArtJvmtiEvent::kClassFileLoadHookNonRetransformable>(
200 self,
201 static_cast<JNIEnv*>(env),
202 static_cast<jclass>(nullptr), // The class doesn't really exist yet so send null.
203 loader.get(),
204 name.c_str(),
205 static_cast<jobject>(nullptr), // Android doesn't seem to have protection domains
Alex Light40528472017-03-28 09:07:36 -0700206 static_cast<jint>(dex_file_copy->Size()),
207 static_cast<const unsigned char*>(dex_file_copy->Begin()),
Alex Light440b5d92017-01-24 15:32:25 -0800208 static_cast<jint*>(&post_no_redefine_len),
209 static_cast<unsigned char**>(&post_no_redefine_dex_data));
210 if (post_no_redefine_dex_data == nullptr) {
211 DCHECK_EQ(post_no_redefine_len, 0);
Alex Light40528472017-03-28 09:07:36 -0700212 post_no_redefine_dex_data = const_cast<unsigned char*>(dex_file_copy->Begin());
213 post_no_redefine_len = dex_file_copy->Size();
Alex Light440b5d92017-01-24 15:32:25 -0800214 } else {
Alex Light28b6e7e2017-05-22 16:05:59 -0700215 post_no_redefine_unique_ptr =
216 std::unique_ptr<const unsigned char, FakeJvmtiDeleter<const unsigned char>>(
217 post_no_redefine_dex_data, FakeJvmtiDeleter<const unsigned char>());
Alex Light440b5d92017-01-24 15:32:25 -0800218 DCHECK_GT(post_no_redefine_len, 0);
219 }
220 // Call all retransformable agents.
221 jint final_len = 0;
222 unsigned char* final_dex_data = nullptr;
Alex Light28b6e7e2017-05-22 16:05:59 -0700223 std::unique_ptr<const unsigned char, FakeJvmtiDeleter<const unsigned char>>
224 final_dex_unique_ptr(nullptr, FakeJvmtiDeleter<const unsigned char>());
Alex Light440b5d92017-01-24 15:32:25 -0800225 event_handler->DispatchEvent<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
226 self,
227 static_cast<JNIEnv*>(env),
228 static_cast<jclass>(nullptr), // The class doesn't really exist yet so send null.
229 loader.get(),
230 name.c_str(),
231 static_cast<jobject>(nullptr), // Android doesn't seem to have protection domains
232 static_cast<jint>(post_no_redefine_len),
233 static_cast<const unsigned char*>(post_no_redefine_dex_data),
234 static_cast<jint*>(&final_len),
235 static_cast<unsigned char**>(&final_dex_data));
236 if (final_dex_data == nullptr) {
237 DCHECK_EQ(final_len, 0);
238 final_dex_data = post_no_redefine_dex_data;
239 final_len = post_no_redefine_len;
240 } else {
Alex Light28b6e7e2017-05-22 16:05:59 -0700241 final_dex_unique_ptr =
242 std::unique_ptr<const unsigned char, FakeJvmtiDeleter<const unsigned char>>(
243 final_dex_data, FakeJvmtiDeleter<const unsigned char>());
Alex Light440b5d92017-01-24 15:32:25 -0800244 DCHECK_GT(final_len, 0);
245 }
246
Alex Light40528472017-03-28 09:07:36 -0700247 if (final_dex_data != dex_file_copy->Begin()) {
Alex Light440b5d92017-01-24 15:32:25 -0800248 LOG(WARNING) << "Changing class " << descriptor;
249 art::ScopedObjectAccess soa(self);
250 art::StackHandleScope<2> hs(self);
251 // Save the results of all the non-retransformable agents.
252 // First allocate the ClassExt
253 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(self)));
254 // Make sure we have a ClassExt. This is fine even though we are a temporary since it will
255 // get copied.
256 if (ext.IsNull()) {
257 // We will just return failure if we fail to allocate
258 LOG(WARNING) << "Could not allocate ext-data for class '" << descriptor << "'. "
259 << "Aborting transformation since we will be unable to store it.";
260 self->AssertPendingOOMException();
261 return;
262 }
263
264 // Allocate the byte array to store the dex file bytes in.
Alex Light6a656312017-03-29 17:18:00 -0700265 art::MutableHandle<art::mirror::Object> arr(hs.NewHandle<art::mirror::Object>(nullptr));
266 if (post_no_redefine_dex_data == dex_file_copy->Begin() && name != "java/lang/Long") {
267 // we didn't have any non-retransformable agents. We can just cache a pointer to the
268 // initial_dex_file. It will be kept live by the class_loader.
269 jlong dex_ptr = reinterpret_cast<uintptr_t>(&initial_dex_file);
270 art::JValue val;
271 val.SetJ(dex_ptr);
272 arr.Assign(art::BoxPrimitive(art::Primitive::kPrimLong, val));
273 } else {
274 arr.Assign(art::mirror::ByteArray::AllocateAndFill(
275 self,
276 reinterpret_cast<const signed char*>(post_no_redefine_dex_data),
277 post_no_redefine_len));
278 }
Alex Light440b5d92017-01-24 15:32:25 -0800279 if (arr.IsNull()) {
Alex Light6a656312017-03-29 17:18:00 -0700280 LOG(WARNING) << "Unable to allocate memory for initial dex-file. Aborting transformation";
Alex Light440b5d92017-01-24 15:32:25 -0800281 self->AssertPendingOOMException();
282 return;
283 }
284
285 std::unique_ptr<const art::DexFile> dex_file(MakeSingleDexFile(self,
286 descriptor,
287 initial_dex_file.GetLocation(),
288 final_len,
289 final_dex_data));
290 if (dex_file.get() == nullptr) {
291 return;
292 }
293
Alex Lighteb98b082017-01-25 13:02:32 -0800294 // TODO Check Redefined dex file for all invariants.
Alex Light440b5d92017-01-24 15:32:25 -0800295 LOG(WARNING) << "Dex file created by class-definition time transformation of "
296 << descriptor << " is not checked for all retransformation invariants.";
Alex Lighteb98b082017-01-25 13:02:32 -0800297
298 if (!ClassLoaderHelper::AddToClassLoader(self, class_loader, dex_file.get())) {
299 LOG(ERROR) << "Unable to add " << descriptor << " to class loader!";
300 return;
301 }
302
Alex Light440b5d92017-01-24 15:32:25 -0800303 // Actually set the ClassExt's original bytes once we have actually succeeded.
Alex Light2f814aa2017-03-24 15:21:34 +0000304 ext->SetOriginalDexFile(arr.Get());
Alex Light440b5d92017-01-24 15:32:25 -0800305 // Set the return values
306 *final_class_def = &dex_file->GetClassDef(0);
307 *final_dex_file = dex_file.release();
308 }
309 }
310
Andreas Gampee6377462017-01-20 17:37:50 -0800311 void ClassLoad(art::Handle<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
312 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassLoad)) {
313 art::Thread* thread = art::Thread::Current();
314 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
315 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700316 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800317 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700318 thread->GetJniEnv(),
319 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Andreas Gampee6377462017-01-20 17:37:50 -0800320 {
321 art::ScopedThreadSuspension sts(thread, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -0800322 event_handler->DispatchEvent<ArtJvmtiEvent::kClassLoad>(
323 thread,
324 static_cast<JNIEnv*>(thread->GetJniEnv()),
325 thread_jni.get(),
326 jklass.get());
Andreas Gampee6377462017-01-20 17:37:50 -0800327 }
Andreas Gampe691051b2017-02-09 09:15:24 -0800328 if (klass->IsTemp()) {
329 AddTempClass(thread, jklass.get());
330 }
Andreas Gampee6377462017-01-20 17:37:50 -0800331 }
332 }
333
Andreas Gampe691051b2017-02-09 09:15:24 -0800334 void ClassPrepare(art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800335 art::Handle<art::mirror::Class> klass)
336 REQUIRES_SHARED(art::Locks::mutator_lock_) {
337 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassPrepare)) {
338 art::Thread* thread = art::Thread::Current();
Andreas Gampe691051b2017-02-09 09:15:24 -0800339 if (temp_klass.Get() != klass.Get()) {
340 DCHECK(temp_klass->IsTemp());
341 DCHECK(temp_klass->IsRetired());
342 HandleTempClass(thread, temp_klass, klass);
343 }
Andreas Gampee6377462017-01-20 17:37:50 -0800344 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
345 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Alex Light72398652017-06-16 09:08:12 -0700346 art::ObjPtr<art::mirror::Object> peer(thread->GetPeer());
Andreas Gampe983c1752017-01-23 19:46:56 -0800347 ScopedLocalRef<jthread> thread_jni(
Alex Light72398652017-06-16 09:08:12 -0700348 thread->GetJniEnv(),
349 peer.IsNull() ? nullptr : thread->GetJniEnv()->AddLocalReference<jthread>(peer));
Andreas Gampee6377462017-01-20 17:37:50 -0800350 art::ScopedThreadSuspension sts(thread, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -0800351 event_handler->DispatchEvent<ArtJvmtiEvent::kClassPrepare>(
352 thread,
353 static_cast<JNIEnv*>(thread->GetJniEnv()),
354 thread_jni.get(),
355 jklass.get());
Andreas Gampee6377462017-01-20 17:37:50 -0800356 }
357 }
358
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800359 // To support parallel class-loading, we need to perform some locking dances here. Namely,
360 // the fixup stage must not be holding the temp_classes lock when it fixes up the system
361 // (as that requires suspending all mutators).
362
Andreas Gampee6377462017-01-20 17:37:50 -0800363 void AddTempClass(art::Thread* self, jclass klass) {
364 std::unique_lock<std::mutex> mu(temp_classes_lock);
Andreas Gampe691051b2017-02-09 09:15:24 -0800365 jclass global_klass = reinterpret_cast<jclass>(self->GetJniEnv()->NewGlobalRef(klass));
366 temp_classes.push_back(global_klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800367 }
368
Andreas Gampe691051b2017-02-09 09:15:24 -0800369 void HandleTempClass(art::Thread* self,
370 art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800371 art::Handle<art::mirror::Class> klass)
372 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800373 bool requires_fixup = false;
374 {
375 std::unique_lock<std::mutex> mu(temp_classes_lock);
376 if (temp_classes.empty()) {
377 return;
Andreas Gampee6377462017-01-20 17:37:50 -0800378 }
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800379
380 for (auto it = temp_classes.begin(); it != temp_classes.end(); ++it) {
381 if (temp_klass.Get() == art::ObjPtr<art::mirror::Class>::DownCast(self->DecodeJObject(*it))) {
382 self->GetJniEnv()->DeleteGlobalRef(*it);
383 temp_classes.erase(it);
384 requires_fixup = true;
385 break;
386 }
387 }
388 }
389 if (requires_fixup) {
390 FixupTempClass(self, temp_klass, klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800391 }
392 }
393
Andreas Gampe691051b2017-02-09 09:15:24 -0800394 void FixupTempClass(art::Thread* self,
395 art::Handle<art::mirror::Class> temp_klass,
396 art::Handle<art::mirror::Class> klass)
Andreas Gampee6377462017-01-20 17:37:50 -0800397 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe691051b2017-02-09 09:15:24 -0800398 // Suspend everything.
399 art::gc::Heap* heap = art::Runtime::Current()->GetHeap();
400 if (heap->IsGcConcurrentAndMoving()) {
401 // Need to take a heap dump while GC isn't running. See the
402 // comment in Heap::VisitObjects().
403 heap->IncrementDisableMovingGC(self);
404 }
405 {
406 art::ScopedThreadSuspension sts(self, art::kWaitingForVisitObjects);
407 art::ScopedSuspendAll ssa("FixupTempClass");
408
409 art::mirror::Class* input = temp_klass.Get();
410 art::mirror::Class* output = klass.Get();
411
412 FixupGlobalReferenceTables(input, output);
Andreas Gampe94dda932017-02-09 18:19:21 -0800413 FixupLocalReferenceTables(self, input, output);
Andreas Gampea67354b2017-02-10 16:18:30 -0800414 FixupHeap(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800415 }
416 if (heap->IsGcConcurrentAndMoving()) {
417 heap->DecrementDisableMovingGC(self);
418 }
419 }
420
Andreas Gampe94dda932017-02-09 18:19:21 -0800421 class RootUpdater : public art::RootVisitor {
422 public:
423 RootUpdater(const art::mirror::Class* input, art::mirror::Class* output)
424 : input_(input), output_(output) {}
425
426 void VisitRoots(art::mirror::Object*** roots,
427 size_t count,
428 const art::RootInfo& info ATTRIBUTE_UNUSED)
429 OVERRIDE {
430 for (size_t i = 0; i != count; ++i) {
431 if (*roots[i] == input_) {
432 *roots[i] = output_;
433 }
434 }
435 }
436
437 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
438 size_t count,
439 const art::RootInfo& info ATTRIBUTE_UNUSED)
440 OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
441 for (size_t i = 0; i != count; ++i) {
442 if (roots[i]->AsMirrorPtr() == input_) {
443 roots[i]->Assign(output_);
444 }
445 }
446 }
447
448 private:
449 const art::mirror::Class* input_;
450 art::mirror::Class* output_;
451 };
452
Andreas Gampea67354b2017-02-10 16:18:30 -0800453 void FixupGlobalReferenceTables(art::mirror::Class* input, art::mirror::Class* output)
Andreas Gampe691051b2017-02-09 09:15:24 -0800454 REQUIRES(art::Locks::mutator_lock_) {
455 art::JavaVMExt* java_vm = art::Runtime::Current()->GetJavaVM();
456
457 // Fix up the global table with a root visitor.
Andreas Gampe94dda932017-02-09 18:19:21 -0800458 RootUpdater global_update(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800459 java_vm->VisitRoots(&global_update);
460
461 class WeakGlobalUpdate : public art::IsMarkedVisitor {
462 public:
463 WeakGlobalUpdate(art::mirror::Class* root_input, art::mirror::Class* root_output)
464 : input_(root_input), output_(root_output) {}
465
466 art::mirror::Object* IsMarked(art::mirror::Object* obj) OVERRIDE {
467 if (obj == input_) {
468 return output_;
469 }
470 return obj;
471 }
472
473 private:
474 const art::mirror::Class* input_;
475 art::mirror::Class* output_;
476 };
477 WeakGlobalUpdate weak_global_update(input, output);
478 java_vm->SweepJniWeakGlobals(&weak_global_update);
Andreas Gampee6377462017-01-20 17:37:50 -0800479 }
480
Andreas Gampe94dda932017-02-09 18:19:21 -0800481 void FixupLocalReferenceTables(art::Thread* self,
482 art::mirror::Class* input,
483 art::mirror::Class* output)
484 REQUIRES(art::Locks::mutator_lock_) {
485 class LocalUpdate {
486 public:
487 LocalUpdate(const art::mirror::Class* root_input, art::mirror::Class* root_output)
488 : input_(root_input), output_(root_output) {}
489
490 static void Callback(art::Thread* t, void* arg) REQUIRES(art::Locks::mutator_lock_) {
491 LocalUpdate* local = reinterpret_cast<LocalUpdate*>(arg);
492
493 // Fix up the local table with a root visitor.
494 RootUpdater local_update(local->input_, local->output_);
495 t->GetJniEnv()->locals.VisitRoots(
496 &local_update, art::RootInfo(art::kRootJNILocal, t->GetThreadId()));
497 }
498
499 private:
500 const art::mirror::Class* input_;
501 art::mirror::Class* output_;
502 };
503 LocalUpdate local_upd(input, output);
504 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
505 art::Runtime::Current()->GetThreadList()->ForEach(LocalUpdate::Callback, &local_upd);
506 }
507
Andreas Gampea67354b2017-02-10 16:18:30 -0800508 void FixupHeap(art::mirror::Class* input, art::mirror::Class* output)
509 REQUIRES(art::Locks::mutator_lock_) {
510 class HeapFixupVisitor {
511 public:
512 HeapFixupVisitor(const art::mirror::Class* root_input, art::mirror::Class* root_output)
513 : input_(root_input), output_(root_output) {}
514
515 void operator()(art::mirror::Object* src,
516 art::MemberOffset field_offset,
517 bool is_static ATTRIBUTE_UNUSED) const
518 REQUIRES_SHARED(art::Locks::mutator_lock_) {
519 art::mirror::HeapReference<art::mirror::Object>* trg =
520 src->GetFieldObjectReferenceAddr(field_offset);
521 if (trg->AsMirrorPtr() == input_) {
522 DCHECK_NE(field_offset.Uint32Value(), 0u); // This shouldn't be the class field of
523 // an object.
524 trg->Assign(output_);
525 }
526 }
527
Andreas Gampe52784ac2017-02-13 18:10:09 -0800528 void operator()(art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
529 art::ObjPtr<art::mirror::Reference> reference) const
530 REQUIRES_SHARED(art::Locks::mutator_lock_) {
531 art::mirror::Object* val = reference->GetReferent();
532 if (val == input_) {
533 reference->SetReferent<false>(output_);
534 }
535 }
536
Andreas Gampea67354b2017-02-10 16:18:30 -0800537 void VisitRoot(art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED)
Andreas Gampe52784ac2017-02-13 18:10:09 -0800538 const {
Andreas Gampea67354b2017-02-10 16:18:30 -0800539 LOG(FATAL) << "Unreachable";
540 }
541
542 void VisitRootIfNonNull(
543 art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED) const {
544 LOG(FATAL) << "Unreachable";
545 }
546
547 static void AllObjectsCallback(art::mirror::Object* obj, void* arg)
548 REQUIRES_SHARED(art::Locks::mutator_lock_) {
549 HeapFixupVisitor* hfv = reinterpret_cast<HeapFixupVisitor*>(arg);
550
551 // Visit references, not native roots.
Andreas Gampe52784ac2017-02-13 18:10:09 -0800552 obj->VisitReferences<false>(*hfv, *hfv);
Andreas Gampea67354b2017-02-10 16:18:30 -0800553 }
554
555 private:
556 const art::mirror::Class* input_;
557 art::mirror::Class* output_;
558 };
559 HeapFixupVisitor hfv(input, output);
560 art::Runtime::Current()->GetHeap()->VisitObjectsPaused(HeapFixupVisitor::AllObjectsCallback,
561 &hfv);
562 }
563
Andreas Gampee6377462017-01-20 17:37:50 -0800564 // A set of all the temp classes we have handed out. We have to fix up references to these.
565 // For simplicity, we store the temp classes as JNI global references in a vector. Normally a
566 // Prepare event will closely follow, so the vector should be small.
567 std::mutex temp_classes_lock;
568 std::vector<jclass> temp_classes;
569
570 EventHandler* event_handler = nullptr;
571};
572
573ClassCallback gClassCallback;
574
575void ClassUtil::Register(EventHandler* handler) {
576 gClassCallback.event_handler = handler;
577 art::ScopedThreadStateChange stsc(art::Thread::Current(),
578 art::ThreadState::kWaitingForDebuggerToAttach);
579 art::ScopedSuspendAll ssa("Add load callback");
580 art::Runtime::Current()->GetRuntimeCallbacks()->AddClassLoadCallback(&gClassCallback);
581}
582
583void ClassUtil::Unregister() {
584 art::ScopedThreadStateChange stsc(art::Thread::Current(),
585 art::ThreadState::kWaitingForDebuggerToAttach);
586 art::ScopedSuspendAll ssa("Remove thread callback");
587 art::Runtime* runtime = art::Runtime::Current();
588 runtime->GetRuntimeCallbacks()->RemoveClassLoadCallback(&gClassCallback);
589}
590
Andreas Gampeac587272017-01-05 15:21:34 -0800591jvmtiError ClassUtil::GetClassFields(jvmtiEnv* env,
592 jclass jklass,
593 jint* field_count_ptr,
594 jfieldID** fields_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
601 if (field_count_ptr == nullptr || fields_ptr == nullptr) {
602 return ERR(NULL_POINTER);
603 }
604
Andreas Gampeac587272017-01-05 15:21:34 -0800605 art::IterationRange<art::StrideIterator<art::ArtField>> ifields = klass->GetIFields();
606 art::IterationRange<art::StrideIterator<art::ArtField>> sfields = klass->GetSFields();
607 size_t array_size = klass->NumInstanceFields() + klass->NumStaticFields();
608
609 unsigned char* out_ptr;
610 jvmtiError allocError = env->Allocate(array_size * sizeof(jfieldID), &out_ptr);
611 if (allocError != ERR(NONE)) {
612 return allocError;
613 }
614 jfieldID* field_array = reinterpret_cast<jfieldID*>(out_ptr);
615
616 size_t array_idx = 0;
617 for (art::ArtField& field : sfields) {
618 field_array[array_idx] = art::jni::EncodeArtField(&field);
619 ++array_idx;
620 }
621 for (art::ArtField& field : ifields) {
622 field_array[array_idx] = art::jni::EncodeArtField(&field);
623 ++array_idx;
624 }
625
626 *field_count_ptr = static_cast<jint>(array_size);
627 *fields_ptr = field_array;
628
629 return ERR(NONE);
630}
631
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800632jvmtiError ClassUtil::GetClassMethods(jvmtiEnv* env,
633 jclass jklass,
634 jint* method_count_ptr,
635 jmethodID** methods_ptr) {
636 art::ScopedObjectAccess soa(art::Thread::Current());
637 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
638 if (klass == nullptr) {
639 return ERR(INVALID_CLASS);
640 }
641
642 if (method_count_ptr == nullptr || methods_ptr == nullptr) {
643 return ERR(NULL_POINTER);
644 }
645
646 size_t array_size = klass->NumDeclaredVirtualMethods() + klass->NumDirectMethods();
647 unsigned char* out_ptr;
648 jvmtiError allocError = env->Allocate(array_size * sizeof(jmethodID), &out_ptr);
649 if (allocError != ERR(NONE)) {
650 return allocError;
651 }
652 jmethodID* method_array = reinterpret_cast<jmethodID*>(out_ptr);
653
654 if (art::kIsDebugBuild) {
655 size_t count = 0;
656 for (auto& m ATTRIBUTE_UNUSED : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
657 count++;
658 }
659 CHECK_EQ(count, klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods());
660 }
661
662 size_t array_idx = 0;
663 for (auto& m : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
664 method_array[array_idx] = art::jni::EncodeArtMethod(&m);
665 ++array_idx;
666 }
667
668 *method_count_ptr = static_cast<jint>(array_size);
669 *methods_ptr = method_array;
670
671 return ERR(NONE);
672}
673
Andreas Gampe8b07e472017-01-06 14:20:39 -0800674jvmtiError ClassUtil::GetImplementedInterfaces(jvmtiEnv* env,
675 jclass jklass,
676 jint* interface_count_ptr,
677 jclass** interfaces_ptr) {
678 art::ScopedObjectAccess soa(art::Thread::Current());
679 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
680 if (klass == nullptr) {
681 return ERR(INVALID_CLASS);
682 }
683
684 if (interface_count_ptr == nullptr || interfaces_ptr == nullptr) {
685 return ERR(NULL_POINTER);
686 }
687
688 // Need to handle array specifically. Arrays implement Serializable and Cloneable, but the
689 // spec says these should not be reported.
690 if (klass->IsArrayClass()) {
691 *interface_count_ptr = 0;
692 *interfaces_ptr = nullptr; // TODO: Should we allocate a dummy here?
693 return ERR(NONE);
694 }
695
696 size_t array_size = klass->NumDirectInterfaces();
697 unsigned char* out_ptr;
698 jvmtiError allocError = env->Allocate(array_size * sizeof(jclass), &out_ptr);
699 if (allocError != ERR(NONE)) {
700 return allocError;
701 }
702 jclass* interface_array = reinterpret_cast<jclass*>(out_ptr);
703
704 art::StackHandleScope<1> hs(soa.Self());
705 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
706
707 for (uint32_t idx = 0; idx != array_size; ++idx) {
708 art::ObjPtr<art::mirror::Class> inf_klass =
709 art::mirror::Class::ResolveDirectInterface(soa.Self(), h_klass, idx);
710 if (inf_klass == nullptr) {
711 soa.Self()->ClearException();
712 env->Deallocate(out_ptr);
713 // TODO: What is the right error code here?
714 return ERR(INTERNAL);
715 }
716 interface_array[idx] = soa.AddLocalReference<jclass>(inf_klass);
717 }
718
719 *interface_count_ptr = static_cast<jint>(array_size);
720 *interfaces_ptr = interface_array;
721
722 return ERR(NONE);
723}
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800724
Andreas Gampee492ae32016-10-28 19:34:57 -0700725jvmtiError ClassUtil::GetClassSignature(jvmtiEnv* env,
726 jclass jklass,
727 char** signature_ptr,
728 char** generic_ptr) {
729 art::ScopedObjectAccess soa(art::Thread::Current());
730 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
731 if (klass == nullptr) {
732 return ERR(INVALID_CLASS);
733 }
734
Andreas Gampe54711412017-02-21 12:41:43 -0800735 JvmtiUniquePtr<char[]> sig_copy;
Andreas Gampee492ae32016-10-28 19:34:57 -0700736 if (signature_ptr != nullptr) {
737 std::string storage;
738 const char* descriptor = klass->GetDescriptor(&storage);
739
Andreas Gampe54711412017-02-21 12:41:43 -0800740 jvmtiError ret;
741 sig_copy = CopyString(env, descriptor, &ret);
742 if (sig_copy == nullptr) {
Andreas Gampee492ae32016-10-28 19:34:57 -0700743 return ret;
744 }
Andreas Gampe54711412017-02-21 12:41:43 -0800745 *signature_ptr = sig_copy.get();
Andreas Gampee492ae32016-10-28 19:34:57 -0700746 }
747
Andreas Gampee6377462017-01-20 17:37:50 -0800748 if (generic_ptr != nullptr) {
749 *generic_ptr = nullptr;
Andreas Gampe0eb36432017-02-15 18:36:14 -0800750 if (!klass->IsProxyClass() && klass->GetDexCache() != nullptr) {
751 art::StackHandleScope<1> hs(soa.Self());
752 art::Handle<art::mirror::Class> h_klass = hs.NewHandle(klass);
753 art::mirror::ObjectArray<art::mirror::String>* str_array =
754 art::annotations::GetSignatureAnnotationForClass(h_klass);
755 if (str_array != nullptr) {
756 std::ostringstream oss;
757 for (int32_t i = 0; i != str_array->GetLength(); ++i) {
758 oss << str_array->Get(i)->ToModifiedUtf8();
759 }
760 std::string output_string = oss.str();
Andreas Gampe54711412017-02-21 12:41:43 -0800761 jvmtiError ret;
762 JvmtiUniquePtr<char[]> copy = CopyString(env, output_string.c_str(), &ret);
763 if (copy == nullptr) {
Andreas Gampe0eb36432017-02-15 18:36:14 -0800764 return ret;
765 }
Andreas Gampe54711412017-02-21 12:41:43 -0800766 *generic_ptr = copy.release();
Andreas Gampe0eb36432017-02-15 18:36:14 -0800767 } else if (soa.Self()->IsExceptionPending()) {
768 // TODO: Should we report an error here?
769 soa.Self()->ClearException();
770 }
771 }
Andreas Gampee6377462017-01-20 17:37:50 -0800772 }
Andreas Gampee492ae32016-10-28 19:34:57 -0700773
774 // Everything is fine, release the buffers.
775 sig_copy.release();
776
777 return ERR(NONE);
778}
779
Andreas Gampeff9d2092017-01-06 09:12:49 -0800780jvmtiError ClassUtil::GetClassStatus(jvmtiEnv* env ATTRIBUTE_UNUSED,
781 jclass jklass,
782 jint* status_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 (status_ptr == nullptr) {
790 return ERR(NULL_POINTER);
791 }
792
793 if (klass->IsArrayClass()) {
794 *status_ptr = JVMTI_CLASS_STATUS_ARRAY;
795 } else if (klass->IsPrimitive()) {
796 *status_ptr = JVMTI_CLASS_STATUS_PRIMITIVE;
797 } else {
798 *status_ptr = JVMTI_CLASS_STATUS_VERIFIED; // All loaded classes are structurally verified.
799 // This is finicky. If there's an error, we'll say it wasn't prepared.
800 if (klass->IsResolved()) {
801 *status_ptr |= JVMTI_CLASS_STATUS_PREPARED;
802 }
803 if (klass->IsInitialized()) {
804 *status_ptr |= JVMTI_CLASS_STATUS_INITIALIZED;
805 }
806 // Technically the class may be erroneous for other reasons, but we do not have enough info.
807 if (klass->IsErroneous()) {
808 *status_ptr |= JVMTI_CLASS_STATUS_ERROR;
809 }
810 }
811
812 return ERR(NONE);
813}
814
Andreas Gampe4fd66ec2017-01-05 14:42:13 -0800815template <typename T>
816static jvmtiError ClassIsT(jclass jklass, T test, jboolean* is_t_ptr) {
817 art::ScopedObjectAccess soa(art::Thread::Current());
818 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
819 if (klass == nullptr) {
820 return ERR(INVALID_CLASS);
821 }
822
823 if (is_t_ptr == nullptr) {
824 return ERR(NULL_POINTER);
825 }
826
827 *is_t_ptr = test(klass) ? JNI_TRUE : JNI_FALSE;
828 return ERR(NONE);
829}
830
831jvmtiError ClassUtil::IsInterface(jvmtiEnv* env ATTRIBUTE_UNUSED,
832 jclass jklass,
833 jboolean* is_interface_ptr) {
834 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
835 return klass->IsInterface();
836 };
837 return ClassIsT(jklass, test, is_interface_ptr);
838}
839
840jvmtiError ClassUtil::IsArrayClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
841 jclass jklass,
842 jboolean* is_array_class_ptr) {
843 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
844 return klass->IsArrayClass();
845 };
846 return ClassIsT(jklass, test, is_array_class_ptr);
847}
848
Andreas Gampe64013e52017-01-06 13:07:19 -0800849// Keep this in sync with Class.getModifiers().
850static uint32_t ClassGetModifiers(art::Thread* self, art::ObjPtr<art::mirror::Class> klass)
851 REQUIRES_SHARED(art::Locks::mutator_lock_) {
852 if (klass->IsArrayClass()) {
853 uint32_t component_modifiers = ClassGetModifiers(self, klass->GetComponentType());
854 if ((component_modifiers & art::kAccInterface) != 0) {
855 component_modifiers &= ~(art::kAccInterface | art::kAccStatic);
856 }
857 return art::kAccAbstract | art::kAccFinal | component_modifiers;
858 }
859
860 uint32_t modifiers = klass->GetAccessFlags() & art::kAccJavaFlagsMask;
861
862 art::StackHandleScope<1> hs(self);
863 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
864 return art::mirror::Class::GetInnerClassFlags(h_klass, modifiers);
865}
866
867jvmtiError ClassUtil::GetClassModifiers(jvmtiEnv* env ATTRIBUTE_UNUSED,
868 jclass jklass,
869 jint* modifiers_ptr) {
870 art::ScopedObjectAccess soa(art::Thread::Current());
871 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
872 if (klass == nullptr) {
873 return ERR(INVALID_CLASS);
874 }
875
876 if (modifiers_ptr == nullptr) {
877 return ERR(NULL_POINTER);
878 }
879
880 *modifiers_ptr = ClassGetModifiers(soa.Self(), klass);
881
882 return ERR(NONE);
883}
884
Andreas Gampe8f5b6032017-01-06 15:50:55 -0800885jvmtiError ClassUtil::GetClassLoader(jvmtiEnv* env ATTRIBUTE_UNUSED,
886 jclass jklass,
887 jobject* classloader_ptr) {
888 art::ScopedObjectAccess soa(art::Thread::Current());
889 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
890 if (klass == nullptr) {
891 return ERR(INVALID_CLASS);
892 }
893
894 if (classloader_ptr == nullptr) {
895 return ERR(NULL_POINTER);
896 }
897
898 *classloader_ptr = soa.AddLocalReference<jobject>(klass->GetClassLoader());
899
900 return ERR(NONE);
901}
902
Andreas Gampe70f16392017-01-16 14:20:10 -0800903jvmtiError ClassUtil::GetClassLoaderClasses(jvmtiEnv* env,
904 jobject initiating_loader,
905 jint* class_count_ptr,
906 jclass** classes_ptr) {
907 UNUSED(env, initiating_loader, class_count_ptr, classes_ptr);
908
909 if (class_count_ptr == nullptr || classes_ptr == nullptr) {
910 return ERR(NULL_POINTER);
911 }
912 art::Thread* self = art::Thread::Current();
913 if (!self->GetJniEnv()->IsInstanceOf(initiating_loader,
914 art::WellKnownClasses::java_lang_ClassLoader)) {
915 return ERR(ILLEGAL_ARGUMENT);
916 }
917 if (self->GetJniEnv()->IsInstanceOf(initiating_loader,
918 art::WellKnownClasses::java_lang_BootClassLoader)) {
919 // Need to use null for the BootClassLoader.
920 initiating_loader = nullptr;
921 }
922
923 art::ScopedObjectAccess soa(self);
924 art::ObjPtr<art::mirror::ClassLoader> class_loader =
925 soa.Decode<art::mirror::ClassLoader>(initiating_loader);
926
927 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
928
929 art::ReaderMutexLock mu(self, *art::Locks::classlinker_classes_lock_);
930
931 art::ClassTable* class_table = class_linker->ClassTableForClassLoader(class_loader);
932 if (class_table == nullptr) {
933 // Nothing loaded.
934 *class_count_ptr = 0;
935 *classes_ptr = nullptr;
936 return ERR(NONE);
937 }
938
939 struct ClassTableCount {
940 bool operator()(art::ObjPtr<art::mirror::Class> klass) {
941 DCHECK(klass != nullptr);
942 ++count;
943 return true;
944 }
945
946 size_t count = 0;
947 };
948 ClassTableCount ctc;
949 class_table->Visit(ctc);
950
951 if (ctc.count == 0) {
952 // Nothing loaded.
953 *class_count_ptr = 0;
954 *classes_ptr = nullptr;
955 return ERR(NONE);
956 }
957
958 unsigned char* data;
959 jvmtiError data_result = env->Allocate(ctc.count * sizeof(jclass), &data);
960 if (data_result != ERR(NONE)) {
961 return data_result;
962 }
963 jclass* class_array = reinterpret_cast<jclass*>(data);
964
965 struct ClassTableFill {
966 bool operator()(art::ObjPtr<art::mirror::Class> klass)
967 REQUIRES_SHARED(art::Locks::mutator_lock_) {
968 DCHECK(klass != nullptr);
969 DCHECK_LT(count, ctc_ref.count);
970 local_class_array[count++] = soa_ptr->AddLocalReference<jclass>(klass);
971 return true;
972 }
973
974 jclass* local_class_array;
975 const ClassTableCount& ctc_ref;
976 art::ScopedObjectAccess* soa_ptr;
977 size_t count;
978 };
979 ClassTableFill ctf = { class_array, ctc, &soa, 0 };
980 class_table->Visit(ctf);
981 DCHECK_EQ(ctc.count, ctf.count);
982
983 *class_count_ptr = ctc.count;
984 *classes_ptr = class_array;
985
986 return ERR(NONE);
987}
988
Andreas Gampe812a2442017-01-19 22:04:46 -0800989jvmtiError ClassUtil::GetClassVersionNumbers(jvmtiEnv* env ATTRIBUTE_UNUSED,
990 jclass jklass,
991 jint* minor_version_ptr,
992 jint* major_version_ptr) {
993 art::ScopedObjectAccess soa(art::Thread::Current());
994 if (jklass == nullptr) {
995 return ERR(INVALID_CLASS);
996 }
997 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
998 if (!jklass_obj->IsClass()) {
999 return ERR(INVALID_CLASS);
1000 }
1001 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
1002 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1003 return ERR(INVALID_CLASS);
1004 }
1005
1006 if (minor_version_ptr == nullptr || major_version_ptr == nullptr) {
1007 return ERR(NULL_POINTER);
1008 }
1009
1010 // Note: proxies will show the dex file version of java.lang.reflect.Proxy, as that is
1011 // what their dex cache copies from.
1012 uint32_t version = klass->GetDexFile().GetHeader().GetVersion();
1013
1014 *major_version_ptr = static_cast<jint>(version);
1015 *minor_version_ptr = 0;
1016
1017 return ERR(NONE);
1018}
1019
Alex Light6fa7b812017-06-16 09:04:29 -07001020jvmtiError ClassUtil::GetSourceFileName(jvmtiEnv* env, jclass jklass, char** source_name_ptr) {
1021 art::ScopedObjectAccess soa(art::Thread::Current());
1022 if (jklass == nullptr) {
1023 return ERR(INVALID_CLASS);
1024 }
1025 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
1026 if (!jklass_obj->IsClass()) {
1027 return ERR(INVALID_CLASS);
1028 }
1029 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
1030 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1031 return ERR(ABSENT_INFORMATION);
1032 }
1033 JvmtiUniquePtr<char[]> source_copy;
1034 const char* file_name = klass->GetSourceFile();
1035 if (file_name == nullptr) {
1036 return ERR(ABSENT_INFORMATION);
1037 }
1038 jvmtiError ret;
1039 source_copy = CopyString(env, file_name, &ret);
1040 if (source_copy == nullptr) {
1041 return ret;
1042 }
1043 *source_name_ptr = source_copy.release();
1044 return OK;
1045}
1046
1047jvmtiError ClassUtil::GetSourceDebugExtension(jvmtiEnv* env,
1048 jclass jklass,
1049 char** source_debug_extension_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::StackHandleScope<1> hs(art::Thread::Current());
1059 art::Handle<art::mirror::Class> klass(hs.NewHandle(jklass_obj->AsClass()));
1060 if (klass->IsPrimitive() || klass->IsArrayClass()) {
1061 return ERR(ABSENT_INFORMATION);
1062 }
1063 JvmtiUniquePtr<char[]> ext_copy;
1064 const char* data = art::annotations::GetSourceDebugExtension(klass);
1065 if (data == nullptr) {
1066 return ERR(ABSENT_INFORMATION);
1067 }
1068 jvmtiError ret;
1069 ext_copy = CopyString(env, data, &ret);
1070 if (ext_copy == nullptr) {
1071 return ret;
1072 }
1073 *source_debug_extension_ptr = ext_copy.release();
1074 return OK;
1075}
1076
Andreas Gampee492ae32016-10-28 19:34:57 -07001077} // namespace openjdkjvmti