blob: b645590ce5148f666c15d495559ff998717f5b26 [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 Light79d6c802019-06-27 15:50:11 +000032#include "class_root.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070033#include "deopt_manager.h"
David Sehr67bf42e2018-02-26 16:43:04 -080034#include "dex/primitive.h"
Alex Light72d7e942019-07-23 13:10:20 -070035#include "events-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070036#include "gc/collector_type.h"
37#include "gc/gc_cause.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070038#include "gc/heap-visit-objects-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070039#include "gc/heap-inl.h"
40#include "gc/scoped_gc_critical_section.h"
Andreas Gampe70bfc8a2016-11-03 11:04:15 -070041#include "gc_root-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070042#include "handle.h"
Alex Light79d6c802019-06-27 15:50:11 +000043#include "handle_scope.h"
Andreas Gampe36a296f2017-06-13 14:11:11 -070044#include "java_frame_root_info.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010045#include "jni/jni_env_ext.h"
Alex Light79d6c802019-06-27 15:50:11 +000046#include "jni/jni_id_manager.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010047#include "jni/jni_internal.h"
Andreas Gampe9e38a502017-03-06 08:19:26 -080048#include "jvmti_weak_table-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070049#include "mirror/array-inl.h"
50#include "mirror/array.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070051#include "mirror/class.h"
Andreas Gampe70bfc8a2016-11-03 11:04:15 -070052#include "mirror/object-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070053#include "mirror/object-refvisitor-inl.h"
Andreas Gampe70bfc8a2016-11-03 11:04:15 -070054#include "mirror/object_array-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070055#include "mirror/object_array-alloc-inl.h"
56#include "mirror/object_reference.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070057#include "obj_ptr-inl.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070058#include "object_callbacks.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070059#include "object_tagging.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070060#include "offsets.h"
Alex Lighta142f712019-12-03 05:52:33 -080061#include "read_barrier.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070062#include "runtime.h"
63#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070064#include "stack.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070065#include "thread-inl.h"
Andreas Gampe70bfc8a2016-11-03 11:04:15 -070066#include "thread_list.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070067#include "ti_logging.h"
68#include "ti_stack.h"
69#include "ti_thread.h"
Alex Light79d6c802019-06-27 15:50:11 +000070#include "well_known_classes.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070071
72namespace openjdkjvmti {
73
Alex Light72d7e942019-07-23 13:10:20 -070074EventHandler* HeapExtensions::gEventHandler = nullptr;
75
Andreas Gampe3ec8e402017-02-21 15:49:53 -080076namespace {
77
Andreas Gampe9e38a502017-03-06 08:19:26 -080078struct IndexCache {
79 // The number of interface fields implemented by the class. This is a prefix to all assigned
80 // field indices.
81 size_t interface_fields;
82
83 // It would be nice to also cache the following, but it is complicated to wire up into the
84 // generic visit:
85 // The number of fields in interfaces and superclasses. This is the first index assigned to
86 // fields of the class.
87 // size_t superclass_fields;
88};
89using IndexCachingTable = JvmtiWeakTable<IndexCache>;
90
91static IndexCachingTable gIndexCachingTable;
92
Andreas Gampe3ec8e402017-02-21 15:49:53 -080093// Report the contents of a string, if a callback is set.
94jint ReportString(art::ObjPtr<art::mirror::Object> obj,
95 jvmtiEnv* env,
96 ObjectTagTable* tag_table,
97 const jvmtiHeapCallbacks* cb,
98 const void* user_data) REQUIRES_SHARED(art::Locks::mutator_lock_) {
99 if (UNLIKELY(cb->string_primitive_value_callback != nullptr) && obj->IsString()) {
100 art::ObjPtr<art::mirror::String> str = obj->AsString();
101 int32_t string_length = str->GetLength();
Andreas Gampe5f942032017-02-27 19:59:40 -0800102 JvmtiUniquePtr<uint16_t[]> data;
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800103
Andreas Gampe5f942032017-02-27 19:59:40 -0800104 if (string_length > 0) {
105 jvmtiError alloc_error;
106 data = AllocJvmtiUniquePtr<uint16_t[]>(env, string_length, &alloc_error);
107 if (data == nullptr) {
108 // TODO: Not really sure what to do here. Should we abort the iteration and go all the way
109 // back? For now just warn.
110 LOG(WARNING) << "Unable to allocate buffer for string reporting! Silently dropping value."
111 << " >" << str->ToModifiedUtf8() << "<";
112 return 0;
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800113 }
Andreas Gampe5f942032017-02-27 19:59:40 -0800114
115 if (str->IsCompressed()) {
116 uint8_t* compressed_data = str->GetValueCompressed();
117 for (int32_t i = 0; i != string_length; ++i) {
118 data[i] = compressed_data[i];
119 }
120 } else {
121 // Can copy directly.
122 memcpy(data.get(), str->GetValue(), string_length * sizeof(uint16_t));
123 }
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800124 }
125
126 const jlong class_tag = tag_table->GetTagOrZero(obj->GetClass());
127 jlong string_tag = tag_table->GetTagOrZero(obj.Ptr());
128 const jlong saved_string_tag = string_tag;
129
130 jint result = cb->string_primitive_value_callback(class_tag,
131 obj->SizeOf(),
132 &string_tag,
133 data.get(),
134 string_length,
135 const_cast<void*>(user_data));
136 if (string_tag != saved_string_tag) {
137 tag_table->Set(obj.Ptr(), string_tag);
138 }
139
140 return result;
141 }
142 return 0;
143}
144
Andreas Gampebecd6ad2017-02-22 19:20:37 -0800145// Report the contents of a primitive array, if a callback is set.
146jint ReportPrimitiveArray(art::ObjPtr<art::mirror::Object> obj,
147 jvmtiEnv* env,
148 ObjectTagTable* tag_table,
149 const jvmtiHeapCallbacks* cb,
150 const void* user_data) REQUIRES_SHARED(art::Locks::mutator_lock_) {
151 if (UNLIKELY(cb->array_primitive_value_callback != nullptr) &&
152 obj->IsArrayInstance() &&
153 !obj->IsObjectArray()) {
154 art::ObjPtr<art::mirror::Array> array = obj->AsArray();
155 int32_t array_length = array->GetLength();
156 size_t component_size = array->GetClass()->GetComponentSize();
157 art::Primitive::Type art_prim_type = array->GetClass()->GetComponentType()->GetPrimitiveType();
158 jvmtiPrimitiveType prim_type =
159 static_cast<jvmtiPrimitiveType>(art::Primitive::Descriptor(art_prim_type)[0]);
160 DCHECK(prim_type == JVMTI_PRIMITIVE_TYPE_BOOLEAN ||
161 prim_type == JVMTI_PRIMITIVE_TYPE_BYTE ||
162 prim_type == JVMTI_PRIMITIVE_TYPE_CHAR ||
163 prim_type == JVMTI_PRIMITIVE_TYPE_SHORT ||
164 prim_type == JVMTI_PRIMITIVE_TYPE_INT ||
165 prim_type == JVMTI_PRIMITIVE_TYPE_LONG ||
166 prim_type == JVMTI_PRIMITIVE_TYPE_FLOAT ||
167 prim_type == JVMTI_PRIMITIVE_TYPE_DOUBLE);
168
169 const jlong class_tag = tag_table->GetTagOrZero(obj->GetClass());
170 jlong array_tag = tag_table->GetTagOrZero(obj.Ptr());
171 const jlong saved_array_tag = array_tag;
172
173 jint result;
174 if (array_length == 0) {
175 result = cb->array_primitive_value_callback(class_tag,
176 obj->SizeOf(),
177 &array_tag,
178 0,
179 prim_type,
180 nullptr,
181 const_cast<void*>(user_data));
182 } else {
183 jvmtiError alloc_error;
184 JvmtiUniquePtr<char[]> data = AllocJvmtiUniquePtr<char[]>(env,
185 array_length * component_size,
186 &alloc_error);
187 if (data == nullptr) {
188 // TODO: Not really sure what to do here. Should we abort the iteration and go all the way
189 // back? For now just warn.
190 LOG(WARNING) << "Unable to allocate buffer for array reporting! Silently dropping value.";
191 return 0;
192 }
193
194 memcpy(data.get(), array->GetRawData(component_size, 0), array_length * component_size);
195
196 result = cb->array_primitive_value_callback(class_tag,
197 obj->SizeOf(),
198 &array_tag,
199 array_length,
200 prim_type,
201 data.get(),
202 const_cast<void*>(user_data));
203 }
204
205 if (array_tag != saved_array_tag) {
206 tag_table->Set(obj.Ptr(), array_tag);
207 }
208
209 return result;
210 }
211 return 0;
212}
213
Andreas Gampee7316932017-02-25 09:15:05 -0800214template <typename UserData>
215bool VisitorFalse(art::ObjPtr<art::mirror::Object> obj ATTRIBUTE_UNUSED,
216 art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
217 art::ArtField& field ATTRIBUTE_UNUSED,
218 size_t field_index ATTRIBUTE_UNUSED,
219 UserData* user_data ATTRIBUTE_UNUSED) {
220 return false;
221}
222
Andreas Gampe95114602017-02-28 15:47:44 -0800223template <typename UserData, bool kCallVisitorOnRecursion>
Andreas Gampee7316932017-02-25 09:15:05 -0800224class FieldVisitor {
225 public:
226 // Report the contents of a primitive fields of the given object, if a callback is set.
Andreas Gampe95114602017-02-28 15:47:44 -0800227 template <typename StaticPrimitiveVisitor,
228 typename StaticReferenceVisitor,
229 typename InstancePrimitiveVisitor,
230 typename InstanceReferenceVisitor>
Andreas Gampee7316932017-02-25 09:15:05 -0800231 static bool ReportFields(art::ObjPtr<art::mirror::Object> obj,
232 UserData* user_data,
233 StaticPrimitiveVisitor& static_prim_visitor,
234 StaticReferenceVisitor& static_ref_visitor,
235 InstancePrimitiveVisitor& instance_prim_visitor,
236 InstanceReferenceVisitor& instance_ref_visitor)
237 REQUIRES_SHARED(art::Locks::mutator_lock_) {
238 FieldVisitor fv(user_data);
239
240 if (obj->IsClass()) {
241 // When visiting a class, we only visit the static fields of the given class. No field of
242 // superclasses is visited.
243 art::ObjPtr<art::mirror::Class> klass = obj->AsClass();
244 // Only report fields on resolved classes. We need valid field data.
245 if (!klass->IsResolved()) {
246 return false;
247 }
248 return fv.ReportFieldsImpl(nullptr,
249 obj->AsClass(),
250 obj->AsClass()->IsInterface(),
251 static_prim_visitor,
252 static_ref_visitor,
253 instance_prim_visitor,
254 instance_ref_visitor);
255 } else {
256 // See comment above. Just double-checking here, but an instance *should* mean the class was
257 // resolved.
258 DCHECK(obj->GetClass()->IsResolved() || obj->GetClass()->IsErroneousResolved());
259 return fv.ReportFieldsImpl(obj,
260 obj->GetClass(),
261 false,
262 static_prim_visitor,
263 static_ref_visitor,
264 instance_prim_visitor,
265 instance_ref_visitor);
266 }
267 }
268
269 private:
270 explicit FieldVisitor(UserData* user_data) : user_data_(user_data) {}
271
272 // Report the contents of fields of the given object. If obj is null, report the static fields,
273 // otherwise the instance fields.
Andreas Gampe95114602017-02-28 15:47:44 -0800274 template <typename StaticPrimitiveVisitor,
275 typename StaticReferenceVisitor,
276 typename InstancePrimitiveVisitor,
277 typename InstanceReferenceVisitor>
Andreas Gampee7316932017-02-25 09:15:05 -0800278 bool ReportFieldsImpl(art::ObjPtr<art::mirror::Object> obj,
279 art::ObjPtr<art::mirror::Class> klass,
280 bool skip_java_lang_object,
281 StaticPrimitiveVisitor& static_prim_visitor,
282 StaticReferenceVisitor& static_ref_visitor,
283 InstancePrimitiveVisitor& instance_prim_visitor,
284 InstanceReferenceVisitor& instance_ref_visitor)
285 REQUIRES_SHARED(art::Locks::mutator_lock_) {
286 // Compute the offset of field indices.
287 size_t interface_field_count = CountInterfaceFields(klass);
288
289 size_t tmp;
290 bool aborted = ReportFieldsRecursive(obj,
291 klass,
292 interface_field_count,
293 skip_java_lang_object,
294 static_prim_visitor,
295 static_ref_visitor,
296 instance_prim_visitor,
297 instance_ref_visitor,
298 &tmp);
299 return aborted;
300 }
301
302 // Visit primitive fields in an object (instance). Return true if the visit was aborted.
Andreas Gampe95114602017-02-28 15:47:44 -0800303 template <typename StaticPrimitiveVisitor,
304 typename StaticReferenceVisitor,
305 typename InstancePrimitiveVisitor,
306 typename InstanceReferenceVisitor>
Andreas Gampee7316932017-02-25 09:15:05 -0800307 bool ReportFieldsRecursive(art::ObjPtr<art::mirror::Object> obj,
308 art::ObjPtr<art::mirror::Class> klass,
309 size_t interface_fields,
310 bool skip_java_lang_object,
311 StaticPrimitiveVisitor& static_prim_visitor,
312 StaticReferenceVisitor& static_ref_visitor,
313 InstancePrimitiveVisitor& instance_prim_visitor,
314 InstanceReferenceVisitor& instance_ref_visitor,
315 size_t* field_index_out)
316 REQUIRES_SHARED(art::Locks::mutator_lock_) {
317 DCHECK(klass != nullptr);
318 size_t field_index;
319 if (klass->GetSuperClass() == nullptr) {
320 // j.l.Object. Start with the fields from interfaces.
321 field_index = interface_fields;
322 if (skip_java_lang_object) {
323 *field_index_out = field_index;
324 return false;
325 }
326 } else {
327 // Report superclass fields.
328 if (kCallVisitorOnRecursion) {
329 if (ReportFieldsRecursive(obj,
330 klass->GetSuperClass(),
331 interface_fields,
332 skip_java_lang_object,
333 static_prim_visitor,
334 static_ref_visitor,
335 instance_prim_visitor,
336 instance_ref_visitor,
337 &field_index)) {
338 return true;
339 }
340 } else {
341 // Still call, but with empty visitor. This is required for correct counting.
342 ReportFieldsRecursive(obj,
343 klass->GetSuperClass(),
344 interface_fields,
345 skip_java_lang_object,
346 VisitorFalse<UserData>,
347 VisitorFalse<UserData>,
348 VisitorFalse<UserData>,
349 VisitorFalse<UserData>,
350 &field_index);
351 }
352 }
353
354 // Now visit fields for the current klass.
355
356 for (auto& static_field : klass->GetSFields()) {
357 if (static_field.IsPrimitiveType()) {
358 if (static_prim_visitor(obj,
359 klass,
360 static_field,
361 field_index,
362 user_data_)) {
363 return true;
364 }
365 } else {
366 if (static_ref_visitor(obj,
367 klass,
368 static_field,
369 field_index,
370 user_data_)) {
371 return true;
372 }
373 }
374 field_index++;
375 }
376
377 for (auto& instance_field : klass->GetIFields()) {
378 if (instance_field.IsPrimitiveType()) {
379 if (instance_prim_visitor(obj,
380 klass,
381 instance_field,
382 field_index,
383 user_data_)) {
384 return true;
385 }
386 } else {
387 if (instance_ref_visitor(obj,
388 klass,
389 instance_field,
390 field_index,
391 user_data_)) {
392 return true;
393 }
394 }
395 field_index++;
396 }
397
398 *field_index_out = field_index;
399 return false;
400 }
401
402 // Implements a visit of the implemented interfaces of a given class.
403 template <typename T>
404 struct RecursiveInterfaceVisit {
405 static void VisitStatic(art::Thread* self, art::ObjPtr<art::mirror::Class> klass, T& visitor)
406 REQUIRES_SHARED(art::Locks::mutator_lock_) {
407 RecursiveInterfaceVisit rv;
408 rv.Visit(self, klass, visitor);
409 }
410
411 void Visit(art::Thread* self, art::ObjPtr<art::mirror::Class> klass, T& visitor)
412 REQUIRES_SHARED(art::Locks::mutator_lock_) {
413 // First visit the parent, to get the order right.
414 // (We do this in preparation for actual visiting of interface fields.)
415 if (klass->GetSuperClass() != nullptr) {
416 Visit(self, klass->GetSuperClass(), visitor);
417 }
418 for (uint32_t i = 0; i != klass->NumDirectInterfaces(); ++i) {
419 art::ObjPtr<art::mirror::Class> inf_klass =
420 art::mirror::Class::GetDirectInterface(self, klass, i);
421 DCHECK(inf_klass != nullptr);
422 VisitInterface(self, inf_klass, visitor);
423 }
424 }
425
426 void VisitInterface(art::Thread* self, art::ObjPtr<art::mirror::Class> inf_klass, T& visitor)
427 REQUIRES_SHARED(art::Locks::mutator_lock_) {
428 auto it = visited_interfaces.find(inf_klass.Ptr());
429 if (it != visited_interfaces.end()) {
430 return;
431 }
432 visited_interfaces.insert(inf_klass.Ptr());
433
434 // Let the visitor know about this one. Note that this order is acceptable, as the ordering
435 // of these fields never matters for known visitors.
436 visitor(inf_klass);
437
438 // Now visit the superinterfaces.
439 for (uint32_t i = 0; i != inf_klass->NumDirectInterfaces(); ++i) {
440 art::ObjPtr<art::mirror::Class> super_inf_klass =
441 art::mirror::Class::GetDirectInterface(self, inf_klass, i);
442 DCHECK(super_inf_klass != nullptr);
443 VisitInterface(self, super_inf_klass, visitor);
444 }
445 }
446
447 std::unordered_set<art::mirror::Class*> visited_interfaces;
448 };
449
450 // Counting interface fields. Note that we cannot use the interface table, as that only contains
451 // "non-marker" interfaces (= interfaces with methods).
452 static size_t CountInterfaceFields(art::ObjPtr<art::mirror::Class> klass)
453 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe9e38a502017-03-06 08:19:26 -0800454 // Do we have a cached value?
455 IndexCache tmp;
456 if (gIndexCachingTable.GetTag(klass.Ptr(), &tmp)) {
457 return tmp.interface_fields;
458 }
459
Andreas Gampee7316932017-02-25 09:15:05 -0800460 size_t count = 0;
461 auto visitor = [&count](art::ObjPtr<art::mirror::Class> inf_klass)
462 REQUIRES_SHARED(art::Locks::mutator_lock_) {
463 DCHECK(inf_klass->IsInterface());
464 DCHECK_EQ(0u, inf_klass->NumInstanceFields());
465 count += inf_klass->NumStaticFields();
466 };
467 RecursiveInterfaceVisit<decltype(visitor)>::VisitStatic(art::Thread::Current(), klass, visitor);
Andreas Gampee7316932017-02-25 09:15:05 -0800468
Andreas Gampe9e38a502017-03-06 08:19:26 -0800469 // Store this into the cache.
470 tmp.interface_fields = count;
471 gIndexCachingTable.Set(klass.Ptr(), tmp);
472
473 return count;
Andreas Gampee7316932017-02-25 09:15:05 -0800474 }
475
476 UserData* user_data_;
477};
478
479// Debug helper. Prints the structure of an object.
480template <bool kStatic, bool kRef>
481struct DumpVisitor {
482 static bool Callback(art::ObjPtr<art::mirror::Object> obj ATTRIBUTE_UNUSED,
483 art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
484 art::ArtField& field,
485 size_t field_index,
486 void* user_data ATTRIBUTE_UNUSED)
487 REQUIRES_SHARED(art::Locks::mutator_lock_) {
488 LOG(ERROR) << (kStatic ? "static " : "instance ")
489 << (kRef ? "ref " : "primitive ")
490 << field.PrettyField()
491 << " @ "
492 << field_index;
493 return false;
494 }
495};
496ATTRIBUTE_UNUSED
497void DumpObjectFields(art::ObjPtr<art::mirror::Object> obj)
498 REQUIRES_SHARED(art::Locks::mutator_lock_) {
499 if (obj->IsClass()) {
Andreas Gampe95114602017-02-28 15:47:44 -0800500 FieldVisitor<void, false>:: ReportFields(obj,
501 nullptr,
502 DumpVisitor<true, false>::Callback,
503 DumpVisitor<true, true>::Callback,
504 DumpVisitor<false, false>::Callback,
505 DumpVisitor<false, true>::Callback);
Andreas Gampee7316932017-02-25 09:15:05 -0800506 } else {
Andreas Gampe95114602017-02-28 15:47:44 -0800507 FieldVisitor<void, true>::ReportFields(obj,
508 nullptr,
509 DumpVisitor<true, false>::Callback,
510 DumpVisitor<true, true>::Callback,
511 DumpVisitor<false, false>::Callback,
512 DumpVisitor<false, true>::Callback);
Andreas Gampee7316932017-02-25 09:15:05 -0800513 }
514}
515
516class ReportPrimitiveField {
517 public:
518 static bool Report(art::ObjPtr<art::mirror::Object> obj,
519 ObjectTagTable* tag_table,
520 const jvmtiHeapCallbacks* cb,
521 const void* user_data)
522 REQUIRES_SHARED(art::Locks::mutator_lock_) {
523 if (UNLIKELY(cb->primitive_field_callback != nullptr)) {
524 jlong class_tag = tag_table->GetTagOrZero(obj->GetClass());
525 ReportPrimitiveField rpf(tag_table, class_tag, cb, user_data);
526 if (obj->IsClass()) {
Andreas Gampe95114602017-02-28 15:47:44 -0800527 return FieldVisitor<ReportPrimitiveField, false>::ReportFields(
528 obj,
529 &rpf,
530 ReportPrimitiveFieldCallback<true>,
531 VisitorFalse<ReportPrimitiveField>,
532 VisitorFalse<ReportPrimitiveField>,
533 VisitorFalse<ReportPrimitiveField>);
Andreas Gampee7316932017-02-25 09:15:05 -0800534 } else {
Andreas Gampe95114602017-02-28 15:47:44 -0800535 return FieldVisitor<ReportPrimitiveField, true>::ReportFields(
536 obj,
537 &rpf,
538 VisitorFalse<ReportPrimitiveField>,
539 VisitorFalse<ReportPrimitiveField>,
540 ReportPrimitiveFieldCallback<false>,
541 VisitorFalse<ReportPrimitiveField>);
Andreas Gampee7316932017-02-25 09:15:05 -0800542 }
543 }
544 return false;
545 }
546
547
548 private:
549 ReportPrimitiveField(ObjectTagTable* tag_table,
550 jlong class_tag,
551 const jvmtiHeapCallbacks* cb,
552 const void* user_data)
553 : tag_table_(tag_table), class_tag_(class_tag), cb_(cb), user_data_(user_data) {}
554
555 template <bool kReportStatic>
556 static bool ReportPrimitiveFieldCallback(art::ObjPtr<art::mirror::Object> obj,
557 art::ObjPtr<art::mirror::Class> klass,
558 art::ArtField& field,
559 size_t field_index,
560 ReportPrimitiveField* user_data)
561 REQUIRES_SHARED(art::Locks::mutator_lock_) {
562 art::Primitive::Type art_prim_type = field.GetTypeAsPrimitiveType();
563 jvmtiPrimitiveType prim_type =
564 static_cast<jvmtiPrimitiveType>(art::Primitive::Descriptor(art_prim_type)[0]);
565 DCHECK(prim_type == JVMTI_PRIMITIVE_TYPE_BOOLEAN ||
566 prim_type == JVMTI_PRIMITIVE_TYPE_BYTE ||
567 prim_type == JVMTI_PRIMITIVE_TYPE_CHAR ||
568 prim_type == JVMTI_PRIMITIVE_TYPE_SHORT ||
569 prim_type == JVMTI_PRIMITIVE_TYPE_INT ||
570 prim_type == JVMTI_PRIMITIVE_TYPE_LONG ||
571 prim_type == JVMTI_PRIMITIVE_TYPE_FLOAT ||
572 prim_type == JVMTI_PRIMITIVE_TYPE_DOUBLE);
573 jvmtiHeapReferenceInfo info;
574 info.field.index = field_index;
575
576 jvalue value;
577 memset(&value, 0, sizeof(jvalue));
578 art::ObjPtr<art::mirror::Object> src = kReportStatic ? klass : obj;
579 switch (art_prim_type) {
580 case art::Primitive::Type::kPrimBoolean:
581 value.z = field.GetBoolean(src) == 0 ? JNI_FALSE : JNI_TRUE;
582 break;
583 case art::Primitive::Type::kPrimByte:
584 value.b = field.GetByte(src);
585 break;
586 case art::Primitive::Type::kPrimChar:
587 value.c = field.GetChar(src);
588 break;
589 case art::Primitive::Type::kPrimShort:
590 value.s = field.GetShort(src);
591 break;
592 case art::Primitive::Type::kPrimInt:
593 value.i = field.GetInt(src);
594 break;
595 case art::Primitive::Type::kPrimLong:
596 value.j = field.GetLong(src);
597 break;
598 case art::Primitive::Type::kPrimFloat:
599 value.f = field.GetFloat(src);
600 break;
601 case art::Primitive::Type::kPrimDouble:
602 value.d = field.GetDouble(src);
603 break;
604 case art::Primitive::Type::kPrimVoid:
605 case art::Primitive::Type::kPrimNot: {
606 LOG(FATAL) << "Should not reach here";
607 UNREACHABLE();
608 }
609 }
610
611 jlong obj_tag = user_data->tag_table_->GetTagOrZero(src.Ptr());
612 const jlong saved_obj_tag = obj_tag;
613
614 jint ret = user_data->cb_->primitive_field_callback(kReportStatic
615 ? JVMTI_HEAP_REFERENCE_STATIC_FIELD
616 : JVMTI_HEAP_REFERENCE_FIELD,
617 &info,
618 user_data->class_tag_,
619 &obj_tag,
620 value,
621 prim_type,
622 const_cast<void*>(user_data->user_data_));
623
624 if (saved_obj_tag != obj_tag) {
625 user_data->tag_table_->Set(src.Ptr(), obj_tag);
626 }
627
628 if ((ret & JVMTI_VISIT_ABORT) != 0) {
629 return true;
630 }
631
632 return false;
633 }
634
635 ObjectTagTable* tag_table_;
636 jlong class_tag_;
637 const jvmtiHeapCallbacks* cb_;
638 const void* user_data_;
639};
640
Andreas Gampe6ea06072017-02-24 18:01:19 +0000641struct HeapFilter {
642 explicit HeapFilter(jint heap_filter)
643 : filter_out_tagged((heap_filter & JVMTI_HEAP_FILTER_TAGGED) != 0),
Andreas Gampee54d9922016-10-11 19:55:37 -0700644 filter_out_untagged((heap_filter & JVMTI_HEAP_FILTER_UNTAGGED) != 0),
645 filter_out_class_tagged((heap_filter & JVMTI_HEAP_FILTER_CLASS_TAGGED) != 0),
646 filter_out_class_untagged((heap_filter & JVMTI_HEAP_FILTER_CLASS_UNTAGGED) != 0),
647 any_filter(filter_out_tagged ||
648 filter_out_untagged ||
649 filter_out_class_tagged ||
Andreas Gampe6ea06072017-02-24 18:01:19 +0000650 filter_out_class_untagged) {
Andreas Gampee54d9922016-10-11 19:55:37 -0700651 }
652
Andreas Gampe6ea06072017-02-24 18:01:19 +0000653 bool ShouldReportByHeapFilter(jlong tag, jlong class_tag) const {
Andreas Gampee54d9922016-10-11 19:55:37 -0700654 if (!any_filter) {
655 return true;
656 }
657
658 if ((tag == 0 && filter_out_untagged) || (tag != 0 && filter_out_tagged)) {
659 return false;
660 }
661
662 if ((class_tag == 0 && filter_out_class_untagged) ||
663 (class_tag != 0 && filter_out_class_tagged)) {
664 return false;
665 }
666
667 return true;
668 }
669
Andreas Gampee54d9922016-10-11 19:55:37 -0700670 const bool filter_out_tagged;
671 const bool filter_out_untagged;
672 const bool filter_out_class_tagged;
673 const bool filter_out_class_untagged;
674 const bool any_filter;
Andreas Gampe6ea06072017-02-24 18:01:19 +0000675};
676
677} // namespace
678
Andreas Gampe9e38a502017-03-06 08:19:26 -0800679void HeapUtil::Register() {
680 art::Runtime::Current()->AddSystemWeakHolder(&gIndexCachingTable);
681}
682
683void HeapUtil::Unregister() {
684 art::Runtime::Current()->RemoveSystemWeakHolder(&gIndexCachingTable);
685}
686
Alex Lightbbbcb532018-08-30 12:50:27 -0700687jvmtiError HeapUtil::IterateOverInstancesOfClass(jvmtiEnv* env,
688 jclass klass,
689 jvmtiHeapObjectFilter filter,
690 jvmtiHeapObjectCallback cb,
691 const void* user_data) {
692 if (cb == nullptr || klass == nullptr) {
693 return ERR(NULL_POINTER);
694 }
695
696 art::Thread* self = art::Thread::Current();
697 art::ScopedObjectAccess soa(self); // Now we know we have the shared lock.
698 art::StackHandleScope<1> hs(self);
699
700 art::ObjPtr<art::mirror::Object> klass_ptr(soa.Decode<art::mirror::Class>(klass));
701 if (!klass_ptr->IsClass()) {
702 return ERR(INVALID_CLASS);
703 }
704 art::Handle<art::mirror::Class> filter_klass(hs.NewHandle(klass_ptr->AsClass()));
Alex Lightbbbcb532018-08-30 12:50:27 -0700705 ObjectTagTable* tag_table = ArtJvmTiEnv::AsArtJvmTiEnv(env)->object_tag_table.get();
706 bool stop_reports = false;
707 auto visitor = [&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
708 // Early return, as we can't really stop visiting.
709 if (stop_reports) {
710 return;
711 }
712
713 art::ScopedAssertNoThreadSuspension no_suspension("IterateOverInstancesOfClass");
714
715 art::ObjPtr<art::mirror::Class> klass = obj->GetClass();
716
717 if (filter_klass != nullptr && !filter_klass->IsAssignableFrom(klass)) {
718 return;
719 }
720
721 jlong tag = 0;
722 tag_table->GetTag(obj, &tag);
723 if ((filter != JVMTI_HEAP_OBJECT_EITHER) &&
724 ((tag == 0 && filter == JVMTI_HEAP_OBJECT_TAGGED) ||
725 (tag != 0 && filter == JVMTI_HEAP_OBJECT_UNTAGGED))) {
726 return;
727 }
728
729 jlong class_tag = 0;
730 tag_table->GetTag(klass.Ptr(), &class_tag);
731
732 jlong saved_tag = tag;
733 jint ret = cb(class_tag, obj->SizeOf(), &tag, const_cast<void*>(user_data));
734
735 stop_reports = (ret == JVMTI_ITERATION_ABORT);
736
737 if (tag != saved_tag) {
738 tag_table->Set(obj, tag);
739 }
740 };
741 art::Runtime::Current()->GetHeap()->VisitObjects(visitor);
742
743 return OK;
744}
745
Andreas Gampe1c158a02017-07-13 17:26:19 -0700746template <typename T>
747static jvmtiError DoIterateThroughHeap(T fn,
748 jvmtiEnv* env,
749 ObjectTagTable* tag_table,
750 jint heap_filter_int,
751 jclass klass,
752 const jvmtiHeapCallbacks* callbacks,
753 const void* user_data) {
754 if (callbacks == nullptr) {
755 return ERR(NULL_POINTER);
Andreas Gampe6ea06072017-02-24 18:01:19 +0000756 }
757
Andreas Gampe1c158a02017-07-13 17:26:19 -0700758 art::Thread* self = art::Thread::Current();
759 art::ScopedObjectAccess soa(self); // Now we know we have the shared lock.
Andreas Gampef787fd32017-05-09 16:04:20 -0700760
Andreas Gampe1c158a02017-07-13 17:26:19 -0700761 bool stop_reports = false;
762 const HeapFilter heap_filter(heap_filter_int);
763 art::ObjPtr<art::mirror::Class> filter_klass = soa.Decode<art::mirror::Class>(klass);
764 auto visitor = [&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampef787fd32017-05-09 16:04:20 -0700765 // Early return, as we can't really stop visiting.
766 if (stop_reports) {
767 return;
768 }
769
770 art::ScopedAssertNoThreadSuspension no_suspension("IterateThroughHeapCallback");
771
772 jlong tag = 0;
773 tag_table->GetTag(obj, &tag);
774
775 jlong class_tag = 0;
776 art::ObjPtr<art::mirror::Class> klass = obj->GetClass();
777 tag_table->GetTag(klass.Ptr(), &class_tag);
778 // For simplicity, even if we find a tag = 0, assume 0 = not tagged.
779
780 if (!heap_filter.ShouldReportByHeapFilter(tag, class_tag)) {
781 return;
782 }
783
784 if (filter_klass != nullptr) {
785 if (filter_klass != klass) {
786 return;
787 }
788 }
789
790 jlong size = obj->SizeOf();
791
792 jint length = -1;
793 if (obj->IsArrayInstance()) {
794 length = obj->AsArray()->GetLength();
795 }
796
797 jlong saved_tag = tag;
Andreas Gampe1c158a02017-07-13 17:26:19 -0700798 jint ret = fn(obj, callbacks, class_tag, size, &tag, length, const_cast<void*>(user_data));
Andreas Gampef787fd32017-05-09 16:04:20 -0700799
800 if (tag != saved_tag) {
801 tag_table->Set(obj, tag);
802 }
803
804 stop_reports = (ret & JVMTI_VISIT_ABORT) != 0;
805
806 if (!stop_reports) {
807 jint string_ret = ReportString(obj, env, tag_table, callbacks, user_data);
808 stop_reports = (string_ret & JVMTI_VISIT_ABORT) != 0;
809 }
810
811 if (!stop_reports) {
812 jint array_ret = ReportPrimitiveArray(obj, env, tag_table, callbacks, user_data);
813 stop_reports = (array_ret & JVMTI_VISIT_ABORT) != 0;
814 }
815
816 if (!stop_reports) {
817 stop_reports = ReportPrimitiveField::Report(obj, tag_table, callbacks, user_data);
818 }
Andreas Gampe1c158a02017-07-13 17:26:19 -0700819 };
820 art::Runtime::Current()->GetHeap()->VisitObjects(visitor);
Andreas Gampee54d9922016-10-11 19:55:37 -0700821
822 return ERR(NONE);
823}
824
Andreas Gampef787fd32017-05-09 16:04:20 -0700825jvmtiError HeapUtil::IterateThroughHeap(jvmtiEnv* env,
826 jint heap_filter,
827 jclass klass,
828 const jvmtiHeapCallbacks* callbacks,
829 const void* user_data) {
830 auto JvmtiIterateHeap = [](art::mirror::Object* obj ATTRIBUTE_UNUSED,
831 const jvmtiHeapCallbacks* cb_callbacks,
832 jlong class_tag,
833 jlong size,
834 jlong* tag,
835 jint length,
836 void* cb_user_data)
837 REQUIRES_SHARED(art::Locks::mutator_lock_) {
838 return cb_callbacks->heap_iteration_callback(class_tag,
839 size,
840 tag,
841 length,
842 cb_user_data);
843 };
844 return DoIterateThroughHeap(JvmtiIterateHeap,
845 env,
846 ArtJvmTiEnv::AsArtJvmTiEnv(env)->object_tag_table.get(),
847 heap_filter,
848 klass,
849 callbacks,
850 user_data);
851}
852
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100853class FollowReferencesHelper final {
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700854 public:
855 FollowReferencesHelper(HeapUtil* h,
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800856 jvmtiEnv* jvmti_env,
Andreas Gampe638a6932016-12-02 19:11:17 -0800857 art::ObjPtr<art::mirror::Object> initial_object,
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700858 const jvmtiHeapCallbacks* callbacks,
Andreas Gampe38da9f22017-02-20 13:35:36 -0800859 art::ObjPtr<art::mirror::Class> class_filter,
Andreas Gampe6ea06072017-02-24 18:01:19 +0000860 jint heap_filter,
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700861 const void* user_data)
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800862 : env(jvmti_env),
863 tag_table_(h->GetTags()),
Andreas Gampe638a6932016-12-02 19:11:17 -0800864 initial_object_(initial_object),
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700865 callbacks_(callbacks),
Andreas Gampe38da9f22017-02-20 13:35:36 -0800866 class_filter_(class_filter),
Andreas Gampe6ea06072017-02-24 18:01:19 +0000867 heap_filter_(heap_filter),
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700868 user_data_(user_data),
869 start_(0),
870 stop_reports_(false) {
871 }
872
873 void Init()
874 REQUIRES_SHARED(art::Locks::mutator_lock_)
875 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
Andreas Gampe638a6932016-12-02 19:11:17 -0800876 if (initial_object_.IsNull()) {
877 CollectAndReportRootsVisitor carrv(this, tag_table_, &worklist_, &visited_);
Andreas Gampef10dfcd2016-12-02 14:42:33 -0800878
879 // We need precise info (e.g., vregs).
880 constexpr art::VisitRootFlags kRootFlags = static_cast<art::VisitRootFlags>(
881 art::VisitRootFlags::kVisitRootFlagAllRoots | art::VisitRootFlags::kVisitRootFlagPrecise);
882 art::Runtime::Current()->VisitRoots(&carrv, kRootFlags);
883
Andreas Gampe638a6932016-12-02 19:11:17 -0800884 art::Runtime::Current()->VisitImageRoots(&carrv);
885 stop_reports_ = carrv.IsStopReports();
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700886
Andreas Gampe638a6932016-12-02 19:11:17 -0800887 if (stop_reports_) {
888 worklist_.clear();
889 }
890 } else {
891 visited_.insert(initial_object_.Ptr());
892 worklist_.push_back(initial_object_.Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700893 }
894 }
895
896 void Work()
897 REQUIRES_SHARED(art::Locks::mutator_lock_)
898 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
899 // Currently implemented as a BFS. To lower overhead, we don't erase elements immediately
900 // from the head of the work list, instead postponing until there's a gap that's "large."
901 //
902 // Alternatively, we can implement a DFS and use the work list as a stack.
903 while (start_ < worklist_.size()) {
904 art::mirror::Object* cur_obj = worklist_[start_];
905 start_++;
906
907 if (start_ >= kMaxStart) {
908 worklist_.erase(worklist_.begin(), worklist_.begin() + start_);
909 start_ = 0;
910 }
911
912 VisitObject(cur_obj);
913
914 if (stop_reports_) {
915 break;
916 }
917 }
918 }
919
920 private:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100921 class CollectAndReportRootsVisitor final : public art::RootVisitor {
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700922 public:
923 CollectAndReportRootsVisitor(FollowReferencesHelper* helper,
924 ObjectTagTable* tag_table,
925 std::vector<art::mirror::Object*>* worklist,
926 std::unordered_set<art::mirror::Object*>* visited)
927 : helper_(helper),
928 tag_table_(tag_table),
929 worklist_(worklist),
930 visited_(visited),
931 stop_reports_(false) {}
932
933 void VisitRoots(art::mirror::Object*** roots, size_t count, const art::RootInfo& info)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100934 override
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700935 REQUIRES_SHARED(art::Locks::mutator_lock_)
936 REQUIRES(!*helper_->tag_table_->GetAllowDisallowLock()) {
937 for (size_t i = 0; i != count; ++i) {
938 AddRoot(*roots[i], info);
939 }
940 }
941
942 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
943 size_t count,
944 const art::RootInfo& info)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100945 override REQUIRES_SHARED(art::Locks::mutator_lock_)
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700946 REQUIRES(!*helper_->tag_table_->GetAllowDisallowLock()) {
947 for (size_t i = 0; i != count; ++i) {
948 AddRoot(roots[i]->AsMirrorPtr(), info);
949 }
950 }
951
952 bool IsStopReports() {
953 return stop_reports_;
954 }
955
956 private:
957 void AddRoot(art::mirror::Object* root_obj, const art::RootInfo& info)
958 REQUIRES_SHARED(art::Locks::mutator_lock_)
959 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
Andreas Gampec756f082017-03-29 17:58:28 -0700960 if (stop_reports_) {
961 return;
962 }
963 bool add_to_worklist = ReportRoot(root_obj, info);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700964 // We use visited_ to mark roots already so we do not need another set.
965 if (visited_->find(root_obj) == visited_->end()) {
Andreas Gampec756f082017-03-29 17:58:28 -0700966 if (add_to_worklist) {
Andreas Gampee0f8ed92017-04-13 16:52:23 -0700967 visited_->insert(root_obj);
Andreas Gampec756f082017-03-29 17:58:28 -0700968 worklist_->push_back(root_obj);
969 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700970 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700971 }
972
Andreas Gampe93c30902016-11-18 13:30:30 -0800973 // Remove NO_THREAD_SAFETY_ANALYSIS once ASSERT_CAPABILITY works correctly.
974 art::Thread* FindThread(const art::RootInfo& info) NO_THREAD_SAFETY_ANALYSIS {
975 art::Locks::thread_list_lock_->AssertExclusiveHeld(art::Thread::Current());
976 return art::Runtime::Current()->GetThreadList()->FindThreadByThreadId(info.GetThreadId());
977 }
978
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700979 jvmtiHeapReferenceKind GetReferenceKind(const art::RootInfo& info,
980 jvmtiHeapReferenceInfo* ref_info)
981 REQUIRES_SHARED(art::Locks::mutator_lock_) {
982 // TODO: Fill in ref_info.
983 memset(ref_info, 0, sizeof(jvmtiHeapReferenceInfo));
984
985 switch (info.GetType()) {
986 case art::RootType::kRootJNIGlobal:
987 return JVMTI_HEAP_REFERENCE_JNI_GLOBAL;
988
989 case art::RootType::kRootJNILocal:
Andreas Gampe93c30902016-11-18 13:30:30 -0800990 {
991 uint32_t thread_id = info.GetThreadId();
992 ref_info->jni_local.thread_id = thread_id;
993
994 art::Thread* thread = FindThread(info);
995 if (thread != nullptr) {
Andreas Gampe202f85a2017-02-06 10:23:26 -0800996 art::mirror::Object* thread_obj;
Andreas Gampe93c30902016-11-18 13:30:30 -0800997 if (thread->IsStillStarting()) {
998 thread_obj = nullptr;
999 } else {
Andreas Gampe202f85a2017-02-06 10:23:26 -08001000 thread_obj = thread->GetPeerFromOtherThread();
Andreas Gampe93c30902016-11-18 13:30:30 -08001001 }
1002 if (thread_obj != nullptr) {
1003 ref_info->jni_local.thread_tag = tag_table_->GetTagOrZero(thread_obj);
1004 }
1005 }
1006
1007 // TODO: We don't have this info.
1008 if (thread != nullptr) {
1009 ref_info->jni_local.depth = 0;
Andreas Gampe6e897762018-10-16 13:09:32 -07001010 art::ArtMethod* method = thread->GetCurrentMethod(nullptr,
1011 /* check_suspended= */ true,
1012 /* abort_on_error= */ false);
Andreas Gampe93c30902016-11-18 13:30:30 -08001013 if (method != nullptr) {
1014 ref_info->jni_local.method = art::jni::EncodeArtMethod(method);
1015 }
1016 }
1017
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001018 return JVMTI_HEAP_REFERENCE_JNI_LOCAL;
Andreas Gampe93c30902016-11-18 13:30:30 -08001019 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001020
1021 case art::RootType::kRootJavaFrame:
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001022 {
1023 uint32_t thread_id = info.GetThreadId();
1024 ref_info->stack_local.thread_id = thread_id;
1025
1026 art::Thread* thread = FindThread(info);
1027 if (thread != nullptr) {
Andreas Gampe202f85a2017-02-06 10:23:26 -08001028 art::mirror::Object* thread_obj;
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001029 if (thread->IsStillStarting()) {
1030 thread_obj = nullptr;
1031 } else {
Andreas Gampe202f85a2017-02-06 10:23:26 -08001032 thread_obj = thread->GetPeerFromOtherThread();
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001033 }
1034 if (thread_obj != nullptr) {
1035 ref_info->stack_local.thread_tag = tag_table_->GetTagOrZero(thread_obj);
1036 }
1037 }
1038
1039 auto& java_info = static_cast<const art::JavaFrameRootInfo&>(info);
Alex Light0054aa52019-09-10 16:46:48 -07001040 size_t vreg = java_info.GetVReg();
1041 ref_info->stack_local.slot = static_cast<jint>(
1042 vreg <= art::JavaFrameRootInfo::kMaxVReg ? vreg : -1);
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001043 const art::StackVisitor* visitor = java_info.GetVisitor();
1044 ref_info->stack_local.location =
Andreas Gampe6e897762018-10-16 13:09:32 -07001045 static_cast<jlocation>(visitor->GetDexPc(/* abort_on_failure= */ false));
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001046 ref_info->stack_local.depth = static_cast<jint>(visitor->GetFrameDepth());
1047 art::ArtMethod* method = visitor->GetMethod();
1048 if (method != nullptr) {
1049 ref_info->stack_local.method = art::jni::EncodeArtMethod(method);
1050 }
1051
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001052 return JVMTI_HEAP_REFERENCE_STACK_LOCAL;
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001053 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001054
1055 case art::RootType::kRootNativeStack:
1056 case art::RootType::kRootThreadBlock:
1057 case art::RootType::kRootThreadObject:
1058 return JVMTI_HEAP_REFERENCE_THREAD;
1059
1060 case art::RootType::kRootStickyClass:
1061 case art::RootType::kRootInternedString:
1062 // Note: this isn't a root in the RI.
1063 return JVMTI_HEAP_REFERENCE_SYSTEM_CLASS;
1064
1065 case art::RootType::kRootMonitorUsed:
1066 case art::RootType::kRootJNIMonitor:
1067 return JVMTI_HEAP_REFERENCE_MONITOR;
1068
1069 case art::RootType::kRootFinalizing:
1070 case art::RootType::kRootDebugger:
1071 case art::RootType::kRootReferenceCleanup:
1072 case art::RootType::kRootVMInternal:
1073 case art::RootType::kRootUnknown:
1074 return JVMTI_HEAP_REFERENCE_OTHER;
1075 }
1076 LOG(FATAL) << "Unreachable";
1077 UNREACHABLE();
1078 }
1079
Andreas Gampec756f082017-03-29 17:58:28 -07001080 bool ReportRoot(art::mirror::Object* root_obj, const art::RootInfo& info)
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001081 REQUIRES_SHARED(art::Locks::mutator_lock_)
1082 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1083 jvmtiHeapReferenceInfo ref_info;
1084 jvmtiHeapReferenceKind kind = GetReferenceKind(info, &ref_info);
1085 jint result = helper_->ReportReference(kind, &ref_info, nullptr, root_obj);
1086 if ((result & JVMTI_VISIT_ABORT) != 0) {
1087 stop_reports_ = true;
1088 }
Andreas Gampec756f082017-03-29 17:58:28 -07001089 return (result & JVMTI_VISIT_OBJECTS) != 0;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001090 }
1091
1092 private:
1093 FollowReferencesHelper* helper_;
1094 ObjectTagTable* tag_table_;
1095 std::vector<art::mirror::Object*>* worklist_;
1096 std::unordered_set<art::mirror::Object*>* visited_;
1097 bool stop_reports_;
1098 };
1099
1100 void VisitObject(art::mirror::Object* obj)
1101 REQUIRES_SHARED(art::Locks::mutator_lock_)
1102 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1103 if (obj->IsClass()) {
Vladimir Marko4617d582019-03-28 13:48:31 +00001104 VisitClass(obj->AsClass().Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001105 return;
1106 }
1107 if (obj->IsArrayInstance()) {
1108 VisitArray(obj);
1109 return;
1110 }
1111
Andreas Gampe95114602017-02-28 15:47:44 -08001112 // All instance fields.
1113 auto report_instance_field = [&](art::ObjPtr<art::mirror::Object> src,
1114 art::ObjPtr<art::mirror::Class> obj_klass ATTRIBUTE_UNUSED,
1115 art::ArtField& field,
1116 size_t field_index,
1117 void* user_data ATTRIBUTE_UNUSED)
1118 REQUIRES_SHARED(art::Locks::mutator_lock_)
1119 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1120 art::ObjPtr<art::mirror::Object> field_value = field.GetObject(src);
1121 if (field_value != nullptr) {
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001122 jvmtiHeapReferenceInfo reference_info;
1123 memset(&reference_info, 0, sizeof(reference_info));
1124
Andreas Gampe95114602017-02-28 15:47:44 -08001125 reference_info.field.index = field_index;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001126
1127 jvmtiHeapReferenceKind kind =
Andreas Gampe95114602017-02-28 15:47:44 -08001128 field.GetOffset().Int32Value() == art::mirror::Object::ClassOffset().Int32Value()
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001129 ? JVMTI_HEAP_REFERENCE_CLASS
1130 : JVMTI_HEAP_REFERENCE_FIELD;
1131 const jvmtiHeapReferenceInfo* reference_info_ptr =
1132 kind == JVMTI_HEAP_REFERENCE_CLASS ? nullptr : &reference_info;
1133
Andreas Gampe95114602017-02-28 15:47:44 -08001134 return !ReportReferenceMaybeEnqueue(kind, reference_info_ptr, src.Ptr(), field_value.Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001135 }
Andreas Gampe95114602017-02-28 15:47:44 -08001136 return false;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001137 };
Andreas Gampe95114602017-02-28 15:47:44 -08001138 stop_reports_ = FieldVisitor<void, true>::ReportFields(obj,
1139 nullptr,
1140 VisitorFalse<void>,
1141 VisitorFalse<void>,
1142 VisitorFalse<void>,
1143 report_instance_field);
1144 if (stop_reports_) {
1145 return;
Andreas Gampe3ec8e402017-02-21 15:49:53 -08001146 }
Andreas Gampee7316932017-02-25 09:15:05 -08001147
Andreas Gampe95114602017-02-28 15:47:44 -08001148 jint string_ret = ReportString(obj, env, tag_table_, callbacks_, user_data_);
1149 stop_reports_ = (string_ret & JVMTI_VISIT_ABORT) != 0;
1150 if (stop_reports_) {
1151 return;
Andreas Gampee7316932017-02-25 09:15:05 -08001152 }
Andreas Gampe95114602017-02-28 15:47:44 -08001153
1154 stop_reports_ = ReportPrimitiveField::Report(obj, tag_table_, callbacks_, user_data_);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001155 }
1156
1157 void VisitArray(art::mirror::Object* array)
1158 REQUIRES_SHARED(art::Locks::mutator_lock_)
1159 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1160 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_CLASS,
1161 nullptr,
1162 array,
1163 array->GetClass());
1164 if (stop_reports_) {
1165 return;
1166 }
1167
1168 if (array->IsObjectArray()) {
Vladimir Marko4617d582019-03-28 13:48:31 +00001169 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> obj_array =
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001170 array->AsObjectArray<art::mirror::Object>();
Alex Lighta9bbc082019-11-14 14:51:41 -08001171 for (auto elem_pair : art::ZipCount(obj_array->Iterate())) {
1172 if (elem_pair.first != nullptr) {
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001173 jvmtiHeapReferenceInfo reference_info;
Alex Lighta9bbc082019-11-14 14:51:41 -08001174 reference_info.array.index = elem_pair.second;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001175 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT,
1176 &reference_info,
1177 array,
Alex Lighta9bbc082019-11-14 14:51:41 -08001178 elem_pair.first.Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001179 if (stop_reports_) {
1180 break;
1181 }
1182 }
1183 }
Andreas Gampebecd6ad2017-02-22 19:20:37 -08001184 } else {
1185 if (!stop_reports_) {
1186 jint array_ret = ReportPrimitiveArray(array, env, tag_table_, callbacks_, user_data_);
1187 stop_reports_ = (array_ret & JVMTI_VISIT_ABORT) != 0;
1188 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001189 }
1190 }
1191
1192 void VisitClass(art::mirror::Class* klass)
1193 REQUIRES_SHARED(art::Locks::mutator_lock_)
1194 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1195 // TODO: Are erroneous classes reported? Are non-prepared ones? For now, just use resolved ones.
1196 if (!klass->IsResolved()) {
1197 return;
1198 }
1199
1200 // Superclass.
1201 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_SUPERCLASS,
1202 nullptr,
1203 klass,
Andreas Gampe98104992018-10-16 12:49:47 -07001204 klass->GetSuperClass().Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001205 if (stop_reports_) {
1206 return;
1207 }
1208
1209 // Directly implemented or extended interfaces.
1210 art::Thread* self = art::Thread::Current();
1211 art::StackHandleScope<1> hs(self);
1212 art::Handle<art::mirror::Class> h_klass(hs.NewHandle<art::mirror::Class>(klass));
1213 for (size_t i = 0; i < h_klass->NumDirectInterfaces(); ++i) {
1214 art::ObjPtr<art::mirror::Class> inf_klass =
Vladimir Marko19a4d372016-12-08 14:41:46 +00001215 art::mirror::Class::ResolveDirectInterface(self, h_klass, i);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001216 if (inf_klass == nullptr) {
1217 // TODO: With a resolved class this should not happen...
1218 self->ClearException();
1219 break;
1220 }
1221
1222 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_INTERFACE,
1223 nullptr,
1224 klass,
1225 inf_klass.Ptr());
1226 if (stop_reports_) {
1227 return;
1228 }
1229 }
1230
1231 // Classloader.
1232 // TODO: What about the boot classpath loader? We'll skip for now, but do we have to find the
1233 // fake BootClassLoader?
1234 if (klass->GetClassLoader() != nullptr) {
1235 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_CLASS_LOADER,
1236 nullptr,
1237 klass,
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001238 klass->GetClassLoader().Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001239 if (stop_reports_) {
1240 return;
1241 }
1242 }
1243 DCHECK_EQ(h_klass.Get(), klass);
1244
1245 // Declared static fields.
Andreas Gampe95114602017-02-28 15:47:44 -08001246 auto report_static_field = [&](art::ObjPtr<art::mirror::Object> obj ATTRIBUTE_UNUSED,
1247 art::ObjPtr<art::mirror::Class> obj_klass,
1248 art::ArtField& field,
1249 size_t field_index,
1250 void* user_data ATTRIBUTE_UNUSED)
1251 REQUIRES_SHARED(art::Locks::mutator_lock_)
1252 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1253 art::ObjPtr<art::mirror::Object> field_value = field.GetObject(obj_klass);
1254 if (field_value != nullptr) {
1255 jvmtiHeapReferenceInfo reference_info;
1256 memset(&reference_info, 0, sizeof(reference_info));
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001257
Andreas Gampe95114602017-02-28 15:47:44 -08001258 reference_info.field.index = static_cast<jint>(field_index);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001259
Andreas Gampe95114602017-02-28 15:47:44 -08001260 return !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_STATIC_FIELD,
1261 &reference_info,
1262 obj_klass.Ptr(),
1263 field_value.Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001264 }
Andreas Gampe95114602017-02-28 15:47:44 -08001265 return false;
1266 };
1267 stop_reports_ = FieldVisitor<void, false>::ReportFields(klass,
1268 nullptr,
1269 VisitorFalse<void>,
1270 report_static_field,
1271 VisitorFalse<void>,
1272 VisitorFalse<void>);
1273 if (stop_reports_) {
1274 return;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001275 }
Andreas Gampee7316932017-02-25 09:15:05 -08001276
Andreas Gampe95114602017-02-28 15:47:44 -08001277 stop_reports_ = ReportPrimitiveField::Report(klass, tag_table_, callbacks_, user_data_);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001278 }
1279
1280 void MaybeEnqueue(art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1281 if (visited_.find(obj) == visited_.end()) {
1282 worklist_.push_back(obj);
1283 visited_.insert(obj);
1284 }
1285 }
1286
1287 bool ReportReferenceMaybeEnqueue(jvmtiHeapReferenceKind kind,
1288 const jvmtiHeapReferenceInfo* reference_info,
1289 art::mirror::Object* referree,
1290 art::mirror::Object* referrer)
1291 REQUIRES_SHARED(art::Locks::mutator_lock_)
1292 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1293 jint result = ReportReference(kind, reference_info, referree, referrer);
1294 if ((result & JVMTI_VISIT_ABORT) == 0) {
1295 if ((result & JVMTI_VISIT_OBJECTS) != 0) {
1296 MaybeEnqueue(referrer);
1297 }
1298 return true;
1299 } else {
1300 return false;
1301 }
1302 }
1303
1304 jint ReportReference(jvmtiHeapReferenceKind kind,
1305 const jvmtiHeapReferenceInfo* reference_info,
1306 art::mirror::Object* referrer,
1307 art::mirror::Object* referree)
1308 REQUIRES_SHARED(art::Locks::mutator_lock_)
1309 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1310 if (referree == nullptr || stop_reports_) {
1311 return 0;
1312 }
1313
Andreas Gampe38da9f22017-02-20 13:35:36 -08001314 if (UNLIKELY(class_filter_ != nullptr) && class_filter_ != referree->GetClass()) {
1315 return JVMTI_VISIT_OBJECTS;
1316 }
1317
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001318 const jlong class_tag = tag_table_->GetTagOrZero(referree->GetClass());
Andreas Gampe6ea06072017-02-24 18:01:19 +00001319 jlong tag = tag_table_->GetTagOrZero(referree);
1320
1321 if (!heap_filter_.ShouldReportByHeapFilter(tag, class_tag)) {
1322 return JVMTI_VISIT_OBJECTS;
1323 }
1324
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001325 const jlong referrer_class_tag =
1326 referrer == nullptr ? 0 : tag_table_->GetTagOrZero(referrer->GetClass());
1327 const jlong size = static_cast<jlong>(referree->SizeOf());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001328 jlong saved_tag = tag;
1329 jlong referrer_tag = 0;
1330 jlong saved_referrer_tag = 0;
1331 jlong* referrer_tag_ptr;
1332 if (referrer == nullptr) {
1333 referrer_tag_ptr = nullptr;
1334 } else {
1335 if (referrer == referree) {
1336 referrer_tag_ptr = &tag;
1337 } else {
1338 referrer_tag = saved_referrer_tag = tag_table_->GetTagOrZero(referrer);
1339 referrer_tag_ptr = &referrer_tag;
1340 }
1341 }
Andreas Gampe38da9f22017-02-20 13:35:36 -08001342
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001343 jint length = -1;
1344 if (referree->IsArrayInstance()) {
1345 length = referree->AsArray()->GetLength();
1346 }
1347
1348 jint result = callbacks_->heap_reference_callback(kind,
1349 reference_info,
1350 class_tag,
1351 referrer_class_tag,
1352 size,
1353 &tag,
1354 referrer_tag_ptr,
1355 length,
1356 const_cast<void*>(user_data_));
1357
1358 if (tag != saved_tag) {
1359 tag_table_->Set(referree, tag);
1360 }
1361 if (referrer_tag != saved_referrer_tag) {
1362 tag_table_->Set(referrer, referrer_tag);
1363 }
1364
1365 return result;
1366 }
1367
Andreas Gampe3ec8e402017-02-21 15:49:53 -08001368 jvmtiEnv* env;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001369 ObjectTagTable* tag_table_;
Andreas Gampe638a6932016-12-02 19:11:17 -08001370 art::ObjPtr<art::mirror::Object> initial_object_;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001371 const jvmtiHeapCallbacks* callbacks_;
Andreas Gampe38da9f22017-02-20 13:35:36 -08001372 art::ObjPtr<art::mirror::Class> class_filter_;
Andreas Gampe6ea06072017-02-24 18:01:19 +00001373 const HeapFilter heap_filter_;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001374 const void* user_data_;
1375
1376 std::vector<art::mirror::Object*> worklist_;
1377 size_t start_;
1378 static constexpr size_t kMaxStart = 1000000U;
1379
1380 std::unordered_set<art::mirror::Object*> visited_;
1381
1382 bool stop_reports_;
1383
1384 friend class CollectAndReportRootsVisitor;
1385};
1386
Andreas Gampe3ec8e402017-02-21 15:49:53 -08001387jvmtiError HeapUtil::FollowReferences(jvmtiEnv* env,
Andreas Gampe6ea06072017-02-24 18:01:19 +00001388 jint heap_filter,
Andreas Gampe38da9f22017-02-20 13:35:36 -08001389 jclass klass,
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001390 jobject initial_object,
1391 const jvmtiHeapCallbacks* callbacks,
1392 const void* user_data) {
1393 if (callbacks == nullptr) {
1394 return ERR(NULL_POINTER);
1395 }
1396
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001397 art::Thread* self = art::Thread::Current();
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001398
Andreas Gampe638a6932016-12-02 19:11:17 -08001399 art::gc::Heap* heap = art::Runtime::Current()->GetHeap();
1400 if (heap->IsGcConcurrentAndMoving()) {
1401 // Need to take a heap dump while GC isn't running. See the
1402 // comment in Heap::VisitObjects().
1403 heap->IncrementDisableMovingGC(self);
1404 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001405 {
Andreas Gampe638a6932016-12-02 19:11:17 -08001406 art::ScopedObjectAccess soa(self); // Now we know we have the shared lock.
Alex Light79d6c802019-06-27 15:50:11 +00001407 art::jni::ScopedEnableSuspendAllJniIdQueries sjni; // make sure we can get JNI ids.
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001408 art::ScopedThreadSuspension sts(self, art::kWaitingForVisitObjects);
1409 art::ScopedSuspendAll ssa("FollowReferences");
1410
Andreas Gampe38da9f22017-02-20 13:35:36 -08001411 art::ObjPtr<art::mirror::Class> class_filter = klass == nullptr
1412 ? nullptr
1413 : art::ObjPtr<art::mirror::Class>::DownCast(self->DecodeJObject(klass));
Andreas Gampe638a6932016-12-02 19:11:17 -08001414 FollowReferencesHelper frh(this,
Andreas Gampe3ec8e402017-02-21 15:49:53 -08001415 env,
Andreas Gampe638a6932016-12-02 19:11:17 -08001416 self->DecodeJObject(initial_object),
1417 callbacks,
Andreas Gampe38da9f22017-02-20 13:35:36 -08001418 class_filter,
Andreas Gampe6ea06072017-02-24 18:01:19 +00001419 heap_filter,
Andreas Gampe638a6932016-12-02 19:11:17 -08001420 user_data);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001421 frh.Init();
1422 frh.Work();
1423 }
Andreas Gampe638a6932016-12-02 19:11:17 -08001424 if (heap->IsGcConcurrentAndMoving()) {
1425 heap->DecrementDisableMovingGC(self);
1426 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001427
1428 return ERR(NONE);
1429}
1430
Andreas Gampeaa8b60c2016-10-12 12:51:25 -07001431jvmtiError HeapUtil::GetLoadedClasses(jvmtiEnv* env,
1432 jint* class_count_ptr,
1433 jclass** classes_ptr) {
1434 if (class_count_ptr == nullptr || classes_ptr == nullptr) {
1435 return ERR(NULL_POINTER);
1436 }
1437
1438 class ReportClassVisitor : public art::ClassVisitor {
1439 public:
1440 explicit ReportClassVisitor(art::Thread* self) : self_(self) {}
1441
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001442 bool operator()(art::ObjPtr<art::mirror::Class> klass)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001443 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightf8a4a2c2017-06-22 08:43:37 -07001444 if (klass->IsLoaded() || klass->IsErroneous()) {
1445 classes_.push_back(self_->GetJniEnv()->AddLocalReference<jclass>(klass));
1446 }
Andreas Gampeaa8b60c2016-10-12 12:51:25 -07001447 return true;
1448 }
1449
1450 art::Thread* self_;
1451 std::vector<jclass> classes_;
1452 };
1453
1454 art::Thread* self = art::Thread::Current();
1455 ReportClassVisitor rcv(self);
1456 {
1457 art::ScopedObjectAccess soa(self);
1458 art::Runtime::Current()->GetClassLinker()->VisitClasses(&rcv);
1459 }
1460
1461 size_t size = rcv.classes_.size();
1462 jclass* classes = nullptr;
1463 jvmtiError alloc_ret = env->Allocate(static_cast<jlong>(size * sizeof(jclass)),
1464 reinterpret_cast<unsigned char**>(&classes));
1465 if (alloc_ret != ERR(NONE)) {
1466 return alloc_ret;
1467 }
1468
1469 for (size_t i = 0; i < size; ++i) {
1470 classes[i] = rcv.classes_[i];
1471 }
1472 *classes_ptr = classes;
1473 *class_count_ptr = static_cast<jint>(size);
1474
1475 return ERR(NONE);
1476}
1477
Andreas Gampe8da6d032016-10-31 19:31:03 -07001478jvmtiError HeapUtil::ForceGarbageCollection(jvmtiEnv* env ATTRIBUTE_UNUSED) {
Andreas Gampe6e897762018-10-16 13:09:32 -07001479 art::Runtime::Current()->GetHeap()->CollectGarbage(/* clear_soft_references= */ false);
Andreas Gampe8da6d032016-10-31 19:31:03 -07001480
1481 return ERR(NONE);
1482}
Andreas Gamped73aba42017-05-03 21:40:26 -07001483
1484static constexpr jint kHeapIdDefault = 0;
1485static constexpr jint kHeapIdImage = 1;
1486static constexpr jint kHeapIdZygote = 2;
1487static constexpr jint kHeapIdApp = 3;
1488
Andreas Gampe2eb25e42017-05-09 17:14:58 -07001489static jint GetHeapId(art::ObjPtr<art::mirror::Object> obj)
1490 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1491 if (obj == nullptr) {
1492 return -1;
1493 }
1494
1495 art::gc::Heap* const heap = art::Runtime::Current()->GetHeap();
1496 const art::gc::space::ContinuousSpace* const space =
1497 heap->FindContinuousSpaceFromObject(obj, true);
1498 jint heap_type = kHeapIdApp;
1499 if (space != nullptr) {
1500 if (space->IsZygoteSpace()) {
1501 heap_type = kHeapIdZygote;
1502 } else if (space->IsImageSpace() && heap->ObjectIsInBootImageSpace(obj)) {
1503 // Only count objects in the boot image as HPROF_HEAP_IMAGE, this leaves app image objects
1504 // as HPROF_HEAP_APP. b/35762934
1505 heap_type = kHeapIdImage;
1506 }
1507 } else {
1508 const auto* los = heap->GetLargeObjectsSpace();
1509 if (los->Contains(obj.Ptr()) && los->IsZygoteLargeObject(art::Thread::Current(), obj.Ptr())) {
1510 heap_type = kHeapIdZygote;
1511 }
1512 }
1513 return heap_type;
1514};
1515
Andreas Gamped73aba42017-05-03 21:40:26 -07001516jvmtiError HeapExtensions::GetObjectHeapId(jvmtiEnv* env, jlong tag, jint* heap_id, ...) {
1517 if (heap_id == nullptr) {
1518 return ERR(NULL_POINTER);
1519 }
1520
1521 art::Thread* self = art::Thread::Current();
1522
1523 auto work = [&]() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1524 ObjectTagTable* tag_table = ArtJvmTiEnv::AsArtJvmTiEnv(env)->object_tag_table.get();
1525 art::ObjPtr<art::mirror::Object> obj = tag_table->Find(tag);
Andreas Gampe2eb25e42017-05-09 17:14:58 -07001526 jint heap_type = GetHeapId(obj);
1527 if (heap_type == -1) {
Andreas Gamped73aba42017-05-03 21:40:26 -07001528 return ERR(NOT_FOUND);
1529 }
Andreas Gamped73aba42017-05-03 21:40:26 -07001530 *heap_id = heap_type;
1531 return ERR(NONE);
1532 };
1533
1534 if (!art::Locks::mutator_lock_->IsSharedHeld(self)) {
1535 if (!self->IsThreadSuspensionAllowable()) {
1536 return ERR(INTERNAL);
1537 }
1538 art::ScopedObjectAccess soa(self);
1539 return work();
1540 } else {
1541 // We cannot use SOA in this case. We might be holding the lock, but may not be in the
1542 // runnable state (e.g., during GC).
1543 art::Locks::mutator_lock_->AssertSharedHeld(self);
1544 // TODO: Investigate why ASSERT_SHARED_CAPABILITY doesn't work.
1545 auto annotalysis_workaround = [&]() NO_THREAD_SAFETY_ANALYSIS {
1546 return work();
1547 };
1548 return annotalysis_workaround();
1549 }
1550}
1551
1552static jvmtiError CopyStringAndReturn(jvmtiEnv* env, const char* in, char** out) {
1553 jvmtiError error;
1554 JvmtiUniquePtr<char[]> param_name = CopyString(env, in, &error);
1555 if (param_name == nullptr) {
1556 return error;
1557 }
1558 *out = param_name.release();
1559 return ERR(NONE);
1560}
1561
1562static constexpr const char* kHeapIdDefaultName = "default";
1563static constexpr const char* kHeapIdImageName = "image";
1564static constexpr const char* kHeapIdZygoteName = "zygote";
1565static constexpr const char* kHeapIdAppName = "app";
1566
1567jvmtiError HeapExtensions::GetHeapName(jvmtiEnv* env, jint heap_id, char** heap_name, ...) {
1568 switch (heap_id) {
1569 case kHeapIdDefault:
1570 return CopyStringAndReturn(env, kHeapIdDefaultName, heap_name);
1571 case kHeapIdImage:
1572 return CopyStringAndReturn(env, kHeapIdImageName, heap_name);
1573 case kHeapIdZygote:
1574 return CopyStringAndReturn(env, kHeapIdZygoteName, heap_name);
1575 case kHeapIdApp:
1576 return CopyStringAndReturn(env, kHeapIdAppName, heap_name);
1577
1578 default:
1579 return ERR(ILLEGAL_ARGUMENT);
1580 }
1581}
1582
Andreas Gampe2eb25e42017-05-09 17:14:58 -07001583jvmtiError HeapExtensions::IterateThroughHeapExt(jvmtiEnv* env,
1584 jint heap_filter,
1585 jclass klass,
1586 const jvmtiHeapCallbacks* callbacks,
1587 const void* user_data) {
1588 if (ArtJvmTiEnv::AsArtJvmTiEnv(env)->capabilities.can_tag_objects != 1) { \
1589 return ERR(MUST_POSSESS_CAPABILITY); \
1590 }
1591
1592 // ART extension API: Also pass the heap id.
1593 auto ArtIterateHeap = [](art::mirror::Object* obj,
1594 const jvmtiHeapCallbacks* cb_callbacks,
1595 jlong class_tag,
1596 jlong size,
1597 jlong* tag,
1598 jint length,
1599 void* cb_user_data)
1600 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1601 jint heap_id = GetHeapId(obj);
1602 using ArtExtensionAPI = jint (*)(jlong, jlong, jlong*, jint length, void*, jint);
1603 return reinterpret_cast<ArtExtensionAPI>(cb_callbacks->heap_iteration_callback)(
1604 class_tag, size, tag, length, cb_user_data, heap_id);
1605 };
1606 return DoIterateThroughHeap(ArtIterateHeap,
1607 env,
1608 ArtJvmTiEnv::AsArtJvmTiEnv(env)->object_tag_table.get(),
1609 heap_filter,
1610 klass,
1611 callbacks,
1612 user_data);
1613}
1614
Alex Lightc14ec8f2019-07-18 16:08:41 -07001615namespace {
1616
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001617using ObjectPtr = art::ObjPtr<art::mirror::Object>;
Alex Light986914b2019-11-19 01:12:25 +00001618using ObjectMap = std::unordered_map<ObjectPtr, ObjectPtr, art::HashObjPtr>;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001619
Alex Light986914b2019-11-19 01:12:25 +00001620static void ReplaceObjectReferences(const ObjectMap& map)
Alex Lightc14ec8f2019-07-18 16:08:41 -07001621 REQUIRES(art::Locks::mutator_lock_,
Alex Lightc14ec8f2019-07-18 16:08:41 -07001622 art::Roles::uninterruptible_) {
1623 art::Runtime::Current()->GetHeap()->VisitObjectsPaused(
1624 [&](art::mirror::Object* ref) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1625 // Rewrite all references in the object if needed.
1626 class ResizeReferenceVisitor {
1627 public:
1628 using CompressedObj = art::mirror::CompressedReference<art::mirror::Object>;
Alex Lighta142f712019-12-03 05:52:33 -08001629 explicit ResizeReferenceVisitor(const ObjectMap& map, ObjectPtr ref)
1630 : map_(map), ref_(ref) {}
Alex Lightc14ec8f2019-07-18 16:08:41 -07001631
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001632 // Ignore class roots.
1633 void VisitRootIfNonNull(CompressedObj* root) const
1634 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1635 if (root != nullptr) {
1636 VisitRoot(root);
1637 }
1638 }
1639 void VisitRoot(CompressedObj* root) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light986914b2019-11-19 01:12:25 +00001640 auto it = map_.find(root->AsMirrorPtr());
1641 if (it != map_.end()) {
1642 root->Assign(it->second);
Alex Lighta142f712019-12-03 05:52:33 -08001643 art::WriteBarrier::ForEveryFieldWrite(ref_);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001644 }
1645 }
Alex Lightc14ec8f2019-07-18 16:08:41 -07001646
1647 void operator()(art::ObjPtr<art::mirror::Object> obj,
1648 art::MemberOffset off,
Alex Light986914b2019-11-19 01:12:25 +00001649 bool is_static) const
Alex Lightc14ec8f2019-07-18 16:08:41 -07001650 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light986914b2019-11-19 01:12:25 +00001651 auto it = map_.find(obj->GetFieldObject<art::mirror::Object>(off));
1652 if (it != map_.end()) {
1653 UNUSED(is_static);
1654 if (UNLIKELY(!is_static && off == art::mirror::Object::ClassOffset())) {
1655 // We don't want to update the declaring class of any objects. They will be replaced
1656 // in the heap and we need the declaring class to know its size.
1657 return;
1658 }
Alex Lightb0ce4d22019-09-19 14:45:45 -07001659 VLOG(plugin) << "Updating field at offset " << off.Uint32Value() << " of type "
1660 << obj->GetClass()->PrettyClass();
Alex Light986914b2019-11-19 01:12:25 +00001661 obj->SetFieldObject</*transaction*/ false>(off, it->second);
1662 art::WriteBarrier::ForEveryFieldWrite(obj);
Alex Lightc14ec8f2019-07-18 16:08:41 -07001663 }
1664 }
1665
1666 // java.lang.ref.Reference visitor.
1667 void operator()(art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
1668 art::ObjPtr<art::mirror::Reference> ref) const
1669 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1670 operator()(ref, art::mirror::Reference::ReferentOffset(), /* is_static */ false);
1671 }
1672
1673 private:
Alex Light986914b2019-11-19 01:12:25 +00001674 const ObjectMap& map_;
Alex Lighta142f712019-12-03 05:52:33 -08001675 ObjectPtr ref_;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001676 };
1677
Alex Lighta142f712019-12-03 05:52:33 -08001678 ResizeReferenceVisitor rrv(map, ref);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001679 if (ref->IsClass()) {
1680 // Class object native roots are the ArtField and ArtMethod 'declaring_class_' fields
1681 // which we don't want to be messing with as it would break ref-visitor assumptions about
1682 // what a class looks like. We want to keep the default behavior in other cases (such as
1683 // dex-cache) though. Unfortunately there is no way to tell from the visitor where exactly
1684 // the root came from.
1685 // TODO It might be nice to have the visitors told where the reference came from.
1686 ref->VisitReferences</*kVisitNativeRoots*/false>(rrv, rrv);
1687 } else {
1688 ref->VisitReferences</*kVisitNativeRoots*/true>(rrv, rrv);
1689 }
Alex Lightc14ec8f2019-07-18 16:08:41 -07001690 });
1691}
1692
Alex Light986914b2019-11-19 01:12:25 +00001693static void ReplaceStrongRoots(art::Thread* self, const ObjectMap& map)
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001694 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
Alex Lightc14ec8f2019-07-18 16:08:41 -07001695 // replace root references expcept java frames.
1696 struct ResizeRootVisitor : public art::RootVisitor {
1697 public:
Alex Light986914b2019-11-19 01:12:25 +00001698 explicit ResizeRootVisitor(const ObjectMap& map) : map_(map) {}
Alex Lightc14ec8f2019-07-18 16:08:41 -07001699
1700 // TODO It's somewhat annoying to have to have this function implemented twice. It might be
1701 // good/useful to implement operator= for CompressedReference to allow us to use a template to
1702 // implement both of these.
1703 void VisitRoots(art::mirror::Object*** roots, size_t count, const art::RootInfo& info) override
1704 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1705 art::mirror::Object*** end = roots + count;
1706 for (art::mirror::Object** obj = *roots; roots != end; obj = *(++roots)) {
Alex Light986914b2019-11-19 01:12:25 +00001707 auto it = map_.find(*obj);
1708 if (it != map_.end()) {
Alex Lightc14ec8f2019-07-18 16:08:41 -07001709 // Java frames might have the JIT doing optimizations (for example loop-unrolling or
1710 // eliding bounds checks) so we need deopt them once we're done here.
1711 if (info.GetType() == art::RootType::kRootJavaFrame) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001712 const art::JavaFrameRootInfo& jfri =
1713 art::down_cast<const art::JavaFrameRootInfo&>(info);
1714 if (jfri.GetVReg() == art::JavaFrameRootInfo::kMethodDeclaringClass) {
Alex Lightb55ef652019-09-26 15:23:28 -07001715 info.Describe(VLOG_STREAM(plugin) << "Not changing declaring-class during stack"
1716 << " walk. Found obsolete java frame id ");
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001717 continue;
1718 } else {
Alex Lightb55ef652019-09-26 15:23:28 -07001719 info.Describe(VLOG_STREAM(plugin) << "Found java frame id ");
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001720 threads_with_roots_.insert(info.GetThreadId());
1721 }
Alex Lightc14ec8f2019-07-18 16:08:41 -07001722 }
Alex Light986914b2019-11-19 01:12:25 +00001723 *obj = it->second.Ptr();
Alex Lightc14ec8f2019-07-18 16:08:41 -07001724 }
1725 }
1726 }
1727
1728 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
1729 size_t count,
1730 const art::RootInfo& info) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
1731 art::mirror::CompressedReference<art::mirror::Object>** end = roots + count;
1732 for (art::mirror::CompressedReference<art::mirror::Object>* obj = *roots; roots != end;
1733 obj = *(++roots)) {
Alex Light986914b2019-11-19 01:12:25 +00001734 auto it = map_.find(obj->AsMirrorPtr());
1735 if (it != map_.end()) {
Alex Lightc14ec8f2019-07-18 16:08:41 -07001736 // Java frames might have the JIT doing optimizations (for example loop-unrolling or
1737 // eliding bounds checks) so we need deopt them once we're done here.
1738 if (info.GetType() == art::RootType::kRootJavaFrame) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001739 const art::JavaFrameRootInfo& jfri =
1740 art::down_cast<const art::JavaFrameRootInfo&>(info);
1741 if (jfri.GetVReg() == art::JavaFrameRootInfo::kMethodDeclaringClass) {
Alex Lightb55ef652019-09-26 15:23:28 -07001742 info.Describe(VLOG_STREAM(plugin) << "Not changing declaring-class during stack"
1743 << " walk. Found obsolete java frame id ");
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001744 continue;
1745 } else {
Alex Lightb55ef652019-09-26 15:23:28 -07001746 info.Describe(VLOG_STREAM(plugin) << "Found java frame id ");
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001747 threads_with_roots_.insert(info.GetThreadId());
1748 }
Alex Lightc14ec8f2019-07-18 16:08:41 -07001749 }
Alex Light986914b2019-11-19 01:12:25 +00001750 obj->Assign(it->second);
Alex Lightc14ec8f2019-07-18 16:08:41 -07001751 }
1752 }
1753 }
1754
1755 const std::unordered_set<uint32_t>& GetThreadsWithJavaFrameRoots() const {
1756 return threads_with_roots_;
1757 }
1758
1759 private:
Alex Light986914b2019-11-19 01:12:25 +00001760 const ObjectMap& map_;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001761 std::unordered_set<uint32_t> threads_with_roots_;
1762 };
Alex Light986914b2019-11-19 01:12:25 +00001763 ResizeRootVisitor rrv(map);
Alex Lightc14ec8f2019-07-18 16:08:41 -07001764 art::Runtime::Current()->VisitRoots(&rrv, art::VisitRootFlags::kVisitRootFlagAllRoots);
1765 // Handle java Frames. Annoyingly the JIT can embed information about the length of the array into
1766 // the compiled code. By changing the length of the array we potentially invalidate these
1767 // assumptions and so could cause (eg) OOB array access or other issues.
1768 if (!rrv.GetThreadsWithJavaFrameRoots().empty()) {
1769 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
1770 art::ThreadList* thread_list = art::Runtime::Current()->GetThreadList();
1771 art::instrumentation::Instrumentation* instr = art::Runtime::Current()->GetInstrumentation();
1772 for (uint32_t id : rrv.GetThreadsWithJavaFrameRoots()) {
1773 art::Thread* t = thread_list->FindThreadByThreadId(id);
1774 CHECK(t != nullptr) << "id " << id << " does not refer to a valid thread."
1775 << " Where did the roots come from?";
Alex Lightb0ce4d22019-09-19 14:45:45 -07001776 VLOG(plugin) << "Instrumenting thread stack of thread " << *t;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001777 // TODO Use deopt manager. We need a version that doesn't acquire all the locks we
1778 // already have.
1779 // TODO We technically only need to do this if the frames are not already being interpreted.
1780 // The cost for doing an extra stack walk is unlikely to be worth it though.
1781 instr->InstrumentThreadStack(t);
1782 }
1783 }
1784}
1785
Alex Light72d7e942019-07-23 13:10:20 -07001786static void ReplaceWeakRoots(art::Thread* self,
1787 EventHandler* event_handler,
Alex Light986914b2019-11-19 01:12:25 +00001788 const ObjectMap& map)
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001789 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
Alex Light72d7e942019-07-23 13:10:20 -07001790 // Handle tags. We want to do this seprately from other weak-refs (handled below) because we need
1791 // to send additional events and handle cases where the agent might have tagged the new
1792 // replacement object during the VMObjectAlloc. We do this by removing all tags associated with
1793 // both the obsolete and the new arrays. Then we send the ObsoleteObjectCreated event and cache
1794 // the new tag values. We next update all the other weak-references (the tags have been removed)
1795 // and finally update the tag table with the new values. Doing things in this way (1) keeps all
1796 // code relating to updating weak-references together and (2) ensures we don't end up in strange
1797 // situations where the order of weak-ref visiting affects the final tagging state. Since we have
1798 // the mutator_lock_ and gc-paused throughout this whole process no threads should be able to see
1799 // the interval where the objects are not tagged.
Alex Light986914b2019-11-19 01:12:25 +00001800 struct NewTagValue {
1801 public:
1802 ObjectPtr obsolete_obj_;
1803 jlong obsolete_tag_;
1804 ObjectPtr new_obj_;
1805 jlong new_tag_;
1806 };
1807
1808 // Map from the environment to the list of <obsolete_tag, new_tag> pairs that were changed.
1809 std::unordered_map<ArtJvmTiEnv*, std::vector<NewTagValue>> changed_tags;
Alex Light72d7e942019-07-23 13:10:20 -07001810 event_handler->ForEachEnv(self, [&](ArtJvmTiEnv* env) {
1811 // Cannot have REQUIRES(art::Locks::mutator_lock_) since ForEachEnv doesn't require it.
1812 art::Locks::mutator_lock_->AssertExclusiveHeld(self);
1813 env->object_tag_table->Lock();
1814 // 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 +00001815 for (auto it : map) {
1816 jlong new_tag = 0;
1817 jlong obsolete_tag = 0;
1818 bool had_obsolete_tag = env->object_tag_table->RemoveLocked(it.first, &obsolete_tag);
1819 bool had_new_tag = env->object_tag_table->RemoveLocked(it.second, &new_tag);
1820 // Dispatch event.
1821 if (had_obsolete_tag || had_new_tag) {
1822 event_handler->DispatchEventOnEnv<ArtJvmtiEvent::kObsoleteObjectCreated>(
1823 env, self, &obsolete_tag, &new_tag);
1824 changed_tags.try_emplace(env).first->second.push_back(
1825 { it.first, obsolete_tag, it.second, new_tag });
1826 }
Alex Light72d7e942019-07-23 13:10:20 -07001827 }
1828 // 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 +00001829 // deal with the visit-weaks overwriting the initial new_obj_ptr tag and generally making things
Alex Light72d7e942019-07-23 13:10:20 -07001830 // difficult.
1831 env->object_tag_table->Unlock();
1832 });
1833 // Handle weak-refs.
Alex Lightc14ec8f2019-07-18 16:08:41 -07001834 struct ReplaceWeaksVisitor : public art::IsMarkedVisitor {
1835 public:
Alex Light986914b2019-11-19 01:12:25 +00001836 ReplaceWeaksVisitor(const ObjectMap& map) : map_(map) {}
Alex Lightc14ec8f2019-07-18 16:08:41 -07001837
1838 art::mirror::Object* IsMarked(art::mirror::Object* obj)
1839 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light986914b2019-11-19 01:12:25 +00001840 auto it = map_.find(obj);
1841 if (it != map_.end()) {
1842 return it->second.Ptr();
Alex Lightc14ec8f2019-07-18 16:08:41 -07001843 } else {
1844 return obj;
1845 }
1846 }
1847
1848 private:
Alex Light986914b2019-11-19 01:12:25 +00001849 const ObjectMap& map_;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001850 };
Alex Light986914b2019-11-19 01:12:25 +00001851 ReplaceWeaksVisitor rwv(map);
Alex Lightc14ec8f2019-07-18 16:08:41 -07001852 art::Runtime::Current()->SweepSystemWeaks(&rwv);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001853 // 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 -07001854 event_handler->ForEachEnv(self, [&](ArtJvmTiEnv* env) {
1855 // Cannot have REQUIRES(art::Locks::mutator_lock_) since ForEachEnv doesn't require it.
1856 art::Locks::mutator_lock_->AssertExclusiveHeld(self);
1857 env->object_tag_table->Lock();
Alex Light986914b2019-11-19 01:12:25 +00001858 auto it = changed_tags.find(env);
1859 if (it != changed_tags.end()) {
1860 for (const NewTagValue& v : it->second) {
1861 env->object_tag_table->SetLocked(v.obsolete_obj_, v.obsolete_tag_);
1862 env->object_tag_table->SetLocked(v.new_obj_, v.new_tag_);
1863 }
Alex Light72d7e942019-07-23 13:10:20 -07001864 }
1865 env->object_tag_table->Unlock();
1866 });
Alex Lightc14ec8f2019-07-18 16:08:41 -07001867}
1868
Nicolas Geoffray5a2301d2019-09-18 06:11:22 +00001869} // namespace
1870
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001871void HeapExtensions::ReplaceReference(art::Thread* self,
1872 art::ObjPtr<art::mirror::Object> old_obj_ptr,
1873 art::ObjPtr<art::mirror::Object> new_obj_ptr) {
Alex Light986914b2019-11-19 01:12:25 +00001874 ObjectMap map { { old_obj_ptr, new_obj_ptr } };
1875 ReplaceReferences(self, map);
1876}
1877
1878void HeapExtensions::ReplaceReferences(art::Thread* self, const ObjectMap& map) {
1879 ReplaceObjectReferences(map);
1880 ReplaceStrongRoots(self, map);
1881 ReplaceWeakRoots(self, HeapExtensions::gEventHandler, map);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001882}
1883
Alex Lightc14ec8f2019-07-18 16:08:41 -07001884jvmtiError HeapExtensions::ChangeArraySize(jvmtiEnv* env, jobject arr, jsize new_size) {
1885 if (ArtJvmTiEnv::AsArtJvmTiEnv(env)->capabilities.can_tag_objects != 1) {
1886 return ERR(MUST_POSSESS_CAPABILITY);
1887 }
1888 art::Thread* self = art::Thread::Current();
1889 ScopedNoUserCodeSuspension snucs(self);
1890 art::ScopedObjectAccess soa(self);
1891 if (arr == nullptr) {
1892 JVMTI_LOG(INFO, env) << "Cannot resize a null object";
1893 return ERR(NULL_POINTER);
1894 }
1895 art::ObjPtr<art::mirror::Class> klass(soa.Decode<art::mirror::Object>(arr)->GetClass());
1896 if (!klass->IsArrayClass()) {
1897 JVMTI_LOG(INFO, env) << klass->PrettyClass() << " is not an array class!";
1898 return ERR(ILLEGAL_ARGUMENT);
1899 }
1900 if (new_size < 0) {
1901 JVMTI_LOG(INFO, env) << "Cannot resize an array to a negative size";
1902 return ERR(ILLEGAL_ARGUMENT);
1903 }
1904 // Allocate the new copy.
1905 art::StackHandleScope<2> hs(self);
1906 art::Handle<art::mirror::Array> old_arr(hs.NewHandle(soa.Decode<art::mirror::Array>(arr)));
1907 art::MutableHandle<art::mirror::Array> new_arr(hs.NewHandle<art::mirror::Array>(nullptr));
1908 if (klass->IsObjectArrayClass()) {
1909 new_arr.Assign(
1910 art::mirror::ObjectArray<art::mirror::Object>::Alloc(self, old_arr->GetClass(), new_size));
1911 } else {
1912 // NB This also copies the old array but since we aren't suspended we need to do this again to
1913 // catch any concurrent modifications.
1914 new_arr.Assign(art::mirror::Array::CopyOf(old_arr, self, new_size));
1915 }
1916 if (new_arr.IsNull()) {
1917 self->AssertPendingOOMException();
1918 JVMTI_LOG(INFO, env) << "Unable to allocate " << old_arr->GetClass()->PrettyClass()
1919 << " (length: " << new_size << ") due to OOME. Error was: "
1920 << self->GetException()->Dump();
1921 self->ClearException();
1922 return ERR(OUT_OF_MEMORY);
1923 } else {
1924 self->AssertNoPendingException();
1925 }
1926 // Suspend everything.
1927 art::ScopedThreadSuspension sts(self, art::ThreadState::kSuspended);
1928 art::gc::ScopedGCCriticalSection sgccs(
1929 self, art::gc::GcCause::kGcCauseDebugger, art::gc::CollectorType::kCollectorTypeDebugger);
1930 art::ScopedSuspendAll ssa("Resize array!");
1931 // Replace internals.
1932 new_arr->SetLockWord(old_arr->GetLockWord(false), false);
1933 old_arr->SetLockWord(art::LockWord::Default(), false);
1934 // Copy the contents now when everything is suspended.
1935 int32_t size = std::min(old_arr->GetLength(), new_size);
1936 switch (old_arr->GetClass()->GetComponentType()->GetPrimitiveType()) {
1937 case art::Primitive::kPrimBoolean:
1938 new_arr->AsBooleanArray()->Memcpy(0, old_arr->AsBooleanArray(), 0, size);
1939 break;
1940 case art::Primitive::kPrimByte:
1941 new_arr->AsByteArray()->Memcpy(0, old_arr->AsByteArray(), 0, size);
1942 break;
1943 case art::Primitive::kPrimChar:
1944 new_arr->AsCharArray()->Memcpy(0, old_arr->AsCharArray(), 0, size);
1945 break;
1946 case art::Primitive::kPrimShort:
1947 new_arr->AsShortArray()->Memcpy(0, old_arr->AsShortArray(), 0, size);
1948 break;
1949 case art::Primitive::kPrimInt:
1950 new_arr->AsIntArray()->Memcpy(0, old_arr->AsIntArray(), 0, size);
1951 break;
1952 case art::Primitive::kPrimLong:
1953 new_arr->AsLongArray()->Memcpy(0, old_arr->AsLongArray(), 0, size);
1954 break;
1955 case art::Primitive::kPrimFloat:
1956 new_arr->AsFloatArray()->Memcpy(0, old_arr->AsFloatArray(), 0, size);
1957 break;
1958 case art::Primitive::kPrimDouble:
1959 new_arr->AsDoubleArray()->Memcpy(0, old_arr->AsDoubleArray(), 0, size);
1960 break;
1961 case art::Primitive::kPrimNot:
1962 for (int32_t i = 0; i < size; i++) {
1963 new_arr->AsObjectArray<art::mirror::Object>()->Set(
1964 i, old_arr->AsObjectArray<art::mirror::Object>()->Get(i));
1965 }
1966 break;
1967 case art::Primitive::kPrimVoid:
1968 LOG(FATAL) << "void-array is not a legal type!";
1969 UNREACHABLE();
1970 }
1971 // Actually replace all the pointers.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001972 ReplaceReference(self, old_arr.Get(), new_arr.Get());
Alex Lightc14ec8f2019-07-18 16:08:41 -07001973 return OK;
1974}
1975
Alex Light72d7e942019-07-23 13:10:20 -07001976void HeapExtensions::Register(EventHandler* eh) {
1977 gEventHandler = eh;
1978}
1979
Andreas Gampee54d9922016-10-11 19:55:37 -07001980} // namespace openjdkjvmti