blob: 2a1d44207aeb3343045578a8c9f50238f746dad9 [file] [log] [blame]
Andreas Gampee54d9922016-10-11 19:55:37 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andreas Gampeba8df692016-11-01 10:30:44 -070017#include "ti_heap.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070018
Alex Lightc14ec8f2019-07-18 16:08:41 -070019#include <ios>
Alex Light986914b2019-11-19 01:12:25 +000020#include <unordered_map>
Alex Lightc14ec8f2019-07-18 16:08:41 -070021
22#include "android-base/logging.h"
23#include "android-base/thread_annotations.h"
24#include "arch/context.h"
Andreas Gampe70bfc8a2016-11-03 11:04:15 -070025#include "art_field-inl.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070026#include "art_jvmti.h"
Alex Lightb0ce4d22019-09-19 14:45:45 -070027#include "base/logging.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070028#include "base/macros.h"
29#include "base/mutex.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070030#include "base/utils.h"
Andreas Gampeaa8b60c2016-10-12 12:51:25 -070031#include "class_linker.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070032#include "deopt_manager.h"
David Sehr67bf42e2018-02-26 16:43:04 -080033#include "dex/primitive.h"
Alex Light72d7e942019-07-23 13:10:20 -070034#include "events-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070035#include "gc/collector_type.h"
36#include "gc/gc_cause.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070037#include "gc/heap-visit-objects-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070038#include "gc/heap-inl.h"
39#include "gc/scoped_gc_critical_section.h"
Andreas Gampe70bfc8a2016-11-03 11:04:15 -070040#include "gc_root-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070041#include "handle.h"
Alex Light79d6c802019-06-27 15:50:11 +000042#include "handle_scope.h"
Andreas Gampe36a296f2017-06-13 14:11:11 -070043#include "java_frame_root_info.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010044#include "jni/jni_env_ext.h"
Alex Light79d6c802019-06-27 15:50:11 +000045#include "jni/jni_id_manager.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010046#include "jni/jni_internal.h"
Andreas Gampe9e38a502017-03-06 08:19:26 -080047#include "jvmti_weak_table-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070048#include "mirror/array-inl.h"
49#include "mirror/array.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070050#include "mirror/class.h"
Andreas Gampe70bfc8a2016-11-03 11:04:15 -070051#include "mirror/object-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070052#include "mirror/object-refvisitor-inl.h"
Andreas Gampe70bfc8a2016-11-03 11:04:15 -070053#include "mirror/object_array-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070054#include "mirror/object_array-alloc-inl.h"
55#include "mirror/object_reference.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070056#include "obj_ptr-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070057#include "object_callbacks.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070058#include "object_tagging.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070059#include "offsets.h"
Alex Lighta142f712019-12-03 05:52:33 -080060#include "read_barrier.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070061#include "runtime.h"
62#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070063#include "stack.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070064#include "thread-inl.h"
Andreas Gampe70bfc8a2016-11-03 11:04:15 -070065#include "thread_list.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070066#include "ti_logging.h"
67#include "ti_stack.h"
68#include "ti_thread.h"
Alex Light79d6c802019-06-27 15:50:11 +000069#include "well_known_classes.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070070
71namespace openjdkjvmti {
72
Alex Light72d7e942019-07-23 13:10:20 -070073EventHandler* HeapExtensions::gEventHandler = nullptr;
74
Andreas Gampe3ec8e402017-02-21 15:49:53 -080075namespace {
76
Andreas Gampe9e38a502017-03-06 08:19:26 -080077struct IndexCache {
78 // The number of interface fields implemented by the class. This is a prefix to all assigned
79 // field indices.
80 size_t interface_fields;
81
82 // It would be nice to also cache the following, but it is complicated to wire up into the
83 // generic visit:
84 // The number of fields in interfaces and superclasses. This is the first index assigned to
85 // fields of the class.
86 // size_t superclass_fields;
87};
88using IndexCachingTable = JvmtiWeakTable<IndexCache>;
89
90static IndexCachingTable gIndexCachingTable;
91
Andreas Gampe3ec8e402017-02-21 15:49:53 -080092// Report the contents of a string, if a callback is set.
93jint ReportString(art::ObjPtr<art::mirror::Object> obj,
94 jvmtiEnv* env,
95 ObjectTagTable* tag_table,
96 const jvmtiHeapCallbacks* cb,
97 const void* user_data) REQUIRES_SHARED(art::Locks::mutator_lock_) {
98 if (UNLIKELY(cb->string_primitive_value_callback != nullptr) && obj->IsString()) {
99 art::ObjPtr<art::mirror::String> str = obj->AsString();
100 int32_t string_length = str->GetLength();
Andreas Gampe5f942032017-02-27 19:59:40 -0800101 JvmtiUniquePtr<uint16_t[]> data;
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800102
Andreas Gampe5f942032017-02-27 19:59:40 -0800103 if (string_length > 0) {
104 jvmtiError alloc_error;
105 data = AllocJvmtiUniquePtr<uint16_t[]>(env, string_length, &alloc_error);
106 if (data == nullptr) {
107 // TODO: Not really sure what to do here. Should we abort the iteration and go all the way
108 // back? For now just warn.
109 LOG(WARNING) << "Unable to allocate buffer for string reporting! Silently dropping value."
110 << " >" << str->ToModifiedUtf8() << "<";
111 return 0;
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800112 }
Andreas Gampe5f942032017-02-27 19:59:40 -0800113
114 if (str->IsCompressed()) {
115 uint8_t* compressed_data = str->GetValueCompressed();
116 for (int32_t i = 0; i != string_length; ++i) {
117 data[i] = compressed_data[i];
118 }
119 } else {
120 // Can copy directly.
121 memcpy(data.get(), str->GetValue(), string_length * sizeof(uint16_t));
122 }
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800123 }
124
125 const jlong class_tag = tag_table->GetTagOrZero(obj->GetClass());
126 jlong string_tag = tag_table->GetTagOrZero(obj.Ptr());
127 const jlong saved_string_tag = string_tag;
128
129 jint result = cb->string_primitive_value_callback(class_tag,
130 obj->SizeOf(),
131 &string_tag,
132 data.get(),
133 string_length,
134 const_cast<void*>(user_data));
135 if (string_tag != saved_string_tag) {
136 tag_table->Set(obj.Ptr(), string_tag);
137 }
138
139 return result;
140 }
141 return 0;
142}
143
Andreas Gampebecd6ad2017-02-22 19:20:37 -0800144// Report the contents of a primitive array, if a callback is set.
145jint ReportPrimitiveArray(art::ObjPtr<art::mirror::Object> obj,
146 jvmtiEnv* env,
147 ObjectTagTable* tag_table,
148 const jvmtiHeapCallbacks* cb,
149 const void* user_data) REQUIRES_SHARED(art::Locks::mutator_lock_) {
150 if (UNLIKELY(cb->array_primitive_value_callback != nullptr) &&
151 obj->IsArrayInstance() &&
152 !obj->IsObjectArray()) {
153 art::ObjPtr<art::mirror::Array> array = obj->AsArray();
154 int32_t array_length = array->GetLength();
155 size_t component_size = array->GetClass()->GetComponentSize();
156 art::Primitive::Type art_prim_type = array->GetClass()->GetComponentType()->GetPrimitiveType();
157 jvmtiPrimitiveType prim_type =
158 static_cast<jvmtiPrimitiveType>(art::Primitive::Descriptor(art_prim_type)[0]);
159 DCHECK(prim_type == JVMTI_PRIMITIVE_TYPE_BOOLEAN ||
160 prim_type == JVMTI_PRIMITIVE_TYPE_BYTE ||
161 prim_type == JVMTI_PRIMITIVE_TYPE_CHAR ||
162 prim_type == JVMTI_PRIMITIVE_TYPE_SHORT ||
163 prim_type == JVMTI_PRIMITIVE_TYPE_INT ||
164 prim_type == JVMTI_PRIMITIVE_TYPE_LONG ||
165 prim_type == JVMTI_PRIMITIVE_TYPE_FLOAT ||
166 prim_type == JVMTI_PRIMITIVE_TYPE_DOUBLE);
167
168 const jlong class_tag = tag_table->GetTagOrZero(obj->GetClass());
169 jlong array_tag = tag_table->GetTagOrZero(obj.Ptr());
170 const jlong saved_array_tag = array_tag;
171
172 jint result;
173 if (array_length == 0) {
174 result = cb->array_primitive_value_callback(class_tag,
175 obj->SizeOf(),
176 &array_tag,
177 0,
178 prim_type,
179 nullptr,
180 const_cast<void*>(user_data));
181 } else {
182 jvmtiError alloc_error;
183 JvmtiUniquePtr<char[]> data = AllocJvmtiUniquePtr<char[]>(env,
184 array_length * component_size,
185 &alloc_error);
186 if (data == nullptr) {
187 // TODO: Not really sure what to do here. Should we abort the iteration and go all the way
188 // back? For now just warn.
189 LOG(WARNING) << "Unable to allocate buffer for array reporting! Silently dropping value.";
190 return 0;
191 }
192
193 memcpy(data.get(), array->GetRawData(component_size, 0), array_length * component_size);
194
195 result = cb->array_primitive_value_callback(class_tag,
196 obj->SizeOf(),
197 &array_tag,
198 array_length,
199 prim_type,
200 data.get(),
201 const_cast<void*>(user_data));
202 }
203
204 if (array_tag != saved_array_tag) {
205 tag_table->Set(obj.Ptr(), array_tag);
206 }
207
208 return result;
209 }
210 return 0;
211}
212
Andreas Gampee7316932017-02-25 09:15:05 -0800213template <typename UserData>
214bool VisitorFalse(art::ObjPtr<art::mirror::Object> obj ATTRIBUTE_UNUSED,
215 art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
216 art::ArtField& field ATTRIBUTE_UNUSED,
217 size_t field_index ATTRIBUTE_UNUSED,
218 UserData* user_data ATTRIBUTE_UNUSED) {
219 return false;
220}
221
Andreas Gampe95114602017-02-28 15:47:44 -0800222template <typename UserData, bool kCallVisitorOnRecursion>
Andreas Gampee7316932017-02-25 09:15:05 -0800223class FieldVisitor {
224 public:
225 // Report the contents of a primitive fields of the given object, if a callback is set.
Andreas Gampe95114602017-02-28 15:47:44 -0800226 template <typename StaticPrimitiveVisitor,
227 typename StaticReferenceVisitor,
228 typename InstancePrimitiveVisitor,
229 typename InstanceReferenceVisitor>
Andreas Gampee7316932017-02-25 09:15:05 -0800230 static bool ReportFields(art::ObjPtr<art::mirror::Object> obj,
231 UserData* user_data,
232 StaticPrimitiveVisitor& static_prim_visitor,
233 StaticReferenceVisitor& static_ref_visitor,
234 InstancePrimitiveVisitor& instance_prim_visitor,
235 InstanceReferenceVisitor& instance_ref_visitor)
236 REQUIRES_SHARED(art::Locks::mutator_lock_) {
237 FieldVisitor fv(user_data);
238
239 if (obj->IsClass()) {
240 // When visiting a class, we only visit the static fields of the given class. No field of
241 // superclasses is visited.
242 art::ObjPtr<art::mirror::Class> klass = obj->AsClass();
243 // Only report fields on resolved classes. We need valid field data.
244 if (!klass->IsResolved()) {
245 return false;
246 }
247 return fv.ReportFieldsImpl(nullptr,
248 obj->AsClass(),
249 obj->AsClass()->IsInterface(),
250 static_prim_visitor,
251 static_ref_visitor,
252 instance_prim_visitor,
253 instance_ref_visitor);
254 } else {
255 // See comment above. Just double-checking here, but an instance *should* mean the class was
256 // resolved.
257 DCHECK(obj->GetClass()->IsResolved() || obj->GetClass()->IsErroneousResolved());
258 return fv.ReportFieldsImpl(obj,
259 obj->GetClass(),
260 false,
261 static_prim_visitor,
262 static_ref_visitor,
263 instance_prim_visitor,
264 instance_ref_visitor);
265 }
266 }
267
268 private:
269 explicit FieldVisitor(UserData* user_data) : user_data_(user_data) {}
270
271 // Report the contents of fields of the given object. If obj is null, report the static fields,
272 // otherwise the instance fields.
Andreas Gampe95114602017-02-28 15:47:44 -0800273 template <typename StaticPrimitiveVisitor,
274 typename StaticReferenceVisitor,
275 typename InstancePrimitiveVisitor,
276 typename InstanceReferenceVisitor>
Andreas Gampee7316932017-02-25 09:15:05 -0800277 bool ReportFieldsImpl(art::ObjPtr<art::mirror::Object> obj,
278 art::ObjPtr<art::mirror::Class> klass,
279 bool skip_java_lang_object,
280 StaticPrimitiveVisitor& static_prim_visitor,
281 StaticReferenceVisitor& static_ref_visitor,
282 InstancePrimitiveVisitor& instance_prim_visitor,
283 InstanceReferenceVisitor& instance_ref_visitor)
284 REQUIRES_SHARED(art::Locks::mutator_lock_) {
285 // Compute the offset of field indices.
286 size_t interface_field_count = CountInterfaceFields(klass);
287
288 size_t tmp;
289 bool aborted = ReportFieldsRecursive(obj,
290 klass,
291 interface_field_count,
292 skip_java_lang_object,
293 static_prim_visitor,
294 static_ref_visitor,
295 instance_prim_visitor,
296 instance_ref_visitor,
297 &tmp);
298 return aborted;
299 }
300
301 // Visit primitive fields in an object (instance). Return true if the visit was aborted.
Andreas Gampe95114602017-02-28 15:47:44 -0800302 template <typename StaticPrimitiveVisitor,
303 typename StaticReferenceVisitor,
304 typename InstancePrimitiveVisitor,
305 typename InstanceReferenceVisitor>
Andreas Gampee7316932017-02-25 09:15:05 -0800306 bool ReportFieldsRecursive(art::ObjPtr<art::mirror::Object> obj,
307 art::ObjPtr<art::mirror::Class> klass,
308 size_t interface_fields,
309 bool skip_java_lang_object,
310 StaticPrimitiveVisitor& static_prim_visitor,
311 StaticReferenceVisitor& static_ref_visitor,
312 InstancePrimitiveVisitor& instance_prim_visitor,
313 InstanceReferenceVisitor& instance_ref_visitor,
314 size_t* field_index_out)
315 REQUIRES_SHARED(art::Locks::mutator_lock_) {
316 DCHECK(klass != nullptr);
317 size_t field_index;
318 if (klass->GetSuperClass() == nullptr) {
319 // j.l.Object. Start with the fields from interfaces.
320 field_index = interface_fields;
321 if (skip_java_lang_object) {
322 *field_index_out = field_index;
323 return false;
324 }
325 } else {
326 // Report superclass fields.
327 if (kCallVisitorOnRecursion) {
328 if (ReportFieldsRecursive(obj,
329 klass->GetSuperClass(),
330 interface_fields,
331 skip_java_lang_object,
332 static_prim_visitor,
333 static_ref_visitor,
334 instance_prim_visitor,
335 instance_ref_visitor,
336 &field_index)) {
337 return true;
338 }
339 } else {
340 // Still call, but with empty visitor. This is required for correct counting.
341 ReportFieldsRecursive(obj,
342 klass->GetSuperClass(),
343 interface_fields,
344 skip_java_lang_object,
345 VisitorFalse<UserData>,
346 VisitorFalse<UserData>,
347 VisitorFalse<UserData>,
348 VisitorFalse<UserData>,
349 &field_index);
350 }
351 }
352
353 // Now visit fields for the current klass.
354
355 for (auto& static_field : klass->GetSFields()) {
356 if (static_field.IsPrimitiveType()) {
357 if (static_prim_visitor(obj,
358 klass,
359 static_field,
360 field_index,
361 user_data_)) {
362 return true;
363 }
364 } else {
365 if (static_ref_visitor(obj,
366 klass,
367 static_field,
368 field_index,
369 user_data_)) {
370 return true;
371 }
372 }
373 field_index++;
374 }
375
376 for (auto& instance_field : klass->GetIFields()) {
377 if (instance_field.IsPrimitiveType()) {
378 if (instance_prim_visitor(obj,
379 klass,
380 instance_field,
381 field_index,
382 user_data_)) {
383 return true;
384 }
385 } else {
386 if (instance_ref_visitor(obj,
387 klass,
388 instance_field,
389 field_index,
390 user_data_)) {
391 return true;
392 }
393 }
394 field_index++;
395 }
396
397 *field_index_out = field_index;
398 return false;
399 }
400
401 // Implements a visit of the implemented interfaces of a given class.
402 template <typename T>
403 struct RecursiveInterfaceVisit {
404 static void VisitStatic(art::Thread* self, art::ObjPtr<art::mirror::Class> klass, T& visitor)
405 REQUIRES_SHARED(art::Locks::mutator_lock_) {
406 RecursiveInterfaceVisit rv;
407 rv.Visit(self, klass, visitor);
408 }
409
410 void Visit(art::Thread* self, art::ObjPtr<art::mirror::Class> klass, T& visitor)
411 REQUIRES_SHARED(art::Locks::mutator_lock_) {
412 // First visit the parent, to get the order right.
413 // (We do this in preparation for actual visiting of interface fields.)
414 if (klass->GetSuperClass() != nullptr) {
415 Visit(self, klass->GetSuperClass(), visitor);
416 }
417 for (uint32_t i = 0; i != klass->NumDirectInterfaces(); ++i) {
Vladimir Markob10668c2021-06-10 09:52:53 +0100418 art::ObjPtr<art::mirror::Class> inf_klass = klass->GetDirectInterface(i);
Andreas Gampee7316932017-02-25 09:15:05 -0800419 DCHECK(inf_klass != nullptr);
420 VisitInterface(self, inf_klass, visitor);
421 }
422 }
423
424 void VisitInterface(art::Thread* self, art::ObjPtr<art::mirror::Class> inf_klass, T& visitor)
425 REQUIRES_SHARED(art::Locks::mutator_lock_) {
426 auto it = visited_interfaces.find(inf_klass.Ptr());
427 if (it != visited_interfaces.end()) {
428 return;
429 }
430 visited_interfaces.insert(inf_klass.Ptr());
431
432 // Let the visitor know about this one. Note that this order is acceptable, as the ordering
433 // of these fields never matters for known visitors.
434 visitor(inf_klass);
435
436 // Now visit the superinterfaces.
437 for (uint32_t i = 0; i != inf_klass->NumDirectInterfaces(); ++i) {
Vladimir Markob10668c2021-06-10 09:52:53 +0100438 art::ObjPtr<art::mirror::Class> super_inf_klass = inf_klass->GetDirectInterface(i);
Andreas Gampee7316932017-02-25 09:15:05 -0800439 DCHECK(super_inf_klass != nullptr);
440 VisitInterface(self, super_inf_klass, visitor);
441 }
442 }
443
444 std::unordered_set<art::mirror::Class*> visited_interfaces;
445 };
446
447 // Counting interface fields. Note that we cannot use the interface table, as that only contains
448 // "non-marker" interfaces (= interfaces with methods).
449 static size_t CountInterfaceFields(art::ObjPtr<art::mirror::Class> klass)
450 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe9e38a502017-03-06 08:19:26 -0800451 // Do we have a cached value?
452 IndexCache tmp;
453 if (gIndexCachingTable.GetTag(klass.Ptr(), &tmp)) {
454 return tmp.interface_fields;
455 }
456
Andreas Gampee7316932017-02-25 09:15:05 -0800457 size_t count = 0;
458 auto visitor = [&count](art::ObjPtr<art::mirror::Class> inf_klass)
459 REQUIRES_SHARED(art::Locks::mutator_lock_) {
460 DCHECK(inf_klass->IsInterface());
461 DCHECK_EQ(0u, inf_klass->NumInstanceFields());
462 count += inf_klass->NumStaticFields();
463 };
464 RecursiveInterfaceVisit<decltype(visitor)>::VisitStatic(art::Thread::Current(), klass, visitor);
Andreas Gampee7316932017-02-25 09:15:05 -0800465
Andreas Gampe9e38a502017-03-06 08:19:26 -0800466 // Store this into the cache.
467 tmp.interface_fields = count;
468 gIndexCachingTable.Set(klass.Ptr(), tmp);
469
470 return count;
Andreas Gampee7316932017-02-25 09:15:05 -0800471 }
472
473 UserData* user_data_;
474};
475
476// Debug helper. Prints the structure of an object.
477template <bool kStatic, bool kRef>
478struct DumpVisitor {
479 static bool Callback(art::ObjPtr<art::mirror::Object> obj ATTRIBUTE_UNUSED,
480 art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
481 art::ArtField& field,
482 size_t field_index,
483 void* user_data ATTRIBUTE_UNUSED)
484 REQUIRES_SHARED(art::Locks::mutator_lock_) {
485 LOG(ERROR) << (kStatic ? "static " : "instance ")
486 << (kRef ? "ref " : "primitive ")
487 << field.PrettyField()
488 << " @ "
489 << field_index;
490 return false;
491 }
492};
493ATTRIBUTE_UNUSED
494void DumpObjectFields(art::ObjPtr<art::mirror::Object> obj)
495 REQUIRES_SHARED(art::Locks::mutator_lock_) {
496 if (obj->IsClass()) {
Andreas Gampe95114602017-02-28 15:47:44 -0800497 FieldVisitor<void, false>:: ReportFields(obj,
498 nullptr,
499 DumpVisitor<true, false>::Callback,
500 DumpVisitor<true, true>::Callback,
501 DumpVisitor<false, false>::Callback,
502 DumpVisitor<false, true>::Callback);
Andreas Gampee7316932017-02-25 09:15:05 -0800503 } else {
Andreas Gampe95114602017-02-28 15:47:44 -0800504 FieldVisitor<void, true>::ReportFields(obj,
505 nullptr,
506 DumpVisitor<true, false>::Callback,
507 DumpVisitor<true, true>::Callback,
508 DumpVisitor<false, false>::Callback,
509 DumpVisitor<false, true>::Callback);
Andreas Gampee7316932017-02-25 09:15:05 -0800510 }
511}
512
513class ReportPrimitiveField {
514 public:
515 static bool Report(art::ObjPtr<art::mirror::Object> obj,
516 ObjectTagTable* tag_table,
517 const jvmtiHeapCallbacks* cb,
518 const void* user_data)
519 REQUIRES_SHARED(art::Locks::mutator_lock_) {
520 if (UNLIKELY(cb->primitive_field_callback != nullptr)) {
521 jlong class_tag = tag_table->GetTagOrZero(obj->GetClass());
522 ReportPrimitiveField rpf(tag_table, class_tag, cb, user_data);
523 if (obj->IsClass()) {
Andreas Gampe95114602017-02-28 15:47:44 -0800524 return FieldVisitor<ReportPrimitiveField, false>::ReportFields(
525 obj,
526 &rpf,
527 ReportPrimitiveFieldCallback<true>,
528 VisitorFalse<ReportPrimitiveField>,
529 VisitorFalse<ReportPrimitiveField>,
530 VisitorFalse<ReportPrimitiveField>);
Andreas Gampee7316932017-02-25 09:15:05 -0800531 } else {
Andreas Gampe95114602017-02-28 15:47:44 -0800532 return FieldVisitor<ReportPrimitiveField, true>::ReportFields(
533 obj,
534 &rpf,
535 VisitorFalse<ReportPrimitiveField>,
536 VisitorFalse<ReportPrimitiveField>,
537 ReportPrimitiveFieldCallback<false>,
538 VisitorFalse<ReportPrimitiveField>);
Andreas Gampee7316932017-02-25 09:15:05 -0800539 }
540 }
541 return false;
542 }
543
544
545 private:
546 ReportPrimitiveField(ObjectTagTable* tag_table,
547 jlong class_tag,
548 const jvmtiHeapCallbacks* cb,
549 const void* user_data)
550 : tag_table_(tag_table), class_tag_(class_tag), cb_(cb), user_data_(user_data) {}
551
552 template <bool kReportStatic>
553 static bool ReportPrimitiveFieldCallback(art::ObjPtr<art::mirror::Object> obj,
554 art::ObjPtr<art::mirror::Class> klass,
555 art::ArtField& field,
556 size_t field_index,
557 ReportPrimitiveField* user_data)
558 REQUIRES_SHARED(art::Locks::mutator_lock_) {
559 art::Primitive::Type art_prim_type = field.GetTypeAsPrimitiveType();
560 jvmtiPrimitiveType prim_type =
561 static_cast<jvmtiPrimitiveType>(art::Primitive::Descriptor(art_prim_type)[0]);
562 DCHECK(prim_type == JVMTI_PRIMITIVE_TYPE_BOOLEAN ||
563 prim_type == JVMTI_PRIMITIVE_TYPE_BYTE ||
564 prim_type == JVMTI_PRIMITIVE_TYPE_CHAR ||
565 prim_type == JVMTI_PRIMITIVE_TYPE_SHORT ||
566 prim_type == JVMTI_PRIMITIVE_TYPE_INT ||
567 prim_type == JVMTI_PRIMITIVE_TYPE_LONG ||
568 prim_type == JVMTI_PRIMITIVE_TYPE_FLOAT ||
569 prim_type == JVMTI_PRIMITIVE_TYPE_DOUBLE);
570 jvmtiHeapReferenceInfo info;
571 info.field.index = field_index;
572
573 jvalue value;
574 memset(&value, 0, sizeof(jvalue));
575 art::ObjPtr<art::mirror::Object> src = kReportStatic ? klass : obj;
576 switch (art_prim_type) {
577 case art::Primitive::Type::kPrimBoolean:
578 value.z = field.GetBoolean(src) == 0 ? JNI_FALSE : JNI_TRUE;
579 break;
580 case art::Primitive::Type::kPrimByte:
581 value.b = field.GetByte(src);
582 break;
583 case art::Primitive::Type::kPrimChar:
584 value.c = field.GetChar(src);
585 break;
586 case art::Primitive::Type::kPrimShort:
587 value.s = field.GetShort(src);
588 break;
589 case art::Primitive::Type::kPrimInt:
590 value.i = field.GetInt(src);
591 break;
592 case art::Primitive::Type::kPrimLong:
593 value.j = field.GetLong(src);
594 break;
595 case art::Primitive::Type::kPrimFloat:
596 value.f = field.GetFloat(src);
597 break;
598 case art::Primitive::Type::kPrimDouble:
599 value.d = field.GetDouble(src);
600 break;
601 case art::Primitive::Type::kPrimVoid:
602 case art::Primitive::Type::kPrimNot: {
603 LOG(FATAL) << "Should not reach here";
604 UNREACHABLE();
605 }
606 }
607
608 jlong obj_tag = user_data->tag_table_->GetTagOrZero(src.Ptr());
609 const jlong saved_obj_tag = obj_tag;
610
611 jint ret = user_data->cb_->primitive_field_callback(kReportStatic
612 ? JVMTI_HEAP_REFERENCE_STATIC_FIELD
613 : JVMTI_HEAP_REFERENCE_FIELD,
614 &info,
615 user_data->class_tag_,
616 &obj_tag,
617 value,
618 prim_type,
619 const_cast<void*>(user_data->user_data_));
620
621 if (saved_obj_tag != obj_tag) {
622 user_data->tag_table_->Set(src.Ptr(), obj_tag);
623 }
624
625 if ((ret & JVMTI_VISIT_ABORT) != 0) {
626 return true;
627 }
628
629 return false;
630 }
631
632 ObjectTagTable* tag_table_;
633 jlong class_tag_;
634 const jvmtiHeapCallbacks* cb_;
635 const void* user_data_;
636};
637
Andreas Gampe6ea06072017-02-24 18:01:19 +0000638struct HeapFilter {
639 explicit HeapFilter(jint heap_filter)
640 : filter_out_tagged((heap_filter & JVMTI_HEAP_FILTER_TAGGED) != 0),
Andreas Gampee54d9922016-10-11 19:55:37 -0700641 filter_out_untagged((heap_filter & JVMTI_HEAP_FILTER_UNTAGGED) != 0),
642 filter_out_class_tagged((heap_filter & JVMTI_HEAP_FILTER_CLASS_TAGGED) != 0),
643 filter_out_class_untagged((heap_filter & JVMTI_HEAP_FILTER_CLASS_UNTAGGED) != 0),
644 any_filter(filter_out_tagged ||
645 filter_out_untagged ||
646 filter_out_class_tagged ||
Andreas Gampe6ea06072017-02-24 18:01:19 +0000647 filter_out_class_untagged) {
Andreas Gampee54d9922016-10-11 19:55:37 -0700648 }
649
Andreas Gampe6ea06072017-02-24 18:01:19 +0000650 bool ShouldReportByHeapFilter(jlong tag, jlong class_tag) const {
Andreas Gampee54d9922016-10-11 19:55:37 -0700651 if (!any_filter) {
652 return true;
653 }
654
655 if ((tag == 0 && filter_out_untagged) || (tag != 0 && filter_out_tagged)) {
656 return false;
657 }
658
659 if ((class_tag == 0 && filter_out_class_untagged) ||
660 (class_tag != 0 && filter_out_class_tagged)) {
661 return false;
662 }
663
664 return true;
665 }
666
Andreas Gampee54d9922016-10-11 19:55:37 -0700667 const bool filter_out_tagged;
668 const bool filter_out_untagged;
669 const bool filter_out_class_tagged;
670 const bool filter_out_class_untagged;
671 const bool any_filter;
Andreas Gampe6ea06072017-02-24 18:01:19 +0000672};
673
674} // namespace
675
Andreas Gampe9e38a502017-03-06 08:19:26 -0800676void HeapUtil::Register() {
677 art::Runtime::Current()->AddSystemWeakHolder(&gIndexCachingTable);
678}
679
680void HeapUtil::Unregister() {
681 art::Runtime::Current()->RemoveSystemWeakHolder(&gIndexCachingTable);
682}
683
Alex Lightbbbcb532018-08-30 12:50:27 -0700684jvmtiError HeapUtil::IterateOverInstancesOfClass(jvmtiEnv* env,
685 jclass klass,
686 jvmtiHeapObjectFilter filter,
687 jvmtiHeapObjectCallback cb,
688 const void* user_data) {
689 if (cb == nullptr || klass == nullptr) {
690 return ERR(NULL_POINTER);
691 }
692
693 art::Thread* self = art::Thread::Current();
694 art::ScopedObjectAccess soa(self); // Now we know we have the shared lock.
695 art::StackHandleScope<1> hs(self);
696
697 art::ObjPtr<art::mirror::Object> klass_ptr(soa.Decode<art::mirror::Class>(klass));
698 if (!klass_ptr->IsClass()) {
699 return ERR(INVALID_CLASS);
700 }
701 art::Handle<art::mirror::Class> filter_klass(hs.NewHandle(klass_ptr->AsClass()));
Alex Lightbbbcb532018-08-30 12:50:27 -0700702 ObjectTagTable* tag_table = ArtJvmTiEnv::AsArtJvmTiEnv(env)->object_tag_table.get();
703 bool stop_reports = false;
704 auto visitor = [&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
705 // Early return, as we can't really stop visiting.
706 if (stop_reports) {
707 return;
708 }
709
710 art::ScopedAssertNoThreadSuspension no_suspension("IterateOverInstancesOfClass");
711
712 art::ObjPtr<art::mirror::Class> klass = obj->GetClass();
713
714 if (filter_klass != nullptr && !filter_klass->IsAssignableFrom(klass)) {
715 return;
716 }
717
718 jlong tag = 0;
719 tag_table->GetTag(obj, &tag);
720 if ((filter != JVMTI_HEAP_OBJECT_EITHER) &&
721 ((tag == 0 && filter == JVMTI_HEAP_OBJECT_TAGGED) ||
722 (tag != 0 && filter == JVMTI_HEAP_OBJECT_UNTAGGED))) {
723 return;
724 }
725
726 jlong class_tag = 0;
727 tag_table->GetTag(klass.Ptr(), &class_tag);
728
729 jlong saved_tag = tag;
730 jint ret = cb(class_tag, obj->SizeOf(), &tag, const_cast<void*>(user_data));
731
732 stop_reports = (ret == JVMTI_ITERATION_ABORT);
733
734 if (tag != saved_tag) {
735 tag_table->Set(obj, tag);
736 }
737 };
738 art::Runtime::Current()->GetHeap()->VisitObjects(visitor);
739
740 return OK;
741}
742
Andreas Gampe1c158a02017-07-13 17:26:19 -0700743template <typename T>
744static jvmtiError DoIterateThroughHeap(T fn,
745 jvmtiEnv* env,
746 ObjectTagTable* tag_table,
747 jint heap_filter_int,
748 jclass klass,
749 const jvmtiHeapCallbacks* callbacks,
750 const void* user_data) {
751 if (callbacks == nullptr) {
752 return ERR(NULL_POINTER);
Andreas Gampe6ea06072017-02-24 18:01:19 +0000753 }
754
Andreas Gampe1c158a02017-07-13 17:26:19 -0700755 art::Thread* self = art::Thread::Current();
756 art::ScopedObjectAccess soa(self); // Now we know we have the shared lock.
Andreas Gampef787fd32017-05-09 16:04:20 -0700757
Andreas Gampe1c158a02017-07-13 17:26:19 -0700758 bool stop_reports = false;
759 const HeapFilter heap_filter(heap_filter_int);
Alex Lightc06e07f2020-07-17 18:13:17 -0700760 art::StackHandleScope<1> hs(self);
761 art::Handle<art::mirror::Class> filter_klass(hs.NewHandle(soa.Decode<art::mirror::Class>(klass)));
Andreas Gampe1c158a02017-07-13 17:26:19 -0700762 auto visitor = [&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampef787fd32017-05-09 16:04:20 -0700763 // Early return, as we can't really stop visiting.
764 if (stop_reports) {
765 return;
766 }
767
768 art::ScopedAssertNoThreadSuspension no_suspension("IterateThroughHeapCallback");
769
770 jlong tag = 0;
771 tag_table->GetTag(obj, &tag);
772
773 jlong class_tag = 0;
774 art::ObjPtr<art::mirror::Class> klass = obj->GetClass();
775 tag_table->GetTag(klass.Ptr(), &class_tag);
776 // For simplicity, even if we find a tag = 0, assume 0 = not tagged.
777
778 if (!heap_filter.ShouldReportByHeapFilter(tag, class_tag)) {
779 return;
780 }
781
782 if (filter_klass != nullptr) {
Alex Lightc06e07f2020-07-17 18:13:17 -0700783 if (filter_klass.Get() != klass) {
Andreas Gampef787fd32017-05-09 16:04:20 -0700784 return;
785 }
786 }
787
788 jlong size = obj->SizeOf();
789
790 jint length = -1;
791 if (obj->IsArrayInstance()) {
792 length = obj->AsArray()->GetLength();
793 }
794
795 jlong saved_tag = tag;
Andreas Gampe1c158a02017-07-13 17:26:19 -0700796 jint ret = fn(obj, callbacks, class_tag, size, &tag, length, const_cast<void*>(user_data));
Andreas Gampef787fd32017-05-09 16:04:20 -0700797
798 if (tag != saved_tag) {
799 tag_table->Set(obj, tag);
800 }
801
802 stop_reports = (ret & JVMTI_VISIT_ABORT) != 0;
803
804 if (!stop_reports) {
805 jint string_ret = ReportString(obj, env, tag_table, callbacks, user_data);
806 stop_reports = (string_ret & JVMTI_VISIT_ABORT) != 0;
807 }
808
809 if (!stop_reports) {
810 jint array_ret = ReportPrimitiveArray(obj, env, tag_table, callbacks, user_data);
811 stop_reports = (array_ret & JVMTI_VISIT_ABORT) != 0;
812 }
813
814 if (!stop_reports) {
815 stop_reports = ReportPrimitiveField::Report(obj, tag_table, callbacks, user_data);
816 }
Andreas Gampe1c158a02017-07-13 17:26:19 -0700817 };
818 art::Runtime::Current()->GetHeap()->VisitObjects(visitor);
Andreas Gampee54d9922016-10-11 19:55:37 -0700819
820 return ERR(NONE);
821}
822
Andreas Gampef787fd32017-05-09 16:04:20 -0700823jvmtiError HeapUtil::IterateThroughHeap(jvmtiEnv* env,
824 jint heap_filter,
825 jclass klass,
826 const jvmtiHeapCallbacks* callbacks,
827 const void* user_data) {
828 auto JvmtiIterateHeap = [](art::mirror::Object* obj ATTRIBUTE_UNUSED,
829 const jvmtiHeapCallbacks* cb_callbacks,
830 jlong class_tag,
831 jlong size,
832 jlong* tag,
833 jint length,
834 void* cb_user_data)
835 REQUIRES_SHARED(art::Locks::mutator_lock_) {
836 return cb_callbacks->heap_iteration_callback(class_tag,
837 size,
838 tag,
839 length,
840 cb_user_data);
841 };
842 return DoIterateThroughHeap(JvmtiIterateHeap,
843 env,
844 ArtJvmTiEnv::AsArtJvmTiEnv(env)->object_tag_table.get(),
845 heap_filter,
846 klass,
847 callbacks,
848 user_data);
849}
850
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100851class FollowReferencesHelper final {
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700852 public:
853 FollowReferencesHelper(HeapUtil* h,
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800854 jvmtiEnv* jvmti_env,
Andreas Gampe638a6932016-12-02 19:11:17 -0800855 art::ObjPtr<art::mirror::Object> initial_object,
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700856 const jvmtiHeapCallbacks* callbacks,
Andreas Gampe38da9f22017-02-20 13:35:36 -0800857 art::ObjPtr<art::mirror::Class> class_filter,
Andreas Gampe6ea06072017-02-24 18:01:19 +0000858 jint heap_filter,
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700859 const void* user_data)
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800860 : env(jvmti_env),
861 tag_table_(h->GetTags()),
Andreas Gampe638a6932016-12-02 19:11:17 -0800862 initial_object_(initial_object),
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700863 callbacks_(callbacks),
Andreas Gampe38da9f22017-02-20 13:35:36 -0800864 class_filter_(class_filter),
Andreas Gampe6ea06072017-02-24 18:01:19 +0000865 heap_filter_(heap_filter),
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700866 user_data_(user_data),
867 start_(0),
868 stop_reports_(false) {
869 }
870
871 void Init()
872 REQUIRES_SHARED(art::Locks::mutator_lock_)
873 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
Andreas Gampe638a6932016-12-02 19:11:17 -0800874 if (initial_object_.IsNull()) {
875 CollectAndReportRootsVisitor carrv(this, tag_table_, &worklist_, &visited_);
Andreas Gampef10dfcd2016-12-02 14:42:33 -0800876
877 // We need precise info (e.g., vregs).
878 constexpr art::VisitRootFlags kRootFlags = static_cast<art::VisitRootFlags>(
879 art::VisitRootFlags::kVisitRootFlagAllRoots | art::VisitRootFlags::kVisitRootFlagPrecise);
880 art::Runtime::Current()->VisitRoots(&carrv, kRootFlags);
881
Andreas Gampe638a6932016-12-02 19:11:17 -0800882 art::Runtime::Current()->VisitImageRoots(&carrv);
883 stop_reports_ = carrv.IsStopReports();
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700884
Andreas Gampe638a6932016-12-02 19:11:17 -0800885 if (stop_reports_) {
886 worklist_.clear();
887 }
888 } else {
889 visited_.insert(initial_object_.Ptr());
890 worklist_.push_back(initial_object_.Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700891 }
892 }
893
894 void Work()
895 REQUIRES_SHARED(art::Locks::mutator_lock_)
896 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
897 // Currently implemented as a BFS. To lower overhead, we don't erase elements immediately
898 // from the head of the work list, instead postponing until there's a gap that's "large."
899 //
900 // Alternatively, we can implement a DFS and use the work list as a stack.
901 while (start_ < worklist_.size()) {
902 art::mirror::Object* cur_obj = worklist_[start_];
903 start_++;
904
905 if (start_ >= kMaxStart) {
906 worklist_.erase(worklist_.begin(), worklist_.begin() + start_);
907 start_ = 0;
908 }
909
910 VisitObject(cur_obj);
911
912 if (stop_reports_) {
913 break;
914 }
915 }
916 }
917
918 private:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100919 class CollectAndReportRootsVisitor final : public art::RootVisitor {
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700920 public:
921 CollectAndReportRootsVisitor(FollowReferencesHelper* helper,
922 ObjectTagTable* tag_table,
923 std::vector<art::mirror::Object*>* worklist,
924 std::unordered_set<art::mirror::Object*>* visited)
925 : helper_(helper),
926 tag_table_(tag_table),
927 worklist_(worklist),
928 visited_(visited),
929 stop_reports_(false) {}
930
931 void VisitRoots(art::mirror::Object*** roots, size_t count, const art::RootInfo& info)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100932 override
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700933 REQUIRES_SHARED(art::Locks::mutator_lock_)
934 REQUIRES(!*helper_->tag_table_->GetAllowDisallowLock()) {
935 for (size_t i = 0; i != count; ++i) {
936 AddRoot(*roots[i], info);
937 }
938 }
939
940 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
941 size_t count,
942 const art::RootInfo& info)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100943 override REQUIRES_SHARED(art::Locks::mutator_lock_)
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700944 REQUIRES(!*helper_->tag_table_->GetAllowDisallowLock()) {
945 for (size_t i = 0; i != count; ++i) {
946 AddRoot(roots[i]->AsMirrorPtr(), info);
947 }
948 }
949
950 bool IsStopReports() {
951 return stop_reports_;
952 }
953
954 private:
955 void AddRoot(art::mirror::Object* root_obj, const art::RootInfo& info)
956 REQUIRES_SHARED(art::Locks::mutator_lock_)
957 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
Andreas Gampec756f082017-03-29 17:58:28 -0700958 if (stop_reports_) {
959 return;
960 }
961 bool add_to_worklist = ReportRoot(root_obj, info);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700962 // We use visited_ to mark roots already so we do not need another set.
963 if (visited_->find(root_obj) == visited_->end()) {
Andreas Gampec756f082017-03-29 17:58:28 -0700964 if (add_to_worklist) {
Andreas Gampee0f8ed92017-04-13 16:52:23 -0700965 visited_->insert(root_obj);
Andreas Gampec756f082017-03-29 17:58:28 -0700966 worklist_->push_back(root_obj);
967 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700968 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700969 }
970
Andreas Gampe93c30902016-11-18 13:30:30 -0800971 // Remove NO_THREAD_SAFETY_ANALYSIS once ASSERT_CAPABILITY works correctly.
972 art::Thread* FindThread(const art::RootInfo& info) NO_THREAD_SAFETY_ANALYSIS {
973 art::Locks::thread_list_lock_->AssertExclusiveHeld(art::Thread::Current());
974 return art::Runtime::Current()->GetThreadList()->FindThreadByThreadId(info.GetThreadId());
975 }
976
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700977 jvmtiHeapReferenceKind GetReferenceKind(const art::RootInfo& info,
978 jvmtiHeapReferenceInfo* ref_info)
979 REQUIRES_SHARED(art::Locks::mutator_lock_) {
980 // TODO: Fill in ref_info.
981 memset(ref_info, 0, sizeof(jvmtiHeapReferenceInfo));
982
983 switch (info.GetType()) {
984 case art::RootType::kRootJNIGlobal:
985 return JVMTI_HEAP_REFERENCE_JNI_GLOBAL;
986
987 case art::RootType::kRootJNILocal:
Andreas Gampe93c30902016-11-18 13:30:30 -0800988 {
989 uint32_t thread_id = info.GetThreadId();
990 ref_info->jni_local.thread_id = thread_id;
991
992 art::Thread* thread = FindThread(info);
993 if (thread != nullptr) {
Andreas Gampe202f85a2017-02-06 10:23:26 -0800994 art::mirror::Object* thread_obj;
Andreas Gampe93c30902016-11-18 13:30:30 -0800995 if (thread->IsStillStarting()) {
996 thread_obj = nullptr;
997 } else {
Andreas Gampe202f85a2017-02-06 10:23:26 -0800998 thread_obj = thread->GetPeerFromOtherThread();
Andreas Gampe93c30902016-11-18 13:30:30 -0800999 }
1000 if (thread_obj != nullptr) {
1001 ref_info->jni_local.thread_tag = tag_table_->GetTagOrZero(thread_obj);
1002 }
1003 }
1004
1005 // TODO: We don't have this info.
1006 if (thread != nullptr) {
1007 ref_info->jni_local.depth = 0;
Andreas Gampe6e897762018-10-16 13:09:32 -07001008 art::ArtMethod* method = thread->GetCurrentMethod(nullptr,
1009 /* check_suspended= */ true,
1010 /* abort_on_error= */ false);
Andreas Gampe93c30902016-11-18 13:30:30 -08001011 if (method != nullptr) {
1012 ref_info->jni_local.method = art::jni::EncodeArtMethod(method);
1013 }
1014 }
1015
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001016 return JVMTI_HEAP_REFERENCE_JNI_LOCAL;
Andreas Gampe93c30902016-11-18 13:30:30 -08001017 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001018
1019 case art::RootType::kRootJavaFrame:
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001020 {
1021 uint32_t thread_id = info.GetThreadId();
1022 ref_info->stack_local.thread_id = thread_id;
1023
1024 art::Thread* thread = FindThread(info);
1025 if (thread != nullptr) {
Andreas Gampe202f85a2017-02-06 10:23:26 -08001026 art::mirror::Object* thread_obj;
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001027 if (thread->IsStillStarting()) {
1028 thread_obj = nullptr;
1029 } else {
Andreas Gampe202f85a2017-02-06 10:23:26 -08001030 thread_obj = thread->GetPeerFromOtherThread();
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001031 }
1032 if (thread_obj != nullptr) {
1033 ref_info->stack_local.thread_tag = tag_table_->GetTagOrZero(thread_obj);
1034 }
1035 }
1036
1037 auto& java_info = static_cast<const art::JavaFrameRootInfo&>(info);
Alex Light0054aa52019-09-10 16:46:48 -07001038 size_t vreg = java_info.GetVReg();
1039 ref_info->stack_local.slot = static_cast<jint>(
1040 vreg <= art::JavaFrameRootInfo::kMaxVReg ? vreg : -1);
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001041 const art::StackVisitor* visitor = java_info.GetVisitor();
1042 ref_info->stack_local.location =
Andreas Gampe6e897762018-10-16 13:09:32 -07001043 static_cast<jlocation>(visitor->GetDexPc(/* abort_on_failure= */ false));
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001044 ref_info->stack_local.depth = static_cast<jint>(visitor->GetFrameDepth());
1045 art::ArtMethod* method = visitor->GetMethod();
1046 if (method != nullptr) {
1047 ref_info->stack_local.method = art::jni::EncodeArtMethod(method);
1048 }
1049
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001050 return JVMTI_HEAP_REFERENCE_STACK_LOCAL;
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001051 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001052
1053 case art::RootType::kRootNativeStack:
1054 case art::RootType::kRootThreadBlock:
1055 case art::RootType::kRootThreadObject:
1056 return JVMTI_HEAP_REFERENCE_THREAD;
1057
1058 case art::RootType::kRootStickyClass:
1059 case art::RootType::kRootInternedString:
1060 // Note: this isn't a root in the RI.
1061 return JVMTI_HEAP_REFERENCE_SYSTEM_CLASS;
1062
1063 case art::RootType::kRootMonitorUsed:
1064 case art::RootType::kRootJNIMonitor:
1065 return JVMTI_HEAP_REFERENCE_MONITOR;
1066
1067 case art::RootType::kRootFinalizing:
1068 case art::RootType::kRootDebugger:
1069 case art::RootType::kRootReferenceCleanup:
1070 case art::RootType::kRootVMInternal:
1071 case art::RootType::kRootUnknown:
1072 return JVMTI_HEAP_REFERENCE_OTHER;
1073 }
1074 LOG(FATAL) << "Unreachable";
1075 UNREACHABLE();
1076 }
1077
Andreas Gampec756f082017-03-29 17:58:28 -07001078 bool ReportRoot(art::mirror::Object* root_obj, const art::RootInfo& info)
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001079 REQUIRES_SHARED(art::Locks::mutator_lock_)
1080 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1081 jvmtiHeapReferenceInfo ref_info;
1082 jvmtiHeapReferenceKind kind = GetReferenceKind(info, &ref_info);
1083 jint result = helper_->ReportReference(kind, &ref_info, nullptr, root_obj);
1084 if ((result & JVMTI_VISIT_ABORT) != 0) {
1085 stop_reports_ = true;
1086 }
Andreas Gampec756f082017-03-29 17:58:28 -07001087 return (result & JVMTI_VISIT_OBJECTS) != 0;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001088 }
1089
1090 private:
1091 FollowReferencesHelper* helper_;
1092 ObjectTagTable* tag_table_;
1093 std::vector<art::mirror::Object*>* worklist_;
1094 std::unordered_set<art::mirror::Object*>* visited_;
1095 bool stop_reports_;
1096 };
1097
1098 void VisitObject(art::mirror::Object* obj)
1099 REQUIRES_SHARED(art::Locks::mutator_lock_)
1100 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1101 if (obj->IsClass()) {
Vladimir Marko4617d582019-03-28 13:48:31 +00001102 VisitClass(obj->AsClass().Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001103 return;
1104 }
1105 if (obj->IsArrayInstance()) {
1106 VisitArray(obj);
1107 return;
1108 }
1109
Andreas Gampe95114602017-02-28 15:47:44 -08001110 // All instance fields.
1111 auto report_instance_field = [&](art::ObjPtr<art::mirror::Object> src,
1112 art::ObjPtr<art::mirror::Class> obj_klass ATTRIBUTE_UNUSED,
1113 art::ArtField& field,
1114 size_t field_index,
1115 void* user_data ATTRIBUTE_UNUSED)
1116 REQUIRES_SHARED(art::Locks::mutator_lock_)
1117 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1118 art::ObjPtr<art::mirror::Object> field_value = field.GetObject(src);
1119 if (field_value != nullptr) {
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001120 jvmtiHeapReferenceInfo reference_info;
1121 memset(&reference_info, 0, sizeof(reference_info));
1122
Andreas Gampe95114602017-02-28 15:47:44 -08001123 reference_info.field.index = field_index;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001124
1125 jvmtiHeapReferenceKind kind =
Andreas Gampe95114602017-02-28 15:47:44 -08001126 field.GetOffset().Int32Value() == art::mirror::Object::ClassOffset().Int32Value()
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001127 ? JVMTI_HEAP_REFERENCE_CLASS
1128 : JVMTI_HEAP_REFERENCE_FIELD;
1129 const jvmtiHeapReferenceInfo* reference_info_ptr =
1130 kind == JVMTI_HEAP_REFERENCE_CLASS ? nullptr : &reference_info;
1131
Andreas Gampe95114602017-02-28 15:47:44 -08001132 return !ReportReferenceMaybeEnqueue(kind, reference_info_ptr, src.Ptr(), field_value.Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001133 }
Andreas Gampe95114602017-02-28 15:47:44 -08001134 return false;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001135 };
Andreas Gampe95114602017-02-28 15:47:44 -08001136 stop_reports_ = FieldVisitor<void, true>::ReportFields(obj,
1137 nullptr,
1138 VisitorFalse<void>,
1139 VisitorFalse<void>,
1140 VisitorFalse<void>,
1141 report_instance_field);
1142 if (stop_reports_) {
1143 return;
Andreas Gampe3ec8e402017-02-21 15:49:53 -08001144 }
Andreas Gampee7316932017-02-25 09:15:05 -08001145
Andreas Gampe95114602017-02-28 15:47:44 -08001146 jint string_ret = ReportString(obj, env, tag_table_, callbacks_, user_data_);
1147 stop_reports_ = (string_ret & JVMTI_VISIT_ABORT) != 0;
1148 if (stop_reports_) {
1149 return;
Andreas Gampee7316932017-02-25 09:15:05 -08001150 }
Andreas Gampe95114602017-02-28 15:47:44 -08001151
1152 stop_reports_ = ReportPrimitiveField::Report(obj, tag_table_, callbacks_, user_data_);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001153 }
1154
1155 void VisitArray(art::mirror::Object* array)
1156 REQUIRES_SHARED(art::Locks::mutator_lock_)
1157 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1158 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_CLASS,
1159 nullptr,
1160 array,
1161 array->GetClass());
1162 if (stop_reports_) {
1163 return;
1164 }
1165
1166 if (array->IsObjectArray()) {
Vladimir Marko4617d582019-03-28 13:48:31 +00001167 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> obj_array =
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001168 array->AsObjectArray<art::mirror::Object>();
Alex Lighta9bbc082019-11-14 14:51:41 -08001169 for (auto elem_pair : art::ZipCount(obj_array->Iterate())) {
1170 if (elem_pair.first != nullptr) {
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001171 jvmtiHeapReferenceInfo reference_info;
Alex Lighta9bbc082019-11-14 14:51:41 -08001172 reference_info.array.index = elem_pair.second;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001173 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT,
1174 &reference_info,
1175 array,
Alex Lighta9bbc082019-11-14 14:51:41 -08001176 elem_pair.first.Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001177 if (stop_reports_) {
1178 break;
1179 }
1180 }
1181 }
Andreas Gampebecd6ad2017-02-22 19:20:37 -08001182 } else {
1183 if (!stop_reports_) {
1184 jint array_ret = ReportPrimitiveArray(array, env, tag_table_, callbacks_, user_data_);
1185 stop_reports_ = (array_ret & JVMTI_VISIT_ABORT) != 0;
1186 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001187 }
1188 }
1189
1190 void VisitClass(art::mirror::Class* klass)
1191 REQUIRES_SHARED(art::Locks::mutator_lock_)
1192 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1193 // TODO: Are erroneous classes reported? Are non-prepared ones? For now, just use resolved ones.
1194 if (!klass->IsResolved()) {
1195 return;
1196 }
1197
1198 // Superclass.
1199 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_SUPERCLASS,
1200 nullptr,
1201 klass,
Andreas Gampe98104992018-10-16 12:49:47 -07001202 klass->GetSuperClass().Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001203 if (stop_reports_) {
1204 return;
1205 }
1206
1207 // Directly implemented or extended interfaces.
1208 art::Thread* self = art::Thread::Current();
1209 art::StackHandleScope<1> hs(self);
1210 art::Handle<art::mirror::Class> h_klass(hs.NewHandle<art::mirror::Class>(klass));
1211 for (size_t i = 0; i < h_klass->NumDirectInterfaces(); ++i) {
1212 art::ObjPtr<art::mirror::Class> inf_klass =
Vladimir Marko19a4d372016-12-08 14:41:46 +00001213 art::mirror::Class::ResolveDirectInterface(self, h_klass, i);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001214 if (inf_klass == nullptr) {
1215 // TODO: With a resolved class this should not happen...
1216 self->ClearException();
1217 break;
1218 }
1219
1220 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_INTERFACE,
1221 nullptr,
1222 klass,
1223 inf_klass.Ptr());
1224 if (stop_reports_) {
1225 return;
1226 }
1227 }
1228
1229 // Classloader.
1230 // TODO: What about the boot classpath loader? We'll skip for now, but do we have to find the
1231 // fake BootClassLoader?
1232 if (klass->GetClassLoader() != nullptr) {
1233 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_CLASS_LOADER,
1234 nullptr,
1235 klass,
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001236 klass->GetClassLoader().Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001237 if (stop_reports_) {
1238 return;
1239 }
1240 }
1241 DCHECK_EQ(h_klass.Get(), klass);
1242
1243 // Declared static fields.
Andreas Gampe95114602017-02-28 15:47:44 -08001244 auto report_static_field = [&](art::ObjPtr<art::mirror::Object> obj ATTRIBUTE_UNUSED,
1245 art::ObjPtr<art::mirror::Class> obj_klass,
1246 art::ArtField& field,
1247 size_t field_index,
1248 void* user_data ATTRIBUTE_UNUSED)
1249 REQUIRES_SHARED(art::Locks::mutator_lock_)
1250 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1251 art::ObjPtr<art::mirror::Object> field_value = field.GetObject(obj_klass);
1252 if (field_value != nullptr) {
1253 jvmtiHeapReferenceInfo reference_info;
1254 memset(&reference_info, 0, sizeof(reference_info));
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001255
Andreas Gampe95114602017-02-28 15:47:44 -08001256 reference_info.field.index = static_cast<jint>(field_index);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001257
Andreas Gampe95114602017-02-28 15:47:44 -08001258 return !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_STATIC_FIELD,
1259 &reference_info,
1260 obj_klass.Ptr(),
1261 field_value.Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001262 }
Andreas Gampe95114602017-02-28 15:47:44 -08001263 return false;
1264 };
1265 stop_reports_ = FieldVisitor<void, false>::ReportFields(klass,
1266 nullptr,
1267 VisitorFalse<void>,
1268 report_static_field,
1269 VisitorFalse<void>,
1270 VisitorFalse<void>);
1271 if (stop_reports_) {
1272 return;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001273 }
Andreas Gampee7316932017-02-25 09:15:05 -08001274
Andreas Gampe95114602017-02-28 15:47:44 -08001275 stop_reports_ = ReportPrimitiveField::Report(klass, tag_table_, callbacks_, user_data_);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001276 }
1277
1278 void MaybeEnqueue(art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1279 if (visited_.find(obj) == visited_.end()) {
1280 worklist_.push_back(obj);
1281 visited_.insert(obj);
1282 }
1283 }
1284
1285 bool ReportReferenceMaybeEnqueue(jvmtiHeapReferenceKind kind,
1286 const jvmtiHeapReferenceInfo* reference_info,
1287 art::mirror::Object* referree,
1288 art::mirror::Object* referrer)
1289 REQUIRES_SHARED(art::Locks::mutator_lock_)
1290 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1291 jint result = ReportReference(kind, reference_info, referree, referrer);
1292 if ((result & JVMTI_VISIT_ABORT) == 0) {
1293 if ((result & JVMTI_VISIT_OBJECTS) != 0) {
1294 MaybeEnqueue(referrer);
1295 }
1296 return true;
1297 } else {
1298 return false;
1299 }
1300 }
1301
1302 jint ReportReference(jvmtiHeapReferenceKind kind,
1303 const jvmtiHeapReferenceInfo* reference_info,
1304 art::mirror::Object* referrer,
1305 art::mirror::Object* referree)
1306 REQUIRES_SHARED(art::Locks::mutator_lock_)
1307 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1308 if (referree == nullptr || stop_reports_) {
1309 return 0;
1310 }
1311
Andreas Gampe38da9f22017-02-20 13:35:36 -08001312 if (UNLIKELY(class_filter_ != nullptr) && class_filter_ != referree->GetClass()) {
1313 return JVMTI_VISIT_OBJECTS;
1314 }
1315
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001316 const jlong class_tag = tag_table_->GetTagOrZero(referree->GetClass());
Andreas Gampe6ea06072017-02-24 18:01:19 +00001317 jlong tag = tag_table_->GetTagOrZero(referree);
1318
1319 if (!heap_filter_.ShouldReportByHeapFilter(tag, class_tag)) {
1320 return JVMTI_VISIT_OBJECTS;
1321 }
1322
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001323 const jlong referrer_class_tag =
1324 referrer == nullptr ? 0 : tag_table_->GetTagOrZero(referrer->GetClass());
1325 const jlong size = static_cast<jlong>(referree->SizeOf());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001326 jlong saved_tag = tag;
1327 jlong referrer_tag = 0;
1328 jlong saved_referrer_tag = 0;
1329 jlong* referrer_tag_ptr;
1330 if (referrer == nullptr) {
1331 referrer_tag_ptr = nullptr;
1332 } else {
1333 if (referrer == referree) {
1334 referrer_tag_ptr = &tag;
1335 } else {
1336 referrer_tag = saved_referrer_tag = tag_table_->GetTagOrZero(referrer);
1337 referrer_tag_ptr = &referrer_tag;
1338 }
1339 }
Andreas Gampe38da9f22017-02-20 13:35:36 -08001340
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001341 jint length = -1;
1342 if (referree->IsArrayInstance()) {
1343 length = referree->AsArray()->GetLength();
1344 }
1345
1346 jint result = callbacks_->heap_reference_callback(kind,
1347 reference_info,
1348 class_tag,
1349 referrer_class_tag,
1350 size,
1351 &tag,
1352 referrer_tag_ptr,
1353 length,
1354 const_cast<void*>(user_data_));
1355
1356 if (tag != saved_tag) {
1357 tag_table_->Set(referree, tag);
1358 }
1359 if (referrer_tag != saved_referrer_tag) {
1360 tag_table_->Set(referrer, referrer_tag);
1361 }
1362
1363 return result;
1364 }
1365
Andreas Gampe3ec8e402017-02-21 15:49:53 -08001366 jvmtiEnv* env;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001367 ObjectTagTable* tag_table_;
Andreas Gampe638a6932016-12-02 19:11:17 -08001368 art::ObjPtr<art::mirror::Object> initial_object_;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001369 const jvmtiHeapCallbacks* callbacks_;
Andreas Gampe38da9f22017-02-20 13:35:36 -08001370 art::ObjPtr<art::mirror::Class> class_filter_;
Andreas Gampe6ea06072017-02-24 18:01:19 +00001371 const HeapFilter heap_filter_;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001372 const void* user_data_;
1373
1374 std::vector<art::mirror::Object*> worklist_;
1375 size_t start_;
1376 static constexpr size_t kMaxStart = 1000000U;
1377
1378 std::unordered_set<art::mirror::Object*> visited_;
1379
1380 bool stop_reports_;
1381
1382 friend class CollectAndReportRootsVisitor;
1383};
1384
Andreas Gampe3ec8e402017-02-21 15:49:53 -08001385jvmtiError HeapUtil::FollowReferences(jvmtiEnv* env,
Andreas Gampe6ea06072017-02-24 18:01:19 +00001386 jint heap_filter,
Andreas Gampe38da9f22017-02-20 13:35:36 -08001387 jclass klass,
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001388 jobject initial_object,
1389 const jvmtiHeapCallbacks* callbacks,
1390 const void* user_data) {
1391 if (callbacks == nullptr) {
1392 return ERR(NULL_POINTER);
1393 }
1394
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001395 art::Thread* self = art::Thread::Current();
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001396
Andreas Gampe638a6932016-12-02 19:11:17 -08001397 art::gc::Heap* heap = art::Runtime::Current()->GetHeap();
1398 if (heap->IsGcConcurrentAndMoving()) {
1399 // Need to take a heap dump while GC isn't running. See the
1400 // comment in Heap::VisitObjects().
1401 heap->IncrementDisableMovingGC(self);
1402 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001403 {
Andreas Gampe638a6932016-12-02 19:11:17 -08001404 art::ScopedObjectAccess soa(self); // Now we know we have the shared lock.
Alex Light79d6c802019-06-27 15:50:11 +00001405 art::jni::ScopedEnableSuspendAllJniIdQueries sjni; // make sure we can get JNI ids.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001406 art::ScopedThreadSuspension sts(self, art::ThreadState::kWaitingForVisitObjects);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001407 art::ScopedSuspendAll ssa("FollowReferences");
1408
Andreas Gampe38da9f22017-02-20 13:35:36 -08001409 art::ObjPtr<art::mirror::Class> class_filter = klass == nullptr
1410 ? nullptr
1411 : art::ObjPtr<art::mirror::Class>::DownCast(self->DecodeJObject(klass));
Andreas Gampe638a6932016-12-02 19:11:17 -08001412 FollowReferencesHelper frh(this,
Andreas Gampe3ec8e402017-02-21 15:49:53 -08001413 env,
Andreas Gampe638a6932016-12-02 19:11:17 -08001414 self->DecodeJObject(initial_object),
1415 callbacks,
Andreas Gampe38da9f22017-02-20 13:35:36 -08001416 class_filter,
Andreas Gampe6ea06072017-02-24 18:01:19 +00001417 heap_filter,
Andreas Gampe638a6932016-12-02 19:11:17 -08001418 user_data);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001419 frh.Init();
1420 frh.Work();
1421 }
Andreas Gampe638a6932016-12-02 19:11:17 -08001422 if (heap->IsGcConcurrentAndMoving()) {
1423 heap->DecrementDisableMovingGC(self);
1424 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001425
1426 return ERR(NONE);
1427}
1428
Andreas Gampeaa8b60c2016-10-12 12:51:25 -07001429jvmtiError HeapUtil::GetLoadedClasses(jvmtiEnv* env,
1430 jint* class_count_ptr,
1431 jclass** classes_ptr) {
1432 if (class_count_ptr == nullptr || classes_ptr == nullptr) {
1433 return ERR(NULL_POINTER);
1434 }
1435
1436 class ReportClassVisitor : public art::ClassVisitor {
1437 public:
1438 explicit ReportClassVisitor(art::Thread* self) : self_(self) {}
1439
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001440 bool operator()(art::ObjPtr<art::mirror::Class> klass)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001441 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightf8a4a2c2017-06-22 08:43:37 -07001442 if (klass->IsLoaded() || klass->IsErroneous()) {
1443 classes_.push_back(self_->GetJniEnv()->AddLocalReference<jclass>(klass));
1444 }
Andreas Gampeaa8b60c2016-10-12 12:51:25 -07001445 return true;
1446 }
1447
1448 art::Thread* self_;
1449 std::vector<jclass> classes_;
1450 };
1451
1452 art::Thread* self = art::Thread::Current();
1453 ReportClassVisitor rcv(self);
1454 {
1455 art::ScopedObjectAccess soa(self);
1456 art::Runtime::Current()->GetClassLinker()->VisitClasses(&rcv);
1457 }
1458
1459 size_t size = rcv.classes_.size();
1460 jclass* classes = nullptr;
1461 jvmtiError alloc_ret = env->Allocate(static_cast<jlong>(size * sizeof(jclass)),
1462 reinterpret_cast<unsigned char**>(&classes));
1463 if (alloc_ret != ERR(NONE)) {
1464 return alloc_ret;
1465 }
1466
1467 for (size_t i = 0; i < size; ++i) {
1468 classes[i] = rcv.classes_[i];
1469 }
1470 *classes_ptr = classes;
1471 *class_count_ptr = static_cast<jint>(size);
1472
1473 return ERR(NONE);
1474}
1475
Andreas Gampe8da6d032016-10-31 19:31:03 -07001476jvmtiError HeapUtil::ForceGarbageCollection(jvmtiEnv* env ATTRIBUTE_UNUSED) {
Andreas Gampe6e897762018-10-16 13:09:32 -07001477 art::Runtime::Current()->GetHeap()->CollectGarbage(/* clear_soft_references= */ false);
Andreas Gampe8da6d032016-10-31 19:31:03 -07001478
1479 return ERR(NONE);
1480}
Andreas Gamped73aba42017-05-03 21:40:26 -07001481
1482static constexpr jint kHeapIdDefault = 0;
1483static constexpr jint kHeapIdImage = 1;
1484static constexpr jint kHeapIdZygote = 2;
1485static constexpr jint kHeapIdApp = 3;
1486
Andreas Gampe2eb25e42017-05-09 17:14:58 -07001487static jint GetHeapId(art::ObjPtr<art::mirror::Object> obj)
1488 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1489 if (obj == nullptr) {
1490 return -1;
1491 }
1492
1493 art::gc::Heap* const heap = art::Runtime::Current()->GetHeap();
1494 const art::gc::space::ContinuousSpace* const space =
1495 heap->FindContinuousSpaceFromObject(obj, true);
1496 jint heap_type = kHeapIdApp;
1497 if (space != nullptr) {
1498 if (space->IsZygoteSpace()) {
1499 heap_type = kHeapIdZygote;
1500 } else if (space->IsImageSpace() && heap->ObjectIsInBootImageSpace(obj)) {
1501 // Only count objects in the boot image as HPROF_HEAP_IMAGE, this leaves app image objects
1502 // as HPROF_HEAP_APP. b/35762934
1503 heap_type = kHeapIdImage;
1504 }
1505 } else {
1506 const auto* los = heap->GetLargeObjectsSpace();
1507 if (los->Contains(obj.Ptr()) && los->IsZygoteLargeObject(art::Thread::Current(), obj.Ptr())) {
1508 heap_type = kHeapIdZygote;
1509 }
1510 }
1511 return heap_type;
1512};
1513
Andreas Gamped73aba42017-05-03 21:40:26 -07001514jvmtiError HeapExtensions::GetObjectHeapId(jvmtiEnv* env, jlong tag, jint* heap_id, ...) {
1515 if (heap_id == nullptr) {
1516 return ERR(NULL_POINTER);
1517 }
1518
1519 art::Thread* self = art::Thread::Current();
1520
1521 auto work = [&]() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1522 ObjectTagTable* tag_table = ArtJvmTiEnv::AsArtJvmTiEnv(env)->object_tag_table.get();
1523 art::ObjPtr<art::mirror::Object> obj = tag_table->Find(tag);
Andreas Gampe2eb25e42017-05-09 17:14:58 -07001524 jint heap_type = GetHeapId(obj);
1525 if (heap_type == -1) {
Andreas Gamped73aba42017-05-03 21:40:26 -07001526 return ERR(NOT_FOUND);
1527 }
Andreas Gamped73aba42017-05-03 21:40:26 -07001528 *heap_id = heap_type;
1529 return ERR(NONE);
1530 };
1531
1532 if (!art::Locks::mutator_lock_->IsSharedHeld(self)) {
1533 if (!self->IsThreadSuspensionAllowable()) {
1534 return ERR(INTERNAL);
1535 }
1536 art::ScopedObjectAccess soa(self);
1537 return work();
1538 } else {
1539 // We cannot use SOA in this case. We might be holding the lock, but may not be in the
1540 // runnable state (e.g., during GC).
1541 art::Locks::mutator_lock_->AssertSharedHeld(self);
1542 // TODO: Investigate why ASSERT_SHARED_CAPABILITY doesn't work.
1543 auto annotalysis_workaround = [&]() NO_THREAD_SAFETY_ANALYSIS {
1544 return work();
1545 };
1546 return annotalysis_workaround();
1547 }
1548}
1549
1550static jvmtiError CopyStringAndReturn(jvmtiEnv* env, const char* in, char** out) {
1551 jvmtiError error;
1552 JvmtiUniquePtr<char[]> param_name = CopyString(env, in, &error);
1553 if (param_name == nullptr) {
1554 return error;
1555 }
1556 *out = param_name.release();
1557 return ERR(NONE);
1558}
1559
1560static constexpr const char* kHeapIdDefaultName = "default";
1561static constexpr const char* kHeapIdImageName = "image";
1562static constexpr const char* kHeapIdZygoteName = "zygote";
1563static constexpr const char* kHeapIdAppName = "app";
1564
1565jvmtiError HeapExtensions::GetHeapName(jvmtiEnv* env, jint heap_id, char** heap_name, ...) {
1566 switch (heap_id) {
1567 case kHeapIdDefault:
1568 return CopyStringAndReturn(env, kHeapIdDefaultName, heap_name);
1569 case kHeapIdImage:
1570 return CopyStringAndReturn(env, kHeapIdImageName, heap_name);
1571 case kHeapIdZygote:
1572 return CopyStringAndReturn(env, kHeapIdZygoteName, heap_name);
1573 case kHeapIdApp:
1574 return CopyStringAndReturn(env, kHeapIdAppName, heap_name);
1575
1576 default:
1577 return ERR(ILLEGAL_ARGUMENT);
1578 }
1579}
1580
Andreas Gampe2eb25e42017-05-09 17:14:58 -07001581jvmtiError HeapExtensions::IterateThroughHeapExt(jvmtiEnv* env,
1582 jint heap_filter,
1583 jclass klass,
1584 const jvmtiHeapCallbacks* callbacks,
1585 const void* user_data) {
1586 if (ArtJvmTiEnv::AsArtJvmTiEnv(env)->capabilities.can_tag_objects != 1) { \
1587 return ERR(MUST_POSSESS_CAPABILITY); \
1588 }
1589
1590 // ART extension API: Also pass the heap id.
1591 auto ArtIterateHeap = [](art::mirror::Object* obj,
1592 const jvmtiHeapCallbacks* cb_callbacks,
1593 jlong class_tag,
1594 jlong size,
1595 jlong* tag,
1596 jint length,
1597 void* cb_user_data)
1598 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1599 jint heap_id = GetHeapId(obj);
1600 using ArtExtensionAPI = jint (*)(jlong, jlong, jlong*, jint length, void*, jint);
1601 return reinterpret_cast<ArtExtensionAPI>(cb_callbacks->heap_iteration_callback)(
1602 class_tag, size, tag, length, cb_user_data, heap_id);
1603 };
1604 return DoIterateThroughHeap(ArtIterateHeap,
1605 env,
1606 ArtJvmTiEnv::AsArtJvmTiEnv(env)->object_tag_table.get(),
1607 heap_filter,
1608 klass,
1609 callbacks,
1610 user_data);
1611}
1612
Alex Lightc14ec8f2019-07-18 16:08:41 -07001613namespace {
1614
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001615using ObjectPtr = art::ObjPtr<art::mirror::Object>;
Alex Light986914b2019-11-19 01:12:25 +00001616using ObjectMap = std::unordered_map<ObjectPtr, ObjectPtr, art::HashObjPtr>;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001617
Alex Light986914b2019-11-19 01:12:25 +00001618static void ReplaceObjectReferences(const ObjectMap& map)
Alex Lightc14ec8f2019-07-18 16:08:41 -07001619 REQUIRES(art::Locks::mutator_lock_,
Alex Lightc14ec8f2019-07-18 16:08:41 -07001620 art::Roles::uninterruptible_) {
1621 art::Runtime::Current()->GetHeap()->VisitObjectsPaused(
1622 [&](art::mirror::Object* ref) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1623 // Rewrite all references in the object if needed.
1624 class ResizeReferenceVisitor {
1625 public:
1626 using CompressedObj = art::mirror::CompressedReference<art::mirror::Object>;
Alex Lighta142f712019-12-03 05:52:33 -08001627 explicit ResizeReferenceVisitor(const ObjectMap& map, ObjectPtr ref)
1628 : map_(map), ref_(ref) {}
Alex Lightc14ec8f2019-07-18 16:08:41 -07001629
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001630 // Ignore class roots.
1631 void VisitRootIfNonNull(CompressedObj* root) const
1632 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1633 if (root != nullptr) {
1634 VisitRoot(root);
1635 }
1636 }
1637 void VisitRoot(CompressedObj* root) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light986914b2019-11-19 01:12:25 +00001638 auto it = map_.find(root->AsMirrorPtr());
1639 if (it != map_.end()) {
1640 root->Assign(it->second);
Alex Lighta142f712019-12-03 05:52:33 -08001641 art::WriteBarrier::ForEveryFieldWrite(ref_);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001642 }
1643 }
Alex Lightc14ec8f2019-07-18 16:08:41 -07001644
1645 void operator()(art::ObjPtr<art::mirror::Object> obj,
1646 art::MemberOffset off,
Alex Light986914b2019-11-19 01:12:25 +00001647 bool is_static) const
Alex Lightc14ec8f2019-07-18 16:08:41 -07001648 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light986914b2019-11-19 01:12:25 +00001649 auto it = map_.find(obj->GetFieldObject<art::mirror::Object>(off));
1650 if (it != map_.end()) {
1651 UNUSED(is_static);
1652 if (UNLIKELY(!is_static && off == art::mirror::Object::ClassOffset())) {
1653 // We don't want to update the declaring class of any objects. They will be replaced
1654 // in the heap and we need the declaring class to know its size.
1655 return;
Alex Light270db1c2019-12-03 12:20:01 +00001656 } else if (UNLIKELY(!is_static && off == art::mirror::Class::SuperClassOffset() &&
1657 obj->IsClass())) {
1658 // We don't want to be messing with the class hierarcy either.
1659 return;
Alex Light986914b2019-11-19 01:12:25 +00001660 }
Alex Lightb0ce4d22019-09-19 14:45:45 -07001661 VLOG(plugin) << "Updating field at offset " << off.Uint32Value() << " of type "
1662 << obj->GetClass()->PrettyClass();
Alex Light986914b2019-11-19 01:12:25 +00001663 obj->SetFieldObject</*transaction*/ false>(off, it->second);
1664 art::WriteBarrier::ForEveryFieldWrite(obj);
Alex Lightc14ec8f2019-07-18 16:08:41 -07001665 }
1666 }
1667
1668 // java.lang.ref.Reference visitor.
1669 void operator()(art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
1670 art::ObjPtr<art::mirror::Reference> ref) const
1671 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1672 operator()(ref, art::mirror::Reference::ReferentOffset(), /* is_static */ false);
1673 }
1674
1675 private:
Alex Light986914b2019-11-19 01:12:25 +00001676 const ObjectMap& map_;
Alex Lighta142f712019-12-03 05:52:33 -08001677 ObjectPtr ref_;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001678 };
1679
Alex Lighta142f712019-12-03 05:52:33 -08001680 ResizeReferenceVisitor rrv(map, ref);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001681 if (ref->IsClass()) {
1682 // Class object native roots are the ArtField and ArtMethod 'declaring_class_' fields
1683 // which we don't want to be messing with as it would break ref-visitor assumptions about
1684 // what a class looks like. We want to keep the default behavior in other cases (such as
1685 // dex-cache) though. Unfortunately there is no way to tell from the visitor where exactly
1686 // the root came from.
1687 // TODO It might be nice to have the visitors told where the reference came from.
1688 ref->VisitReferences</*kVisitNativeRoots*/false>(rrv, rrv);
1689 } else {
1690 ref->VisitReferences</*kVisitNativeRoots*/true>(rrv, rrv);
1691 }
Alex Lightc14ec8f2019-07-18 16:08:41 -07001692 });
1693}
1694
Alex Light986914b2019-11-19 01:12:25 +00001695static void ReplaceStrongRoots(art::Thread* self, const ObjectMap& map)
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001696 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
Alex Lightc14ec8f2019-07-18 16:08:41 -07001697 // replace root references expcept java frames.
1698 struct ResizeRootVisitor : public art::RootVisitor {
1699 public:
Alex Light986914b2019-11-19 01:12:25 +00001700 explicit ResizeRootVisitor(const ObjectMap& map) : map_(map) {}
Alex Lightc14ec8f2019-07-18 16:08:41 -07001701
1702 // TODO It's somewhat annoying to have to have this function implemented twice. It might be
1703 // good/useful to implement operator= for CompressedReference to allow us to use a template to
1704 // implement both of these.
1705 void VisitRoots(art::mirror::Object*** roots, size_t count, const art::RootInfo& info) override
1706 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1707 art::mirror::Object*** end = roots + count;
1708 for (art::mirror::Object** obj = *roots; roots != end; obj = *(++roots)) {
Alex Light986914b2019-11-19 01:12:25 +00001709 auto it = map_.find(*obj);
1710 if (it != map_.end()) {
Alex Lightc14ec8f2019-07-18 16:08:41 -07001711 // Java frames might have the JIT doing optimizations (for example loop-unrolling or
1712 // eliding bounds checks) so we need deopt them once we're done here.
1713 if (info.GetType() == art::RootType::kRootJavaFrame) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001714 const art::JavaFrameRootInfo& jfri =
1715 art::down_cast<const art::JavaFrameRootInfo&>(info);
1716 if (jfri.GetVReg() == art::JavaFrameRootInfo::kMethodDeclaringClass) {
Alex Lightb55ef652019-09-26 15:23:28 -07001717 info.Describe(VLOG_STREAM(plugin) << "Not changing declaring-class during stack"
1718 << " walk. Found obsolete java frame id ");
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001719 continue;
1720 } else {
Alex Lightb55ef652019-09-26 15:23:28 -07001721 info.Describe(VLOG_STREAM(plugin) << "Found java frame id ");
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001722 threads_with_roots_.insert(info.GetThreadId());
1723 }
Alex Lightc14ec8f2019-07-18 16:08:41 -07001724 }
Alex Light986914b2019-11-19 01:12:25 +00001725 *obj = it->second.Ptr();
Alex Lightc14ec8f2019-07-18 16:08:41 -07001726 }
1727 }
1728 }
1729
1730 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
1731 size_t count,
1732 const art::RootInfo& info) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
1733 art::mirror::CompressedReference<art::mirror::Object>** end = roots + count;
1734 for (art::mirror::CompressedReference<art::mirror::Object>* obj = *roots; roots != end;
1735 obj = *(++roots)) {
Alex Light986914b2019-11-19 01:12:25 +00001736 auto it = map_.find(obj->AsMirrorPtr());
1737 if (it != map_.end()) {
Alex Lightc14ec8f2019-07-18 16:08:41 -07001738 // Java frames might have the JIT doing optimizations (for example loop-unrolling or
1739 // eliding bounds checks) so we need deopt them once we're done here.
1740 if (info.GetType() == art::RootType::kRootJavaFrame) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001741 const art::JavaFrameRootInfo& jfri =
1742 art::down_cast<const art::JavaFrameRootInfo&>(info);
1743 if (jfri.GetVReg() == art::JavaFrameRootInfo::kMethodDeclaringClass) {
Alex Lightb55ef652019-09-26 15:23:28 -07001744 info.Describe(VLOG_STREAM(plugin) << "Not changing declaring-class during stack"
1745 << " walk. Found obsolete java frame id ");
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001746 continue;
1747 } else {
Alex Lightb55ef652019-09-26 15:23:28 -07001748 info.Describe(VLOG_STREAM(plugin) << "Found java frame id ");
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001749 threads_with_roots_.insert(info.GetThreadId());
1750 }
Alex Lightc14ec8f2019-07-18 16:08:41 -07001751 }
Alex Light986914b2019-11-19 01:12:25 +00001752 obj->Assign(it->second);
Alex Lightc14ec8f2019-07-18 16:08:41 -07001753 }
1754 }
1755 }
1756
1757 const std::unordered_set<uint32_t>& GetThreadsWithJavaFrameRoots() const {
1758 return threads_with_roots_;
1759 }
1760
1761 private:
Alex Light986914b2019-11-19 01:12:25 +00001762 const ObjectMap& map_;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001763 std::unordered_set<uint32_t> threads_with_roots_;
1764 };
Alex Light986914b2019-11-19 01:12:25 +00001765 ResizeRootVisitor rrv(map);
Alex Lightc14ec8f2019-07-18 16:08:41 -07001766 art::Runtime::Current()->VisitRoots(&rrv, art::VisitRootFlags::kVisitRootFlagAllRoots);
1767 // Handle java Frames. Annoyingly the JIT can embed information about the length of the array into
1768 // the compiled code. By changing the length of the array we potentially invalidate these
1769 // assumptions and so could cause (eg) OOB array access or other issues.
1770 if (!rrv.GetThreadsWithJavaFrameRoots().empty()) {
1771 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
1772 art::ThreadList* thread_list = art::Runtime::Current()->GetThreadList();
1773 art::instrumentation::Instrumentation* instr = art::Runtime::Current()->GetInstrumentation();
1774 for (uint32_t id : rrv.GetThreadsWithJavaFrameRoots()) {
1775 art::Thread* t = thread_list->FindThreadByThreadId(id);
1776 CHECK(t != nullptr) << "id " << id << " does not refer to a valid thread."
1777 << " Where did the roots come from?";
Alex Lightb0ce4d22019-09-19 14:45:45 -07001778 VLOG(plugin) << "Instrumenting thread stack of thread " << *t;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001779 // TODO Use deopt manager. We need a version that doesn't acquire all the locks we
1780 // already have.
1781 // TODO We technically only need to do this if the frames are not already being interpreted.
1782 // The cost for doing an extra stack walk is unlikely to be worth it though.
Mythri Alle5097f832021-11-02 14:52:30 +00001783 instr->InstrumentThreadStack(t, /* deopt_all_frames= */ true);
Alex Lightc14ec8f2019-07-18 16:08:41 -07001784 }
1785 }
1786}
1787
Alex Light72d7e942019-07-23 13:10:20 -07001788static void ReplaceWeakRoots(art::Thread* self,
1789 EventHandler* event_handler,
Alex Light986914b2019-11-19 01:12:25 +00001790 const ObjectMap& map)
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001791 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
Alex Light72d7e942019-07-23 13:10:20 -07001792 // Handle tags. We want to do this seprately from other weak-refs (handled below) because we need
1793 // to send additional events and handle cases where the agent might have tagged the new
1794 // replacement object during the VMObjectAlloc. We do this by removing all tags associated with
1795 // both the obsolete and the new arrays. Then we send the ObsoleteObjectCreated event and cache
1796 // the new tag values. We next update all the other weak-references (the tags have been removed)
1797 // and finally update the tag table with the new values. Doing things in this way (1) keeps all
1798 // code relating to updating weak-references together and (2) ensures we don't end up in strange
1799 // situations where the order of weak-ref visiting affects the final tagging state. Since we have
1800 // the mutator_lock_ and gc-paused throughout this whole process no threads should be able to see
1801 // the interval where the objects are not tagged.
Alex Light986914b2019-11-19 01:12:25 +00001802 struct NewTagValue {
1803 public:
1804 ObjectPtr obsolete_obj_;
1805 jlong obsolete_tag_;
1806 ObjectPtr new_obj_;
1807 jlong new_tag_;
1808 };
1809
1810 // Map from the environment to the list of <obsolete_tag, new_tag> pairs that were changed.
1811 std::unordered_map<ArtJvmTiEnv*, std::vector<NewTagValue>> changed_tags;
Alex Light72d7e942019-07-23 13:10:20 -07001812 event_handler->ForEachEnv(self, [&](ArtJvmTiEnv* env) {
1813 // Cannot have REQUIRES(art::Locks::mutator_lock_) since ForEachEnv doesn't require it.
1814 art::Locks::mutator_lock_->AssertExclusiveHeld(self);
1815 env->object_tag_table->Lock();
1816 // Get the tags and clear them (so we don't need to special-case the normal weak-ref visitor)
Alex Light986914b2019-11-19 01:12:25 +00001817 for (auto it : map) {
1818 jlong new_tag = 0;
1819 jlong obsolete_tag = 0;
1820 bool had_obsolete_tag = env->object_tag_table->RemoveLocked(it.first, &obsolete_tag);
1821 bool had_new_tag = env->object_tag_table->RemoveLocked(it.second, &new_tag);
1822 // Dispatch event.
1823 if (had_obsolete_tag || had_new_tag) {
1824 event_handler->DispatchEventOnEnv<ArtJvmtiEvent::kObsoleteObjectCreated>(
1825 env, self, &obsolete_tag, &new_tag);
1826 changed_tags.try_emplace(env).first->second.push_back(
1827 { it.first, obsolete_tag, it.second, new_tag });
1828 }
Alex Light72d7e942019-07-23 13:10:20 -07001829 }
1830 // After weak-ref update we need to go back and re-add obsoletes. We wait to avoid having to
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001831 // deal with the visit-weaks overwriting the initial new_obj_ptr tag and generally making things
Alex Light72d7e942019-07-23 13:10:20 -07001832 // difficult.
1833 env->object_tag_table->Unlock();
1834 });
1835 // Handle weak-refs.
Alex Lightc14ec8f2019-07-18 16:08:41 -07001836 struct ReplaceWeaksVisitor : public art::IsMarkedVisitor {
1837 public:
Alex Light986914b2019-11-19 01:12:25 +00001838 ReplaceWeaksVisitor(const ObjectMap& map) : map_(map) {}
Alex Lightc14ec8f2019-07-18 16:08:41 -07001839
1840 art::mirror::Object* IsMarked(art::mirror::Object* obj)
1841 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light986914b2019-11-19 01:12:25 +00001842 auto it = map_.find(obj);
1843 if (it != map_.end()) {
1844 return it->second.Ptr();
Alex Lightc14ec8f2019-07-18 16:08:41 -07001845 } else {
1846 return obj;
1847 }
1848 }
1849
1850 private:
Alex Light986914b2019-11-19 01:12:25 +00001851 const ObjectMap& map_;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001852 };
Alex Light986914b2019-11-19 01:12:25 +00001853 ReplaceWeaksVisitor rwv(map);
Alex Lightc14ec8f2019-07-18 16:08:41 -07001854 art::Runtime::Current()->SweepSystemWeaks(&rwv);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001855 // Re-add the object tags. At this point all weak-references to the old_obj_ptr are gone.
Alex Light72d7e942019-07-23 13:10:20 -07001856 event_handler->ForEachEnv(self, [&](ArtJvmTiEnv* env) {
1857 // Cannot have REQUIRES(art::Locks::mutator_lock_) since ForEachEnv doesn't require it.
1858 art::Locks::mutator_lock_->AssertExclusiveHeld(self);
1859 env->object_tag_table->Lock();
Alex Light986914b2019-11-19 01:12:25 +00001860 auto it = changed_tags.find(env);
1861 if (it != changed_tags.end()) {
1862 for (const NewTagValue& v : it->second) {
1863 env->object_tag_table->SetLocked(v.obsolete_obj_, v.obsolete_tag_);
1864 env->object_tag_table->SetLocked(v.new_obj_, v.new_tag_);
1865 }
Alex Light72d7e942019-07-23 13:10:20 -07001866 }
1867 env->object_tag_table->Unlock();
1868 });
Alex Lightc14ec8f2019-07-18 16:08:41 -07001869}
1870
Nicolas Geoffray5a2301d2019-09-18 06:11:22 +00001871} // namespace
1872
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001873void HeapExtensions::ReplaceReference(art::Thread* self,
1874 art::ObjPtr<art::mirror::Object> old_obj_ptr,
1875 art::ObjPtr<art::mirror::Object> new_obj_ptr) {
Alex Light986914b2019-11-19 01:12:25 +00001876 ObjectMap map { { old_obj_ptr, new_obj_ptr } };
1877 ReplaceReferences(self, map);
1878}
1879
1880void HeapExtensions::ReplaceReferences(art::Thread* self, const ObjectMap& map) {
1881 ReplaceObjectReferences(map);
1882 ReplaceStrongRoots(self, map);
1883 ReplaceWeakRoots(self, HeapExtensions::gEventHandler, map);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001884}
1885
Alex Lightc14ec8f2019-07-18 16:08:41 -07001886jvmtiError HeapExtensions::ChangeArraySize(jvmtiEnv* env, jobject arr, jsize new_size) {
1887 if (ArtJvmTiEnv::AsArtJvmTiEnv(env)->capabilities.can_tag_objects != 1) {
1888 return ERR(MUST_POSSESS_CAPABILITY);
1889 }
1890 art::Thread* self = art::Thread::Current();
1891 ScopedNoUserCodeSuspension snucs(self);
1892 art::ScopedObjectAccess soa(self);
1893 if (arr == nullptr) {
1894 JVMTI_LOG(INFO, env) << "Cannot resize a null object";
1895 return ERR(NULL_POINTER);
1896 }
1897 art::ObjPtr<art::mirror::Class> klass(soa.Decode<art::mirror::Object>(arr)->GetClass());
1898 if (!klass->IsArrayClass()) {
1899 JVMTI_LOG(INFO, env) << klass->PrettyClass() << " is not an array class!";
1900 return ERR(ILLEGAL_ARGUMENT);
1901 }
1902 if (new_size < 0) {
1903 JVMTI_LOG(INFO, env) << "Cannot resize an array to a negative size";
1904 return ERR(ILLEGAL_ARGUMENT);
1905 }
1906 // Allocate the new copy.
1907 art::StackHandleScope<2> hs(self);
1908 art::Handle<art::mirror::Array> old_arr(hs.NewHandle(soa.Decode<art::mirror::Array>(arr)));
1909 art::MutableHandle<art::mirror::Array> new_arr(hs.NewHandle<art::mirror::Array>(nullptr));
1910 if (klass->IsObjectArrayClass()) {
1911 new_arr.Assign(
1912 art::mirror::ObjectArray<art::mirror::Object>::Alloc(self, old_arr->GetClass(), new_size));
1913 } else {
1914 // NB This also copies the old array but since we aren't suspended we need to do this again to
1915 // catch any concurrent modifications.
1916 new_arr.Assign(art::mirror::Array::CopyOf(old_arr, self, new_size));
1917 }
1918 if (new_arr.IsNull()) {
1919 self->AssertPendingOOMException();
1920 JVMTI_LOG(INFO, env) << "Unable to allocate " << old_arr->GetClass()->PrettyClass()
1921 << " (length: " << new_size << ") due to OOME. Error was: "
1922 << self->GetException()->Dump();
1923 self->ClearException();
1924 return ERR(OUT_OF_MEMORY);
1925 } else {
1926 self->AssertNoPendingException();
1927 }
1928 // Suspend everything.
1929 art::ScopedThreadSuspension sts(self, art::ThreadState::kSuspended);
1930 art::gc::ScopedGCCriticalSection sgccs(
1931 self, art::gc::GcCause::kGcCauseDebugger, art::gc::CollectorType::kCollectorTypeDebugger);
1932 art::ScopedSuspendAll ssa("Resize array!");
1933 // Replace internals.
1934 new_arr->SetLockWord(old_arr->GetLockWord(false), false);
1935 old_arr->SetLockWord(art::LockWord::Default(), false);
1936 // Copy the contents now when everything is suspended.
1937 int32_t size = std::min(old_arr->GetLength(), new_size);
1938 switch (old_arr->GetClass()->GetComponentType()->GetPrimitiveType()) {
1939 case art::Primitive::kPrimBoolean:
1940 new_arr->AsBooleanArray()->Memcpy(0, old_arr->AsBooleanArray(), 0, size);
1941 break;
1942 case art::Primitive::kPrimByte:
1943 new_arr->AsByteArray()->Memcpy(0, old_arr->AsByteArray(), 0, size);
1944 break;
1945 case art::Primitive::kPrimChar:
1946 new_arr->AsCharArray()->Memcpy(0, old_arr->AsCharArray(), 0, size);
1947 break;
1948 case art::Primitive::kPrimShort:
1949 new_arr->AsShortArray()->Memcpy(0, old_arr->AsShortArray(), 0, size);
1950 break;
1951 case art::Primitive::kPrimInt:
1952 new_arr->AsIntArray()->Memcpy(0, old_arr->AsIntArray(), 0, size);
1953 break;
1954 case art::Primitive::kPrimLong:
1955 new_arr->AsLongArray()->Memcpy(0, old_arr->AsLongArray(), 0, size);
1956 break;
1957 case art::Primitive::kPrimFloat:
1958 new_arr->AsFloatArray()->Memcpy(0, old_arr->AsFloatArray(), 0, size);
1959 break;
1960 case art::Primitive::kPrimDouble:
1961 new_arr->AsDoubleArray()->Memcpy(0, old_arr->AsDoubleArray(), 0, size);
1962 break;
1963 case art::Primitive::kPrimNot:
1964 for (int32_t i = 0; i < size; i++) {
1965 new_arr->AsObjectArray<art::mirror::Object>()->Set(
1966 i, old_arr->AsObjectArray<art::mirror::Object>()->Get(i));
1967 }
1968 break;
1969 case art::Primitive::kPrimVoid:
1970 LOG(FATAL) << "void-array is not a legal type!";
1971 UNREACHABLE();
1972 }
1973 // Actually replace all the pointers.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001974 ReplaceReference(self, old_arr.Get(), new_arr.Get());
Alex Lightc14ec8f2019-07-18 16:08:41 -07001975 return OK;
1976}
1977
Alex Light72d7e942019-07-23 13:10:20 -07001978void HeapExtensions::Register(EventHandler* eh) {
1979 gEventHandler = eh;
1980}
1981
Andreas Gampee54d9922016-10-11 19:55:37 -07001982} // namespace openjdkjvmti