blob: bbb2ced61afb940d8f5ee6db702a57a5a2bd9feb [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>
20
21#include "android-base/logging.h"
22#include "android-base/thread_annotations.h"
23#include "arch/context.h"
Andreas Gampe70bfc8a2016-11-03 11:04:15 -070024#include "art_field-inl.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070025#include "art_jvmti.h"
Alex Lightb0ce4d22019-09-19 14:45:45 -070026#include "base/logging.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070027#include "base/macros.h"
28#include "base/mutex.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070029#include "base/utils.h"
Andreas Gampeaa8b60c2016-10-12 12:51:25 -070030#include "class_linker.h"
Alex Light79d6c802019-06-27 15:50:11 +000031#include "class_root.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"
Andreas Gampee54d9922016-10-11 19:55:37 -070060#include "runtime.h"
61#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070062#include "stack.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070063#include "thread-inl.h"
Andreas Gampe70bfc8a2016-11-03 11:04:15 -070064#include "thread_list.h"
Alex Lightc14ec8f2019-07-18 16:08:41 -070065#include "ti_logging.h"
66#include "ti_stack.h"
67#include "ti_thread.h"
Alex Light79d6c802019-06-27 15:50:11 +000068#include "well_known_classes.h"
Andreas Gampee54d9922016-10-11 19:55:37 -070069
70namespace openjdkjvmti {
71
Alex Light72d7e942019-07-23 13:10:20 -070072EventHandler* HeapExtensions::gEventHandler = nullptr;
73
Andreas Gampe3ec8e402017-02-21 15:49:53 -080074namespace {
75
Andreas Gampe9e38a502017-03-06 08:19:26 -080076struct IndexCache {
77 // The number of interface fields implemented by the class. This is a prefix to all assigned
78 // field indices.
79 size_t interface_fields;
80
81 // It would be nice to also cache the following, but it is complicated to wire up into the
82 // generic visit:
83 // The number of fields in interfaces and superclasses. This is the first index assigned to
84 // fields of the class.
85 // size_t superclass_fields;
86};
87using IndexCachingTable = JvmtiWeakTable<IndexCache>;
88
89static IndexCachingTable gIndexCachingTable;
90
Andreas Gampe3ec8e402017-02-21 15:49:53 -080091// Report the contents of a string, if a callback is set.
92jint ReportString(art::ObjPtr<art::mirror::Object> obj,
93 jvmtiEnv* env,
94 ObjectTagTable* tag_table,
95 const jvmtiHeapCallbacks* cb,
96 const void* user_data) REQUIRES_SHARED(art::Locks::mutator_lock_) {
97 if (UNLIKELY(cb->string_primitive_value_callback != nullptr) && obj->IsString()) {
98 art::ObjPtr<art::mirror::String> str = obj->AsString();
99 int32_t string_length = str->GetLength();
Andreas Gampe5f942032017-02-27 19:59:40 -0800100 JvmtiUniquePtr<uint16_t[]> data;
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800101
Andreas Gampe5f942032017-02-27 19:59:40 -0800102 if (string_length > 0) {
103 jvmtiError alloc_error;
104 data = AllocJvmtiUniquePtr<uint16_t[]>(env, string_length, &alloc_error);
105 if (data == nullptr) {
106 // TODO: Not really sure what to do here. Should we abort the iteration and go all the way
107 // back? For now just warn.
108 LOG(WARNING) << "Unable to allocate buffer for string reporting! Silently dropping value."
109 << " >" << str->ToModifiedUtf8() << "<";
110 return 0;
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800111 }
Andreas Gampe5f942032017-02-27 19:59:40 -0800112
113 if (str->IsCompressed()) {
114 uint8_t* compressed_data = str->GetValueCompressed();
115 for (int32_t i = 0; i != string_length; ++i) {
116 data[i] = compressed_data[i];
117 }
118 } else {
119 // Can copy directly.
120 memcpy(data.get(), str->GetValue(), string_length * sizeof(uint16_t));
121 }
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800122 }
123
124 const jlong class_tag = tag_table->GetTagOrZero(obj->GetClass());
125 jlong string_tag = tag_table->GetTagOrZero(obj.Ptr());
126 const jlong saved_string_tag = string_tag;
127
128 jint result = cb->string_primitive_value_callback(class_tag,
129 obj->SizeOf(),
130 &string_tag,
131 data.get(),
132 string_length,
133 const_cast<void*>(user_data));
134 if (string_tag != saved_string_tag) {
135 tag_table->Set(obj.Ptr(), string_tag);
136 }
137
138 return result;
139 }
140 return 0;
141}
142
Andreas Gampebecd6ad2017-02-22 19:20:37 -0800143// Report the contents of a primitive array, if a callback is set.
144jint ReportPrimitiveArray(art::ObjPtr<art::mirror::Object> obj,
145 jvmtiEnv* env,
146 ObjectTagTable* tag_table,
147 const jvmtiHeapCallbacks* cb,
148 const void* user_data) REQUIRES_SHARED(art::Locks::mutator_lock_) {
149 if (UNLIKELY(cb->array_primitive_value_callback != nullptr) &&
150 obj->IsArrayInstance() &&
151 !obj->IsObjectArray()) {
152 art::ObjPtr<art::mirror::Array> array = obj->AsArray();
153 int32_t array_length = array->GetLength();
154 size_t component_size = array->GetClass()->GetComponentSize();
155 art::Primitive::Type art_prim_type = array->GetClass()->GetComponentType()->GetPrimitiveType();
156 jvmtiPrimitiveType prim_type =
157 static_cast<jvmtiPrimitiveType>(art::Primitive::Descriptor(art_prim_type)[0]);
158 DCHECK(prim_type == JVMTI_PRIMITIVE_TYPE_BOOLEAN ||
159 prim_type == JVMTI_PRIMITIVE_TYPE_BYTE ||
160 prim_type == JVMTI_PRIMITIVE_TYPE_CHAR ||
161 prim_type == JVMTI_PRIMITIVE_TYPE_SHORT ||
162 prim_type == JVMTI_PRIMITIVE_TYPE_INT ||
163 prim_type == JVMTI_PRIMITIVE_TYPE_LONG ||
164 prim_type == JVMTI_PRIMITIVE_TYPE_FLOAT ||
165 prim_type == JVMTI_PRIMITIVE_TYPE_DOUBLE);
166
167 const jlong class_tag = tag_table->GetTagOrZero(obj->GetClass());
168 jlong array_tag = tag_table->GetTagOrZero(obj.Ptr());
169 const jlong saved_array_tag = array_tag;
170
171 jint result;
172 if (array_length == 0) {
173 result = cb->array_primitive_value_callback(class_tag,
174 obj->SizeOf(),
175 &array_tag,
176 0,
177 prim_type,
178 nullptr,
179 const_cast<void*>(user_data));
180 } else {
181 jvmtiError alloc_error;
182 JvmtiUniquePtr<char[]> data = AllocJvmtiUniquePtr<char[]>(env,
183 array_length * component_size,
184 &alloc_error);
185 if (data == nullptr) {
186 // TODO: Not really sure what to do here. Should we abort the iteration and go all the way
187 // back? For now just warn.
188 LOG(WARNING) << "Unable to allocate buffer for array reporting! Silently dropping value.";
189 return 0;
190 }
191
192 memcpy(data.get(), array->GetRawData(component_size, 0), array_length * component_size);
193
194 result = cb->array_primitive_value_callback(class_tag,
195 obj->SizeOf(),
196 &array_tag,
197 array_length,
198 prim_type,
199 data.get(),
200 const_cast<void*>(user_data));
201 }
202
203 if (array_tag != saved_array_tag) {
204 tag_table->Set(obj.Ptr(), array_tag);
205 }
206
207 return result;
208 }
209 return 0;
210}
211
Andreas Gampee7316932017-02-25 09:15:05 -0800212template <typename UserData>
213bool VisitorFalse(art::ObjPtr<art::mirror::Object> obj ATTRIBUTE_UNUSED,
214 art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
215 art::ArtField& field ATTRIBUTE_UNUSED,
216 size_t field_index ATTRIBUTE_UNUSED,
217 UserData* user_data ATTRIBUTE_UNUSED) {
218 return false;
219}
220
Andreas Gampe95114602017-02-28 15:47:44 -0800221template <typename UserData, bool kCallVisitorOnRecursion>
Andreas Gampee7316932017-02-25 09:15:05 -0800222class FieldVisitor {
223 public:
224 // Report the contents of a primitive fields of the given object, if a callback is set.
Andreas Gampe95114602017-02-28 15:47:44 -0800225 template <typename StaticPrimitiveVisitor,
226 typename StaticReferenceVisitor,
227 typename InstancePrimitiveVisitor,
228 typename InstanceReferenceVisitor>
Andreas Gampee7316932017-02-25 09:15:05 -0800229 static bool ReportFields(art::ObjPtr<art::mirror::Object> obj,
230 UserData* user_data,
231 StaticPrimitiveVisitor& static_prim_visitor,
232 StaticReferenceVisitor& static_ref_visitor,
233 InstancePrimitiveVisitor& instance_prim_visitor,
234 InstanceReferenceVisitor& instance_ref_visitor)
235 REQUIRES_SHARED(art::Locks::mutator_lock_) {
236 FieldVisitor fv(user_data);
237
238 if (obj->IsClass()) {
239 // When visiting a class, we only visit the static fields of the given class. No field of
240 // superclasses is visited.
241 art::ObjPtr<art::mirror::Class> klass = obj->AsClass();
242 // Only report fields on resolved classes. We need valid field data.
243 if (!klass->IsResolved()) {
244 return false;
245 }
246 return fv.ReportFieldsImpl(nullptr,
247 obj->AsClass(),
248 obj->AsClass()->IsInterface(),
249 static_prim_visitor,
250 static_ref_visitor,
251 instance_prim_visitor,
252 instance_ref_visitor);
253 } else {
254 // See comment above. Just double-checking here, but an instance *should* mean the class was
255 // resolved.
256 DCHECK(obj->GetClass()->IsResolved() || obj->GetClass()->IsErroneousResolved());
257 return fv.ReportFieldsImpl(obj,
258 obj->GetClass(),
259 false,
260 static_prim_visitor,
261 static_ref_visitor,
262 instance_prim_visitor,
263 instance_ref_visitor);
264 }
265 }
266
267 private:
268 explicit FieldVisitor(UserData* user_data) : user_data_(user_data) {}
269
270 // Report the contents of fields of the given object. If obj is null, report the static fields,
271 // otherwise the instance fields.
Andreas Gampe95114602017-02-28 15:47:44 -0800272 template <typename StaticPrimitiveVisitor,
273 typename StaticReferenceVisitor,
274 typename InstancePrimitiveVisitor,
275 typename InstanceReferenceVisitor>
Andreas Gampee7316932017-02-25 09:15:05 -0800276 bool ReportFieldsImpl(art::ObjPtr<art::mirror::Object> obj,
277 art::ObjPtr<art::mirror::Class> klass,
278 bool skip_java_lang_object,
279 StaticPrimitiveVisitor& static_prim_visitor,
280 StaticReferenceVisitor& static_ref_visitor,
281 InstancePrimitiveVisitor& instance_prim_visitor,
282 InstanceReferenceVisitor& instance_ref_visitor)
283 REQUIRES_SHARED(art::Locks::mutator_lock_) {
284 // Compute the offset of field indices.
285 size_t interface_field_count = CountInterfaceFields(klass);
286
287 size_t tmp;
288 bool aborted = ReportFieldsRecursive(obj,
289 klass,
290 interface_field_count,
291 skip_java_lang_object,
292 static_prim_visitor,
293 static_ref_visitor,
294 instance_prim_visitor,
295 instance_ref_visitor,
296 &tmp);
297 return aborted;
298 }
299
300 // Visit primitive fields in an object (instance). Return true if the visit was aborted.
Andreas Gampe95114602017-02-28 15:47:44 -0800301 template <typename StaticPrimitiveVisitor,
302 typename StaticReferenceVisitor,
303 typename InstancePrimitiveVisitor,
304 typename InstanceReferenceVisitor>
Andreas Gampee7316932017-02-25 09:15:05 -0800305 bool ReportFieldsRecursive(art::ObjPtr<art::mirror::Object> obj,
306 art::ObjPtr<art::mirror::Class> klass,
307 size_t interface_fields,
308 bool skip_java_lang_object,
309 StaticPrimitiveVisitor& static_prim_visitor,
310 StaticReferenceVisitor& static_ref_visitor,
311 InstancePrimitiveVisitor& instance_prim_visitor,
312 InstanceReferenceVisitor& instance_ref_visitor,
313 size_t* field_index_out)
314 REQUIRES_SHARED(art::Locks::mutator_lock_) {
315 DCHECK(klass != nullptr);
316 size_t field_index;
317 if (klass->GetSuperClass() == nullptr) {
318 // j.l.Object. Start with the fields from interfaces.
319 field_index = interface_fields;
320 if (skip_java_lang_object) {
321 *field_index_out = field_index;
322 return false;
323 }
324 } else {
325 // Report superclass fields.
326 if (kCallVisitorOnRecursion) {
327 if (ReportFieldsRecursive(obj,
328 klass->GetSuperClass(),
329 interface_fields,
330 skip_java_lang_object,
331 static_prim_visitor,
332 static_ref_visitor,
333 instance_prim_visitor,
334 instance_ref_visitor,
335 &field_index)) {
336 return true;
337 }
338 } else {
339 // Still call, but with empty visitor. This is required for correct counting.
340 ReportFieldsRecursive(obj,
341 klass->GetSuperClass(),
342 interface_fields,
343 skip_java_lang_object,
344 VisitorFalse<UserData>,
345 VisitorFalse<UserData>,
346 VisitorFalse<UserData>,
347 VisitorFalse<UserData>,
348 &field_index);
349 }
350 }
351
352 // Now visit fields for the current klass.
353
354 for (auto& static_field : klass->GetSFields()) {
355 if (static_field.IsPrimitiveType()) {
356 if (static_prim_visitor(obj,
357 klass,
358 static_field,
359 field_index,
360 user_data_)) {
361 return true;
362 }
363 } else {
364 if (static_ref_visitor(obj,
365 klass,
366 static_field,
367 field_index,
368 user_data_)) {
369 return true;
370 }
371 }
372 field_index++;
373 }
374
375 for (auto& instance_field : klass->GetIFields()) {
376 if (instance_field.IsPrimitiveType()) {
377 if (instance_prim_visitor(obj,
378 klass,
379 instance_field,
380 field_index,
381 user_data_)) {
382 return true;
383 }
384 } else {
385 if (instance_ref_visitor(obj,
386 klass,
387 instance_field,
388 field_index,
389 user_data_)) {
390 return true;
391 }
392 }
393 field_index++;
394 }
395
396 *field_index_out = field_index;
397 return false;
398 }
399
400 // Implements a visit of the implemented interfaces of a given class.
401 template <typename T>
402 struct RecursiveInterfaceVisit {
403 static void VisitStatic(art::Thread* self, art::ObjPtr<art::mirror::Class> klass, T& visitor)
404 REQUIRES_SHARED(art::Locks::mutator_lock_) {
405 RecursiveInterfaceVisit rv;
406 rv.Visit(self, klass, visitor);
407 }
408
409 void Visit(art::Thread* self, art::ObjPtr<art::mirror::Class> klass, T& visitor)
410 REQUIRES_SHARED(art::Locks::mutator_lock_) {
411 // First visit the parent, to get the order right.
412 // (We do this in preparation for actual visiting of interface fields.)
413 if (klass->GetSuperClass() != nullptr) {
414 Visit(self, klass->GetSuperClass(), visitor);
415 }
416 for (uint32_t i = 0; i != klass->NumDirectInterfaces(); ++i) {
417 art::ObjPtr<art::mirror::Class> inf_klass =
418 art::mirror::Class::GetDirectInterface(self, klass, i);
419 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) {
438 art::ObjPtr<art::mirror::Class> super_inf_klass =
439 art::mirror::Class::GetDirectInterface(self, inf_klass, i);
440 DCHECK(super_inf_klass != nullptr);
441 VisitInterface(self, super_inf_klass, visitor);
442 }
443 }
444
445 std::unordered_set<art::mirror::Class*> visited_interfaces;
446 };
447
448 // Counting interface fields. Note that we cannot use the interface table, as that only contains
449 // "non-marker" interfaces (= interfaces with methods).
450 static size_t CountInterfaceFields(art::ObjPtr<art::mirror::Class> klass)
451 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe9e38a502017-03-06 08:19:26 -0800452 // Do we have a cached value?
453 IndexCache tmp;
454 if (gIndexCachingTable.GetTag(klass.Ptr(), &tmp)) {
455 return tmp.interface_fields;
456 }
457
Andreas Gampee7316932017-02-25 09:15:05 -0800458 size_t count = 0;
459 auto visitor = [&count](art::ObjPtr<art::mirror::Class> inf_klass)
460 REQUIRES_SHARED(art::Locks::mutator_lock_) {
461 DCHECK(inf_klass->IsInterface());
462 DCHECK_EQ(0u, inf_klass->NumInstanceFields());
463 count += inf_klass->NumStaticFields();
464 };
465 RecursiveInterfaceVisit<decltype(visitor)>::VisitStatic(art::Thread::Current(), klass, visitor);
Andreas Gampee7316932017-02-25 09:15:05 -0800466
Andreas Gampe9e38a502017-03-06 08:19:26 -0800467 // Store this into the cache.
468 tmp.interface_fields = count;
469 gIndexCachingTable.Set(klass.Ptr(), tmp);
470
471 return count;
Andreas Gampee7316932017-02-25 09:15:05 -0800472 }
473
474 UserData* user_data_;
475};
476
477// Debug helper. Prints the structure of an object.
478template <bool kStatic, bool kRef>
479struct DumpVisitor {
480 static bool Callback(art::ObjPtr<art::mirror::Object> obj ATTRIBUTE_UNUSED,
481 art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
482 art::ArtField& field,
483 size_t field_index,
484 void* user_data ATTRIBUTE_UNUSED)
485 REQUIRES_SHARED(art::Locks::mutator_lock_) {
486 LOG(ERROR) << (kStatic ? "static " : "instance ")
487 << (kRef ? "ref " : "primitive ")
488 << field.PrettyField()
489 << " @ "
490 << field_index;
491 return false;
492 }
493};
494ATTRIBUTE_UNUSED
495void DumpObjectFields(art::ObjPtr<art::mirror::Object> obj)
496 REQUIRES_SHARED(art::Locks::mutator_lock_) {
497 if (obj->IsClass()) {
Andreas Gampe95114602017-02-28 15:47:44 -0800498 FieldVisitor<void, false>:: ReportFields(obj,
499 nullptr,
500 DumpVisitor<true, false>::Callback,
501 DumpVisitor<true, true>::Callback,
502 DumpVisitor<false, false>::Callback,
503 DumpVisitor<false, true>::Callback);
Andreas Gampee7316932017-02-25 09:15:05 -0800504 } else {
Andreas Gampe95114602017-02-28 15:47:44 -0800505 FieldVisitor<void, true>::ReportFields(obj,
506 nullptr,
507 DumpVisitor<true, false>::Callback,
508 DumpVisitor<true, true>::Callback,
509 DumpVisitor<false, false>::Callback,
510 DumpVisitor<false, true>::Callback);
Andreas Gampee7316932017-02-25 09:15:05 -0800511 }
512}
513
514class ReportPrimitiveField {
515 public:
516 static bool Report(art::ObjPtr<art::mirror::Object> obj,
517 ObjectTagTable* tag_table,
518 const jvmtiHeapCallbacks* cb,
519 const void* user_data)
520 REQUIRES_SHARED(art::Locks::mutator_lock_) {
521 if (UNLIKELY(cb->primitive_field_callback != nullptr)) {
522 jlong class_tag = tag_table->GetTagOrZero(obj->GetClass());
523 ReportPrimitiveField rpf(tag_table, class_tag, cb, user_data);
524 if (obj->IsClass()) {
Andreas Gampe95114602017-02-28 15:47:44 -0800525 return FieldVisitor<ReportPrimitiveField, false>::ReportFields(
526 obj,
527 &rpf,
528 ReportPrimitiveFieldCallback<true>,
529 VisitorFalse<ReportPrimitiveField>,
530 VisitorFalse<ReportPrimitiveField>,
531 VisitorFalse<ReportPrimitiveField>);
Andreas Gampee7316932017-02-25 09:15:05 -0800532 } else {
Andreas Gampe95114602017-02-28 15:47:44 -0800533 return FieldVisitor<ReportPrimitiveField, true>::ReportFields(
534 obj,
535 &rpf,
536 VisitorFalse<ReportPrimitiveField>,
537 VisitorFalse<ReportPrimitiveField>,
538 ReportPrimitiveFieldCallback<false>,
539 VisitorFalse<ReportPrimitiveField>);
Andreas Gampee7316932017-02-25 09:15:05 -0800540 }
541 }
542 return false;
543 }
544
545
546 private:
547 ReportPrimitiveField(ObjectTagTable* tag_table,
548 jlong class_tag,
549 const jvmtiHeapCallbacks* cb,
550 const void* user_data)
551 : tag_table_(tag_table), class_tag_(class_tag), cb_(cb), user_data_(user_data) {}
552
553 template <bool kReportStatic>
554 static bool ReportPrimitiveFieldCallback(art::ObjPtr<art::mirror::Object> obj,
555 art::ObjPtr<art::mirror::Class> klass,
556 art::ArtField& field,
557 size_t field_index,
558 ReportPrimitiveField* user_data)
559 REQUIRES_SHARED(art::Locks::mutator_lock_) {
560 art::Primitive::Type art_prim_type = field.GetTypeAsPrimitiveType();
561 jvmtiPrimitiveType prim_type =
562 static_cast<jvmtiPrimitiveType>(art::Primitive::Descriptor(art_prim_type)[0]);
563 DCHECK(prim_type == JVMTI_PRIMITIVE_TYPE_BOOLEAN ||
564 prim_type == JVMTI_PRIMITIVE_TYPE_BYTE ||
565 prim_type == JVMTI_PRIMITIVE_TYPE_CHAR ||
566 prim_type == JVMTI_PRIMITIVE_TYPE_SHORT ||
567 prim_type == JVMTI_PRIMITIVE_TYPE_INT ||
568 prim_type == JVMTI_PRIMITIVE_TYPE_LONG ||
569 prim_type == JVMTI_PRIMITIVE_TYPE_FLOAT ||
570 prim_type == JVMTI_PRIMITIVE_TYPE_DOUBLE);
571 jvmtiHeapReferenceInfo info;
572 info.field.index = field_index;
573
574 jvalue value;
575 memset(&value, 0, sizeof(jvalue));
576 art::ObjPtr<art::mirror::Object> src = kReportStatic ? klass : obj;
577 switch (art_prim_type) {
578 case art::Primitive::Type::kPrimBoolean:
579 value.z = field.GetBoolean(src) == 0 ? JNI_FALSE : JNI_TRUE;
580 break;
581 case art::Primitive::Type::kPrimByte:
582 value.b = field.GetByte(src);
583 break;
584 case art::Primitive::Type::kPrimChar:
585 value.c = field.GetChar(src);
586 break;
587 case art::Primitive::Type::kPrimShort:
588 value.s = field.GetShort(src);
589 break;
590 case art::Primitive::Type::kPrimInt:
591 value.i = field.GetInt(src);
592 break;
593 case art::Primitive::Type::kPrimLong:
594 value.j = field.GetLong(src);
595 break;
596 case art::Primitive::Type::kPrimFloat:
597 value.f = field.GetFloat(src);
598 break;
599 case art::Primitive::Type::kPrimDouble:
600 value.d = field.GetDouble(src);
601 break;
602 case art::Primitive::Type::kPrimVoid:
603 case art::Primitive::Type::kPrimNot: {
604 LOG(FATAL) << "Should not reach here";
605 UNREACHABLE();
606 }
607 }
608
609 jlong obj_tag = user_data->tag_table_->GetTagOrZero(src.Ptr());
610 const jlong saved_obj_tag = obj_tag;
611
612 jint ret = user_data->cb_->primitive_field_callback(kReportStatic
613 ? JVMTI_HEAP_REFERENCE_STATIC_FIELD
614 : JVMTI_HEAP_REFERENCE_FIELD,
615 &info,
616 user_data->class_tag_,
617 &obj_tag,
618 value,
619 prim_type,
620 const_cast<void*>(user_data->user_data_));
621
622 if (saved_obj_tag != obj_tag) {
623 user_data->tag_table_->Set(src.Ptr(), obj_tag);
624 }
625
626 if ((ret & JVMTI_VISIT_ABORT) != 0) {
627 return true;
628 }
629
630 return false;
631 }
632
633 ObjectTagTable* tag_table_;
634 jlong class_tag_;
635 const jvmtiHeapCallbacks* cb_;
636 const void* user_data_;
637};
638
Andreas Gampe6ea06072017-02-24 18:01:19 +0000639struct HeapFilter {
640 explicit HeapFilter(jint heap_filter)
641 : filter_out_tagged((heap_filter & JVMTI_HEAP_FILTER_TAGGED) != 0),
Andreas Gampee54d9922016-10-11 19:55:37 -0700642 filter_out_untagged((heap_filter & JVMTI_HEAP_FILTER_UNTAGGED) != 0),
643 filter_out_class_tagged((heap_filter & JVMTI_HEAP_FILTER_CLASS_TAGGED) != 0),
644 filter_out_class_untagged((heap_filter & JVMTI_HEAP_FILTER_CLASS_UNTAGGED) != 0),
645 any_filter(filter_out_tagged ||
646 filter_out_untagged ||
647 filter_out_class_tagged ||
Andreas Gampe6ea06072017-02-24 18:01:19 +0000648 filter_out_class_untagged) {
Andreas Gampee54d9922016-10-11 19:55:37 -0700649 }
650
Andreas Gampe6ea06072017-02-24 18:01:19 +0000651 bool ShouldReportByHeapFilter(jlong tag, jlong class_tag) const {
Andreas Gampee54d9922016-10-11 19:55:37 -0700652 if (!any_filter) {
653 return true;
654 }
655
656 if ((tag == 0 && filter_out_untagged) || (tag != 0 && filter_out_tagged)) {
657 return false;
658 }
659
660 if ((class_tag == 0 && filter_out_class_untagged) ||
661 (class_tag != 0 && filter_out_class_tagged)) {
662 return false;
663 }
664
665 return true;
666 }
667
Andreas Gampee54d9922016-10-11 19:55:37 -0700668 const bool filter_out_tagged;
669 const bool filter_out_untagged;
670 const bool filter_out_class_tagged;
671 const bool filter_out_class_untagged;
672 const bool any_filter;
Andreas Gampe6ea06072017-02-24 18:01:19 +0000673};
674
675} // namespace
676
Andreas Gampe9e38a502017-03-06 08:19:26 -0800677void HeapUtil::Register() {
678 art::Runtime::Current()->AddSystemWeakHolder(&gIndexCachingTable);
679}
680
681void HeapUtil::Unregister() {
682 art::Runtime::Current()->RemoveSystemWeakHolder(&gIndexCachingTable);
683}
684
Alex Lightbbbcb532018-08-30 12:50:27 -0700685jvmtiError HeapUtil::IterateOverInstancesOfClass(jvmtiEnv* env,
686 jclass klass,
687 jvmtiHeapObjectFilter filter,
688 jvmtiHeapObjectCallback cb,
689 const void* user_data) {
690 if (cb == nullptr || klass == nullptr) {
691 return ERR(NULL_POINTER);
692 }
693
694 art::Thread* self = art::Thread::Current();
695 art::ScopedObjectAccess soa(self); // Now we know we have the shared lock.
696 art::StackHandleScope<1> hs(self);
697
698 art::ObjPtr<art::mirror::Object> klass_ptr(soa.Decode<art::mirror::Class>(klass));
699 if (!klass_ptr->IsClass()) {
700 return ERR(INVALID_CLASS);
701 }
702 art::Handle<art::mirror::Class> filter_klass(hs.NewHandle(klass_ptr->AsClass()));
703 if (filter_klass->IsInterface()) {
704 // nothing is an 'instance' of an interface so just return without walking anything.
705 return OK;
706 }
707
708 ObjectTagTable* tag_table = ArtJvmTiEnv::AsArtJvmTiEnv(env)->object_tag_table.get();
709 bool stop_reports = false;
710 auto visitor = [&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
711 // Early return, as we can't really stop visiting.
712 if (stop_reports) {
713 return;
714 }
715
716 art::ScopedAssertNoThreadSuspension no_suspension("IterateOverInstancesOfClass");
717
718 art::ObjPtr<art::mirror::Class> klass = obj->GetClass();
719
720 if (filter_klass != nullptr && !filter_klass->IsAssignableFrom(klass)) {
721 return;
722 }
723
724 jlong tag = 0;
725 tag_table->GetTag(obj, &tag);
726 if ((filter != JVMTI_HEAP_OBJECT_EITHER) &&
727 ((tag == 0 && filter == JVMTI_HEAP_OBJECT_TAGGED) ||
728 (tag != 0 && filter == JVMTI_HEAP_OBJECT_UNTAGGED))) {
729 return;
730 }
731
732 jlong class_tag = 0;
733 tag_table->GetTag(klass.Ptr(), &class_tag);
734
735 jlong saved_tag = tag;
736 jint ret = cb(class_tag, obj->SizeOf(), &tag, const_cast<void*>(user_data));
737
738 stop_reports = (ret == JVMTI_ITERATION_ABORT);
739
740 if (tag != saved_tag) {
741 tag_table->Set(obj, tag);
742 }
743 };
744 art::Runtime::Current()->GetHeap()->VisitObjects(visitor);
745
746 return OK;
747}
748
Andreas Gampe1c158a02017-07-13 17:26:19 -0700749template <typename T>
750static jvmtiError DoIterateThroughHeap(T fn,
751 jvmtiEnv* env,
752 ObjectTagTable* tag_table,
753 jint heap_filter_int,
754 jclass klass,
755 const jvmtiHeapCallbacks* callbacks,
756 const void* user_data) {
757 if (callbacks == nullptr) {
758 return ERR(NULL_POINTER);
Andreas Gampe6ea06072017-02-24 18:01:19 +0000759 }
760
Andreas Gampe1c158a02017-07-13 17:26:19 -0700761 art::Thread* self = art::Thread::Current();
762 art::ScopedObjectAccess soa(self); // Now we know we have the shared lock.
Andreas Gampef787fd32017-05-09 16:04:20 -0700763
Andreas Gampe1c158a02017-07-13 17:26:19 -0700764 bool stop_reports = false;
765 const HeapFilter heap_filter(heap_filter_int);
766 art::ObjPtr<art::mirror::Class> filter_klass = soa.Decode<art::mirror::Class>(klass);
767 auto visitor = [&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampef787fd32017-05-09 16:04:20 -0700768 // Early return, as we can't really stop visiting.
769 if (stop_reports) {
770 return;
771 }
772
773 art::ScopedAssertNoThreadSuspension no_suspension("IterateThroughHeapCallback");
774
775 jlong tag = 0;
776 tag_table->GetTag(obj, &tag);
777
778 jlong class_tag = 0;
779 art::ObjPtr<art::mirror::Class> klass = obj->GetClass();
780 tag_table->GetTag(klass.Ptr(), &class_tag);
781 // For simplicity, even if we find a tag = 0, assume 0 = not tagged.
782
783 if (!heap_filter.ShouldReportByHeapFilter(tag, class_tag)) {
784 return;
785 }
786
787 if (filter_klass != nullptr) {
788 if (filter_klass != klass) {
789 return;
790 }
791 }
792
793 jlong size = obj->SizeOf();
794
795 jint length = -1;
796 if (obj->IsArrayInstance()) {
797 length = obj->AsArray()->GetLength();
798 }
799
800 jlong saved_tag = tag;
Andreas Gampe1c158a02017-07-13 17:26:19 -0700801 jint ret = fn(obj, callbacks, class_tag, size, &tag, length, const_cast<void*>(user_data));
Andreas Gampef787fd32017-05-09 16:04:20 -0700802
803 if (tag != saved_tag) {
804 tag_table->Set(obj, tag);
805 }
806
807 stop_reports = (ret & JVMTI_VISIT_ABORT) != 0;
808
809 if (!stop_reports) {
810 jint string_ret = ReportString(obj, env, tag_table, callbacks, user_data);
811 stop_reports = (string_ret & JVMTI_VISIT_ABORT) != 0;
812 }
813
814 if (!stop_reports) {
815 jint array_ret = ReportPrimitiveArray(obj, env, tag_table, callbacks, user_data);
816 stop_reports = (array_ret & JVMTI_VISIT_ABORT) != 0;
817 }
818
819 if (!stop_reports) {
820 stop_reports = ReportPrimitiveField::Report(obj, tag_table, callbacks, user_data);
821 }
Andreas Gampe1c158a02017-07-13 17:26:19 -0700822 };
823 art::Runtime::Current()->GetHeap()->VisitObjects(visitor);
Andreas Gampee54d9922016-10-11 19:55:37 -0700824
825 return ERR(NONE);
826}
827
Andreas Gampef787fd32017-05-09 16:04:20 -0700828jvmtiError HeapUtil::IterateThroughHeap(jvmtiEnv* env,
829 jint heap_filter,
830 jclass klass,
831 const jvmtiHeapCallbacks* callbacks,
832 const void* user_data) {
833 auto JvmtiIterateHeap = [](art::mirror::Object* obj ATTRIBUTE_UNUSED,
834 const jvmtiHeapCallbacks* cb_callbacks,
835 jlong class_tag,
836 jlong size,
837 jlong* tag,
838 jint length,
839 void* cb_user_data)
840 REQUIRES_SHARED(art::Locks::mutator_lock_) {
841 return cb_callbacks->heap_iteration_callback(class_tag,
842 size,
843 tag,
844 length,
845 cb_user_data);
846 };
847 return DoIterateThroughHeap(JvmtiIterateHeap,
848 env,
849 ArtJvmTiEnv::AsArtJvmTiEnv(env)->object_tag_table.get(),
850 heap_filter,
851 klass,
852 callbacks,
853 user_data);
854}
855
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100856class FollowReferencesHelper final {
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700857 public:
858 FollowReferencesHelper(HeapUtil* h,
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800859 jvmtiEnv* jvmti_env,
Andreas Gampe638a6932016-12-02 19:11:17 -0800860 art::ObjPtr<art::mirror::Object> initial_object,
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700861 const jvmtiHeapCallbacks* callbacks,
Andreas Gampe38da9f22017-02-20 13:35:36 -0800862 art::ObjPtr<art::mirror::Class> class_filter,
Andreas Gampe6ea06072017-02-24 18:01:19 +0000863 jint heap_filter,
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700864 const void* user_data)
Andreas Gampe3ec8e402017-02-21 15:49:53 -0800865 : env(jvmti_env),
866 tag_table_(h->GetTags()),
Andreas Gampe638a6932016-12-02 19:11:17 -0800867 initial_object_(initial_object),
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700868 callbacks_(callbacks),
Andreas Gampe38da9f22017-02-20 13:35:36 -0800869 class_filter_(class_filter),
Andreas Gampe6ea06072017-02-24 18:01:19 +0000870 heap_filter_(heap_filter),
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700871 user_data_(user_data),
872 start_(0),
873 stop_reports_(false) {
874 }
875
876 void Init()
877 REQUIRES_SHARED(art::Locks::mutator_lock_)
878 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
Andreas Gampe638a6932016-12-02 19:11:17 -0800879 if (initial_object_.IsNull()) {
880 CollectAndReportRootsVisitor carrv(this, tag_table_, &worklist_, &visited_);
Andreas Gampef10dfcd2016-12-02 14:42:33 -0800881
882 // We need precise info (e.g., vregs).
883 constexpr art::VisitRootFlags kRootFlags = static_cast<art::VisitRootFlags>(
884 art::VisitRootFlags::kVisitRootFlagAllRoots | art::VisitRootFlags::kVisitRootFlagPrecise);
885 art::Runtime::Current()->VisitRoots(&carrv, kRootFlags);
886
Andreas Gampe638a6932016-12-02 19:11:17 -0800887 art::Runtime::Current()->VisitImageRoots(&carrv);
888 stop_reports_ = carrv.IsStopReports();
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700889
Andreas Gampe638a6932016-12-02 19:11:17 -0800890 if (stop_reports_) {
891 worklist_.clear();
892 }
893 } else {
894 visited_.insert(initial_object_.Ptr());
895 worklist_.push_back(initial_object_.Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700896 }
897 }
898
899 void Work()
900 REQUIRES_SHARED(art::Locks::mutator_lock_)
901 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
902 // Currently implemented as a BFS. To lower overhead, we don't erase elements immediately
903 // from the head of the work list, instead postponing until there's a gap that's "large."
904 //
905 // Alternatively, we can implement a DFS and use the work list as a stack.
906 while (start_ < worklist_.size()) {
907 art::mirror::Object* cur_obj = worklist_[start_];
908 start_++;
909
910 if (start_ >= kMaxStart) {
911 worklist_.erase(worklist_.begin(), worklist_.begin() + start_);
912 start_ = 0;
913 }
914
915 VisitObject(cur_obj);
916
917 if (stop_reports_) {
918 break;
919 }
920 }
921 }
922
923 private:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100924 class CollectAndReportRootsVisitor final : public art::RootVisitor {
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700925 public:
926 CollectAndReportRootsVisitor(FollowReferencesHelper* helper,
927 ObjectTagTable* tag_table,
928 std::vector<art::mirror::Object*>* worklist,
929 std::unordered_set<art::mirror::Object*>* visited)
930 : helper_(helper),
931 tag_table_(tag_table),
932 worklist_(worklist),
933 visited_(visited),
934 stop_reports_(false) {}
935
936 void VisitRoots(art::mirror::Object*** roots, size_t count, const art::RootInfo& info)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100937 override
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700938 REQUIRES_SHARED(art::Locks::mutator_lock_)
939 REQUIRES(!*helper_->tag_table_->GetAllowDisallowLock()) {
940 for (size_t i = 0; i != count; ++i) {
941 AddRoot(*roots[i], info);
942 }
943 }
944
945 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
946 size_t count,
947 const art::RootInfo& info)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100948 override REQUIRES_SHARED(art::Locks::mutator_lock_)
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700949 REQUIRES(!*helper_->tag_table_->GetAllowDisallowLock()) {
950 for (size_t i = 0; i != count; ++i) {
951 AddRoot(roots[i]->AsMirrorPtr(), info);
952 }
953 }
954
955 bool IsStopReports() {
956 return stop_reports_;
957 }
958
959 private:
960 void AddRoot(art::mirror::Object* root_obj, const art::RootInfo& info)
961 REQUIRES_SHARED(art::Locks::mutator_lock_)
962 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
Andreas Gampec756f082017-03-29 17:58:28 -0700963 if (stop_reports_) {
964 return;
965 }
966 bool add_to_worklist = ReportRoot(root_obj, info);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700967 // We use visited_ to mark roots already so we do not need another set.
968 if (visited_->find(root_obj) == visited_->end()) {
Andreas Gampec756f082017-03-29 17:58:28 -0700969 if (add_to_worklist) {
Andreas Gampee0f8ed92017-04-13 16:52:23 -0700970 visited_->insert(root_obj);
Andreas Gampec756f082017-03-29 17:58:28 -0700971 worklist_->push_back(root_obj);
972 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700973 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700974 }
975
Andreas Gampe93c30902016-11-18 13:30:30 -0800976 // Remove NO_THREAD_SAFETY_ANALYSIS once ASSERT_CAPABILITY works correctly.
977 art::Thread* FindThread(const art::RootInfo& info) NO_THREAD_SAFETY_ANALYSIS {
978 art::Locks::thread_list_lock_->AssertExclusiveHeld(art::Thread::Current());
979 return art::Runtime::Current()->GetThreadList()->FindThreadByThreadId(info.GetThreadId());
980 }
981
Andreas Gampe70bfc8a2016-11-03 11:04:15 -0700982 jvmtiHeapReferenceKind GetReferenceKind(const art::RootInfo& info,
983 jvmtiHeapReferenceInfo* ref_info)
984 REQUIRES_SHARED(art::Locks::mutator_lock_) {
985 // TODO: Fill in ref_info.
986 memset(ref_info, 0, sizeof(jvmtiHeapReferenceInfo));
987
988 switch (info.GetType()) {
989 case art::RootType::kRootJNIGlobal:
990 return JVMTI_HEAP_REFERENCE_JNI_GLOBAL;
991
992 case art::RootType::kRootJNILocal:
Andreas Gampe93c30902016-11-18 13:30:30 -0800993 {
994 uint32_t thread_id = info.GetThreadId();
995 ref_info->jni_local.thread_id = thread_id;
996
997 art::Thread* thread = FindThread(info);
998 if (thread != nullptr) {
Andreas Gampe202f85a2017-02-06 10:23:26 -0800999 art::mirror::Object* thread_obj;
Andreas Gampe93c30902016-11-18 13:30:30 -08001000 if (thread->IsStillStarting()) {
1001 thread_obj = nullptr;
1002 } else {
Andreas Gampe202f85a2017-02-06 10:23:26 -08001003 thread_obj = thread->GetPeerFromOtherThread();
Andreas Gampe93c30902016-11-18 13:30:30 -08001004 }
1005 if (thread_obj != nullptr) {
1006 ref_info->jni_local.thread_tag = tag_table_->GetTagOrZero(thread_obj);
1007 }
1008 }
1009
1010 // TODO: We don't have this info.
1011 if (thread != nullptr) {
1012 ref_info->jni_local.depth = 0;
Andreas Gampe6e897762018-10-16 13:09:32 -07001013 art::ArtMethod* method = thread->GetCurrentMethod(nullptr,
1014 /* check_suspended= */ true,
1015 /* abort_on_error= */ false);
Andreas Gampe93c30902016-11-18 13:30:30 -08001016 if (method != nullptr) {
1017 ref_info->jni_local.method = art::jni::EncodeArtMethod(method);
1018 }
1019 }
1020
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001021 return JVMTI_HEAP_REFERENCE_JNI_LOCAL;
Andreas Gampe93c30902016-11-18 13:30:30 -08001022 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001023
1024 case art::RootType::kRootJavaFrame:
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001025 {
1026 uint32_t thread_id = info.GetThreadId();
1027 ref_info->stack_local.thread_id = thread_id;
1028
1029 art::Thread* thread = FindThread(info);
1030 if (thread != nullptr) {
Andreas Gampe202f85a2017-02-06 10:23:26 -08001031 art::mirror::Object* thread_obj;
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001032 if (thread->IsStillStarting()) {
1033 thread_obj = nullptr;
1034 } else {
Andreas Gampe202f85a2017-02-06 10:23:26 -08001035 thread_obj = thread->GetPeerFromOtherThread();
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001036 }
1037 if (thread_obj != nullptr) {
1038 ref_info->stack_local.thread_tag = tag_table_->GetTagOrZero(thread_obj);
1039 }
1040 }
1041
1042 auto& java_info = static_cast<const art::JavaFrameRootInfo&>(info);
Alex Light0054aa52019-09-10 16:46:48 -07001043 size_t vreg = java_info.GetVReg();
1044 ref_info->stack_local.slot = static_cast<jint>(
1045 vreg <= art::JavaFrameRootInfo::kMaxVReg ? vreg : -1);
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001046 const art::StackVisitor* visitor = java_info.GetVisitor();
1047 ref_info->stack_local.location =
Andreas Gampe6e897762018-10-16 13:09:32 -07001048 static_cast<jlocation>(visitor->GetDexPc(/* abort_on_failure= */ false));
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001049 ref_info->stack_local.depth = static_cast<jint>(visitor->GetFrameDepth());
1050 art::ArtMethod* method = visitor->GetMethod();
1051 if (method != nullptr) {
1052 ref_info->stack_local.method = art::jni::EncodeArtMethod(method);
1053 }
1054
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001055 return JVMTI_HEAP_REFERENCE_STACK_LOCAL;
Andreas Gampef10dfcd2016-12-02 14:42:33 -08001056 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001057
1058 case art::RootType::kRootNativeStack:
1059 case art::RootType::kRootThreadBlock:
1060 case art::RootType::kRootThreadObject:
1061 return JVMTI_HEAP_REFERENCE_THREAD;
1062
1063 case art::RootType::kRootStickyClass:
1064 case art::RootType::kRootInternedString:
1065 // Note: this isn't a root in the RI.
1066 return JVMTI_HEAP_REFERENCE_SYSTEM_CLASS;
1067
1068 case art::RootType::kRootMonitorUsed:
1069 case art::RootType::kRootJNIMonitor:
1070 return JVMTI_HEAP_REFERENCE_MONITOR;
1071
1072 case art::RootType::kRootFinalizing:
1073 case art::RootType::kRootDebugger:
1074 case art::RootType::kRootReferenceCleanup:
1075 case art::RootType::kRootVMInternal:
1076 case art::RootType::kRootUnknown:
1077 return JVMTI_HEAP_REFERENCE_OTHER;
1078 }
1079 LOG(FATAL) << "Unreachable";
1080 UNREACHABLE();
1081 }
1082
Andreas Gampec756f082017-03-29 17:58:28 -07001083 bool ReportRoot(art::mirror::Object* root_obj, const art::RootInfo& info)
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001084 REQUIRES_SHARED(art::Locks::mutator_lock_)
1085 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1086 jvmtiHeapReferenceInfo ref_info;
1087 jvmtiHeapReferenceKind kind = GetReferenceKind(info, &ref_info);
1088 jint result = helper_->ReportReference(kind, &ref_info, nullptr, root_obj);
1089 if ((result & JVMTI_VISIT_ABORT) != 0) {
1090 stop_reports_ = true;
1091 }
Andreas Gampec756f082017-03-29 17:58:28 -07001092 return (result & JVMTI_VISIT_OBJECTS) != 0;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001093 }
1094
1095 private:
1096 FollowReferencesHelper* helper_;
1097 ObjectTagTable* tag_table_;
1098 std::vector<art::mirror::Object*>* worklist_;
1099 std::unordered_set<art::mirror::Object*>* visited_;
1100 bool stop_reports_;
1101 };
1102
1103 void VisitObject(art::mirror::Object* obj)
1104 REQUIRES_SHARED(art::Locks::mutator_lock_)
1105 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1106 if (obj->IsClass()) {
Vladimir Marko4617d582019-03-28 13:48:31 +00001107 VisitClass(obj->AsClass().Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001108 return;
1109 }
1110 if (obj->IsArrayInstance()) {
1111 VisitArray(obj);
1112 return;
1113 }
1114
Andreas Gampe95114602017-02-28 15:47:44 -08001115 // All instance fields.
1116 auto report_instance_field = [&](art::ObjPtr<art::mirror::Object> src,
1117 art::ObjPtr<art::mirror::Class> obj_klass ATTRIBUTE_UNUSED,
1118 art::ArtField& field,
1119 size_t field_index,
1120 void* user_data ATTRIBUTE_UNUSED)
1121 REQUIRES_SHARED(art::Locks::mutator_lock_)
1122 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1123 art::ObjPtr<art::mirror::Object> field_value = field.GetObject(src);
1124 if (field_value != nullptr) {
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001125 jvmtiHeapReferenceInfo reference_info;
1126 memset(&reference_info, 0, sizeof(reference_info));
1127
Andreas Gampe95114602017-02-28 15:47:44 -08001128 reference_info.field.index = field_index;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001129
1130 jvmtiHeapReferenceKind kind =
Andreas Gampe95114602017-02-28 15:47:44 -08001131 field.GetOffset().Int32Value() == art::mirror::Object::ClassOffset().Int32Value()
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001132 ? JVMTI_HEAP_REFERENCE_CLASS
1133 : JVMTI_HEAP_REFERENCE_FIELD;
1134 const jvmtiHeapReferenceInfo* reference_info_ptr =
1135 kind == JVMTI_HEAP_REFERENCE_CLASS ? nullptr : &reference_info;
1136
Andreas Gampe95114602017-02-28 15:47:44 -08001137 return !ReportReferenceMaybeEnqueue(kind, reference_info_ptr, src.Ptr(), field_value.Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001138 }
Andreas Gampe95114602017-02-28 15:47:44 -08001139 return false;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001140 };
Andreas Gampe95114602017-02-28 15:47:44 -08001141 stop_reports_ = FieldVisitor<void, true>::ReportFields(obj,
1142 nullptr,
1143 VisitorFalse<void>,
1144 VisitorFalse<void>,
1145 VisitorFalse<void>,
1146 report_instance_field);
1147 if (stop_reports_) {
1148 return;
Andreas Gampe3ec8e402017-02-21 15:49:53 -08001149 }
Andreas Gampee7316932017-02-25 09:15:05 -08001150
Andreas Gampe95114602017-02-28 15:47:44 -08001151 jint string_ret = ReportString(obj, env, tag_table_, callbacks_, user_data_);
1152 stop_reports_ = (string_ret & JVMTI_VISIT_ABORT) != 0;
1153 if (stop_reports_) {
1154 return;
Andreas Gampee7316932017-02-25 09:15:05 -08001155 }
Andreas Gampe95114602017-02-28 15:47:44 -08001156
1157 stop_reports_ = ReportPrimitiveField::Report(obj, tag_table_, callbacks_, user_data_);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001158 }
1159
1160 void VisitArray(art::mirror::Object* array)
1161 REQUIRES_SHARED(art::Locks::mutator_lock_)
1162 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1163 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_CLASS,
1164 nullptr,
1165 array,
1166 array->GetClass());
1167 if (stop_reports_) {
1168 return;
1169 }
1170
1171 if (array->IsObjectArray()) {
Vladimir Marko4617d582019-03-28 13:48:31 +00001172 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> obj_array =
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001173 array->AsObjectArray<art::mirror::Object>();
1174 int32_t length = obj_array->GetLength();
1175 for (int32_t i = 0; i != length; ++i) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00001176 art::ObjPtr<art::mirror::Object> elem = obj_array->GetWithoutChecks(i);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001177 if (elem != nullptr) {
1178 jvmtiHeapReferenceInfo reference_info;
1179 reference_info.array.index = i;
1180 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT,
1181 &reference_info,
1182 array,
Vladimir Marko423bebb2019-03-26 15:17:21 +00001183 elem.Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001184 if (stop_reports_) {
1185 break;
1186 }
1187 }
1188 }
Andreas Gampebecd6ad2017-02-22 19:20:37 -08001189 } else {
1190 if (!stop_reports_) {
1191 jint array_ret = ReportPrimitiveArray(array, env, tag_table_, callbacks_, user_data_);
1192 stop_reports_ = (array_ret & JVMTI_VISIT_ABORT) != 0;
1193 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001194 }
1195 }
1196
1197 void VisitClass(art::mirror::Class* klass)
1198 REQUIRES_SHARED(art::Locks::mutator_lock_)
1199 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1200 // TODO: Are erroneous classes reported? Are non-prepared ones? For now, just use resolved ones.
1201 if (!klass->IsResolved()) {
1202 return;
1203 }
1204
1205 // Superclass.
1206 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_SUPERCLASS,
1207 nullptr,
1208 klass,
Andreas Gampe98104992018-10-16 12:49:47 -07001209 klass->GetSuperClass().Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001210 if (stop_reports_) {
1211 return;
1212 }
1213
1214 // Directly implemented or extended interfaces.
1215 art::Thread* self = art::Thread::Current();
1216 art::StackHandleScope<1> hs(self);
1217 art::Handle<art::mirror::Class> h_klass(hs.NewHandle<art::mirror::Class>(klass));
1218 for (size_t i = 0; i < h_klass->NumDirectInterfaces(); ++i) {
1219 art::ObjPtr<art::mirror::Class> inf_klass =
Vladimir Marko19a4d372016-12-08 14:41:46 +00001220 art::mirror::Class::ResolveDirectInterface(self, h_klass, i);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001221 if (inf_klass == nullptr) {
1222 // TODO: With a resolved class this should not happen...
1223 self->ClearException();
1224 break;
1225 }
1226
1227 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_INTERFACE,
1228 nullptr,
1229 klass,
1230 inf_klass.Ptr());
1231 if (stop_reports_) {
1232 return;
1233 }
1234 }
1235
1236 // Classloader.
1237 // TODO: What about the boot classpath loader? We'll skip for now, but do we have to find the
1238 // fake BootClassLoader?
1239 if (klass->GetClassLoader() != nullptr) {
1240 stop_reports_ = !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_CLASS_LOADER,
1241 nullptr,
1242 klass,
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001243 klass->GetClassLoader().Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001244 if (stop_reports_) {
1245 return;
1246 }
1247 }
1248 DCHECK_EQ(h_klass.Get(), klass);
1249
1250 // Declared static fields.
Andreas Gampe95114602017-02-28 15:47:44 -08001251 auto report_static_field = [&](art::ObjPtr<art::mirror::Object> obj ATTRIBUTE_UNUSED,
1252 art::ObjPtr<art::mirror::Class> obj_klass,
1253 art::ArtField& field,
1254 size_t field_index,
1255 void* user_data ATTRIBUTE_UNUSED)
1256 REQUIRES_SHARED(art::Locks::mutator_lock_)
1257 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1258 art::ObjPtr<art::mirror::Object> field_value = field.GetObject(obj_klass);
1259 if (field_value != nullptr) {
1260 jvmtiHeapReferenceInfo reference_info;
1261 memset(&reference_info, 0, sizeof(reference_info));
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001262
Andreas Gampe95114602017-02-28 15:47:44 -08001263 reference_info.field.index = static_cast<jint>(field_index);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001264
Andreas Gampe95114602017-02-28 15:47:44 -08001265 return !ReportReferenceMaybeEnqueue(JVMTI_HEAP_REFERENCE_STATIC_FIELD,
1266 &reference_info,
1267 obj_klass.Ptr(),
1268 field_value.Ptr());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001269 }
Andreas Gampe95114602017-02-28 15:47:44 -08001270 return false;
1271 };
1272 stop_reports_ = FieldVisitor<void, false>::ReportFields(klass,
1273 nullptr,
1274 VisitorFalse<void>,
1275 report_static_field,
1276 VisitorFalse<void>,
1277 VisitorFalse<void>);
1278 if (stop_reports_) {
1279 return;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001280 }
Andreas Gampee7316932017-02-25 09:15:05 -08001281
Andreas Gampe95114602017-02-28 15:47:44 -08001282 stop_reports_ = ReportPrimitiveField::Report(klass, tag_table_, callbacks_, user_data_);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001283 }
1284
1285 void MaybeEnqueue(art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1286 if (visited_.find(obj) == visited_.end()) {
1287 worklist_.push_back(obj);
1288 visited_.insert(obj);
1289 }
1290 }
1291
1292 bool ReportReferenceMaybeEnqueue(jvmtiHeapReferenceKind kind,
1293 const jvmtiHeapReferenceInfo* reference_info,
1294 art::mirror::Object* referree,
1295 art::mirror::Object* referrer)
1296 REQUIRES_SHARED(art::Locks::mutator_lock_)
1297 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1298 jint result = ReportReference(kind, reference_info, referree, referrer);
1299 if ((result & JVMTI_VISIT_ABORT) == 0) {
1300 if ((result & JVMTI_VISIT_OBJECTS) != 0) {
1301 MaybeEnqueue(referrer);
1302 }
1303 return true;
1304 } else {
1305 return false;
1306 }
1307 }
1308
1309 jint ReportReference(jvmtiHeapReferenceKind kind,
1310 const jvmtiHeapReferenceInfo* reference_info,
1311 art::mirror::Object* referrer,
1312 art::mirror::Object* referree)
1313 REQUIRES_SHARED(art::Locks::mutator_lock_)
1314 REQUIRES(!*tag_table_->GetAllowDisallowLock()) {
1315 if (referree == nullptr || stop_reports_) {
1316 return 0;
1317 }
1318
Andreas Gampe38da9f22017-02-20 13:35:36 -08001319 if (UNLIKELY(class_filter_ != nullptr) && class_filter_ != referree->GetClass()) {
1320 return JVMTI_VISIT_OBJECTS;
1321 }
1322
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001323 const jlong class_tag = tag_table_->GetTagOrZero(referree->GetClass());
Andreas Gampe6ea06072017-02-24 18:01:19 +00001324 jlong tag = tag_table_->GetTagOrZero(referree);
1325
1326 if (!heap_filter_.ShouldReportByHeapFilter(tag, class_tag)) {
1327 return JVMTI_VISIT_OBJECTS;
1328 }
1329
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001330 const jlong referrer_class_tag =
1331 referrer == nullptr ? 0 : tag_table_->GetTagOrZero(referrer->GetClass());
1332 const jlong size = static_cast<jlong>(referree->SizeOf());
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001333 jlong saved_tag = tag;
1334 jlong referrer_tag = 0;
1335 jlong saved_referrer_tag = 0;
1336 jlong* referrer_tag_ptr;
1337 if (referrer == nullptr) {
1338 referrer_tag_ptr = nullptr;
1339 } else {
1340 if (referrer == referree) {
1341 referrer_tag_ptr = &tag;
1342 } else {
1343 referrer_tag = saved_referrer_tag = tag_table_->GetTagOrZero(referrer);
1344 referrer_tag_ptr = &referrer_tag;
1345 }
1346 }
Andreas Gampe38da9f22017-02-20 13:35:36 -08001347
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001348 jint length = -1;
1349 if (referree->IsArrayInstance()) {
1350 length = referree->AsArray()->GetLength();
1351 }
1352
1353 jint result = callbacks_->heap_reference_callback(kind,
1354 reference_info,
1355 class_tag,
1356 referrer_class_tag,
1357 size,
1358 &tag,
1359 referrer_tag_ptr,
1360 length,
1361 const_cast<void*>(user_data_));
1362
1363 if (tag != saved_tag) {
1364 tag_table_->Set(referree, tag);
1365 }
1366 if (referrer_tag != saved_referrer_tag) {
1367 tag_table_->Set(referrer, referrer_tag);
1368 }
1369
1370 return result;
1371 }
1372
Andreas Gampe3ec8e402017-02-21 15:49:53 -08001373 jvmtiEnv* env;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001374 ObjectTagTable* tag_table_;
Andreas Gampe638a6932016-12-02 19:11:17 -08001375 art::ObjPtr<art::mirror::Object> initial_object_;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001376 const jvmtiHeapCallbacks* callbacks_;
Andreas Gampe38da9f22017-02-20 13:35:36 -08001377 art::ObjPtr<art::mirror::Class> class_filter_;
Andreas Gampe6ea06072017-02-24 18:01:19 +00001378 const HeapFilter heap_filter_;
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001379 const void* user_data_;
1380
1381 std::vector<art::mirror::Object*> worklist_;
1382 size_t start_;
1383 static constexpr size_t kMaxStart = 1000000U;
1384
1385 std::unordered_set<art::mirror::Object*> visited_;
1386
1387 bool stop_reports_;
1388
1389 friend class CollectAndReportRootsVisitor;
1390};
1391
Andreas Gampe3ec8e402017-02-21 15:49:53 -08001392jvmtiError HeapUtil::FollowReferences(jvmtiEnv* env,
Andreas Gampe6ea06072017-02-24 18:01:19 +00001393 jint heap_filter,
Andreas Gampe38da9f22017-02-20 13:35:36 -08001394 jclass klass,
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001395 jobject initial_object,
1396 const jvmtiHeapCallbacks* callbacks,
1397 const void* user_data) {
1398 if (callbacks == nullptr) {
1399 return ERR(NULL_POINTER);
1400 }
1401
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001402 art::Thread* self = art::Thread::Current();
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001403
Andreas Gampe638a6932016-12-02 19:11:17 -08001404 art::gc::Heap* heap = art::Runtime::Current()->GetHeap();
1405 if (heap->IsGcConcurrentAndMoving()) {
1406 // Need to take a heap dump while GC isn't running. See the
1407 // comment in Heap::VisitObjects().
1408 heap->IncrementDisableMovingGC(self);
1409 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001410 {
Andreas Gampe638a6932016-12-02 19:11:17 -08001411 art::ScopedObjectAccess soa(self); // Now we know we have the shared lock.
Alex Light79d6c802019-06-27 15:50:11 +00001412 art::jni::ScopedEnableSuspendAllJniIdQueries sjni; // make sure we can get JNI ids.
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001413 art::ScopedThreadSuspension sts(self, art::kWaitingForVisitObjects);
1414 art::ScopedSuspendAll ssa("FollowReferences");
1415
Andreas Gampe38da9f22017-02-20 13:35:36 -08001416 art::ObjPtr<art::mirror::Class> class_filter = klass == nullptr
1417 ? nullptr
1418 : art::ObjPtr<art::mirror::Class>::DownCast(self->DecodeJObject(klass));
Andreas Gampe638a6932016-12-02 19:11:17 -08001419 FollowReferencesHelper frh(this,
Andreas Gampe3ec8e402017-02-21 15:49:53 -08001420 env,
Andreas Gampe638a6932016-12-02 19:11:17 -08001421 self->DecodeJObject(initial_object),
1422 callbacks,
Andreas Gampe38da9f22017-02-20 13:35:36 -08001423 class_filter,
Andreas Gampe6ea06072017-02-24 18:01:19 +00001424 heap_filter,
Andreas Gampe638a6932016-12-02 19:11:17 -08001425 user_data);
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001426 frh.Init();
1427 frh.Work();
1428 }
Andreas Gampe638a6932016-12-02 19:11:17 -08001429 if (heap->IsGcConcurrentAndMoving()) {
1430 heap->DecrementDisableMovingGC(self);
1431 }
Andreas Gampe70bfc8a2016-11-03 11:04:15 -07001432
1433 return ERR(NONE);
1434}
1435
Andreas Gampeaa8b60c2016-10-12 12:51:25 -07001436jvmtiError HeapUtil::GetLoadedClasses(jvmtiEnv* env,
1437 jint* class_count_ptr,
1438 jclass** classes_ptr) {
1439 if (class_count_ptr == nullptr || classes_ptr == nullptr) {
1440 return ERR(NULL_POINTER);
1441 }
1442
1443 class ReportClassVisitor : public art::ClassVisitor {
1444 public:
1445 explicit ReportClassVisitor(art::Thread* self) : self_(self) {}
1446
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001447 bool operator()(art::ObjPtr<art::mirror::Class> klass)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001448 override REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightf8a4a2c2017-06-22 08:43:37 -07001449 if (klass->IsLoaded() || klass->IsErroneous()) {
1450 classes_.push_back(self_->GetJniEnv()->AddLocalReference<jclass>(klass));
1451 }
Andreas Gampeaa8b60c2016-10-12 12:51:25 -07001452 return true;
1453 }
1454
1455 art::Thread* self_;
1456 std::vector<jclass> classes_;
1457 };
1458
1459 art::Thread* self = art::Thread::Current();
1460 ReportClassVisitor rcv(self);
1461 {
1462 art::ScopedObjectAccess soa(self);
1463 art::Runtime::Current()->GetClassLinker()->VisitClasses(&rcv);
1464 }
1465
1466 size_t size = rcv.classes_.size();
1467 jclass* classes = nullptr;
1468 jvmtiError alloc_ret = env->Allocate(static_cast<jlong>(size * sizeof(jclass)),
1469 reinterpret_cast<unsigned char**>(&classes));
1470 if (alloc_ret != ERR(NONE)) {
1471 return alloc_ret;
1472 }
1473
1474 for (size_t i = 0; i < size; ++i) {
1475 classes[i] = rcv.classes_[i];
1476 }
1477 *classes_ptr = classes;
1478 *class_count_ptr = static_cast<jint>(size);
1479
1480 return ERR(NONE);
1481}
1482
Andreas Gampe8da6d032016-10-31 19:31:03 -07001483jvmtiError HeapUtil::ForceGarbageCollection(jvmtiEnv* env ATTRIBUTE_UNUSED) {
Andreas Gampe6e897762018-10-16 13:09:32 -07001484 art::Runtime::Current()->GetHeap()->CollectGarbage(/* clear_soft_references= */ false);
Andreas Gampe8da6d032016-10-31 19:31:03 -07001485
1486 return ERR(NONE);
1487}
Andreas Gamped73aba42017-05-03 21:40:26 -07001488
1489static constexpr jint kHeapIdDefault = 0;
1490static constexpr jint kHeapIdImage = 1;
1491static constexpr jint kHeapIdZygote = 2;
1492static constexpr jint kHeapIdApp = 3;
1493
Andreas Gampe2eb25e42017-05-09 17:14:58 -07001494static jint GetHeapId(art::ObjPtr<art::mirror::Object> obj)
1495 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1496 if (obj == nullptr) {
1497 return -1;
1498 }
1499
1500 art::gc::Heap* const heap = art::Runtime::Current()->GetHeap();
1501 const art::gc::space::ContinuousSpace* const space =
1502 heap->FindContinuousSpaceFromObject(obj, true);
1503 jint heap_type = kHeapIdApp;
1504 if (space != nullptr) {
1505 if (space->IsZygoteSpace()) {
1506 heap_type = kHeapIdZygote;
1507 } else if (space->IsImageSpace() && heap->ObjectIsInBootImageSpace(obj)) {
1508 // Only count objects in the boot image as HPROF_HEAP_IMAGE, this leaves app image objects
1509 // as HPROF_HEAP_APP. b/35762934
1510 heap_type = kHeapIdImage;
1511 }
1512 } else {
1513 const auto* los = heap->GetLargeObjectsSpace();
1514 if (los->Contains(obj.Ptr()) && los->IsZygoteLargeObject(art::Thread::Current(), obj.Ptr())) {
1515 heap_type = kHeapIdZygote;
1516 }
1517 }
1518 return heap_type;
1519};
1520
Andreas Gamped73aba42017-05-03 21:40:26 -07001521jvmtiError HeapExtensions::GetObjectHeapId(jvmtiEnv* env, jlong tag, jint* heap_id, ...) {
1522 if (heap_id == nullptr) {
1523 return ERR(NULL_POINTER);
1524 }
1525
1526 art::Thread* self = art::Thread::Current();
1527
1528 auto work = [&]() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1529 ObjectTagTable* tag_table = ArtJvmTiEnv::AsArtJvmTiEnv(env)->object_tag_table.get();
1530 art::ObjPtr<art::mirror::Object> obj = tag_table->Find(tag);
Andreas Gampe2eb25e42017-05-09 17:14:58 -07001531 jint heap_type = GetHeapId(obj);
1532 if (heap_type == -1) {
Andreas Gamped73aba42017-05-03 21:40:26 -07001533 return ERR(NOT_FOUND);
1534 }
Andreas Gamped73aba42017-05-03 21:40:26 -07001535 *heap_id = heap_type;
1536 return ERR(NONE);
1537 };
1538
1539 if (!art::Locks::mutator_lock_->IsSharedHeld(self)) {
1540 if (!self->IsThreadSuspensionAllowable()) {
1541 return ERR(INTERNAL);
1542 }
1543 art::ScopedObjectAccess soa(self);
1544 return work();
1545 } else {
1546 // We cannot use SOA in this case. We might be holding the lock, but may not be in the
1547 // runnable state (e.g., during GC).
1548 art::Locks::mutator_lock_->AssertSharedHeld(self);
1549 // TODO: Investigate why ASSERT_SHARED_CAPABILITY doesn't work.
1550 auto annotalysis_workaround = [&]() NO_THREAD_SAFETY_ANALYSIS {
1551 return work();
1552 };
1553 return annotalysis_workaround();
1554 }
1555}
1556
1557static jvmtiError CopyStringAndReturn(jvmtiEnv* env, const char* in, char** out) {
1558 jvmtiError error;
1559 JvmtiUniquePtr<char[]> param_name = CopyString(env, in, &error);
1560 if (param_name == nullptr) {
1561 return error;
1562 }
1563 *out = param_name.release();
1564 return ERR(NONE);
1565}
1566
1567static constexpr const char* kHeapIdDefaultName = "default";
1568static constexpr const char* kHeapIdImageName = "image";
1569static constexpr const char* kHeapIdZygoteName = "zygote";
1570static constexpr const char* kHeapIdAppName = "app";
1571
1572jvmtiError HeapExtensions::GetHeapName(jvmtiEnv* env, jint heap_id, char** heap_name, ...) {
1573 switch (heap_id) {
1574 case kHeapIdDefault:
1575 return CopyStringAndReturn(env, kHeapIdDefaultName, heap_name);
1576 case kHeapIdImage:
1577 return CopyStringAndReturn(env, kHeapIdImageName, heap_name);
1578 case kHeapIdZygote:
1579 return CopyStringAndReturn(env, kHeapIdZygoteName, heap_name);
1580 case kHeapIdApp:
1581 return CopyStringAndReturn(env, kHeapIdAppName, heap_name);
1582
1583 default:
1584 return ERR(ILLEGAL_ARGUMENT);
1585 }
1586}
1587
Andreas Gampe2eb25e42017-05-09 17:14:58 -07001588jvmtiError HeapExtensions::IterateThroughHeapExt(jvmtiEnv* env,
1589 jint heap_filter,
1590 jclass klass,
1591 const jvmtiHeapCallbacks* callbacks,
1592 const void* user_data) {
1593 if (ArtJvmTiEnv::AsArtJvmTiEnv(env)->capabilities.can_tag_objects != 1) { \
1594 return ERR(MUST_POSSESS_CAPABILITY); \
1595 }
1596
1597 // ART extension API: Also pass the heap id.
1598 auto ArtIterateHeap = [](art::mirror::Object* obj,
1599 const jvmtiHeapCallbacks* cb_callbacks,
1600 jlong class_tag,
1601 jlong size,
1602 jlong* tag,
1603 jint length,
1604 void* cb_user_data)
1605 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1606 jint heap_id = GetHeapId(obj);
1607 using ArtExtensionAPI = jint (*)(jlong, jlong, jlong*, jint length, void*, jint);
1608 return reinterpret_cast<ArtExtensionAPI>(cb_callbacks->heap_iteration_callback)(
1609 class_tag, size, tag, length, cb_user_data, heap_id);
1610 };
1611 return DoIterateThroughHeap(ArtIterateHeap,
1612 env,
1613 ArtJvmTiEnv::AsArtJvmTiEnv(env)->object_tag_table.get(),
1614 heap_filter,
1615 klass,
1616 callbacks,
1617 user_data);
1618}
1619
Alex Lightc14ec8f2019-07-18 16:08:41 -07001620namespace {
1621
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001622using ObjectPtr = art::ObjPtr<art::mirror::Object>;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001623
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001624static void ReplaceObjectReferences(ObjectPtr old_obj_ptr, ObjectPtr new_obj_ptr)
Alex Lightc14ec8f2019-07-18 16:08:41 -07001625 REQUIRES(art::Locks::mutator_lock_,
Alex Lightc14ec8f2019-07-18 16:08:41 -07001626 art::Roles::uninterruptible_) {
1627 art::Runtime::Current()->GetHeap()->VisitObjectsPaused(
1628 [&](art::mirror::Object* ref) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1629 // Rewrite all references in the object if needed.
1630 class ResizeReferenceVisitor {
1631 public:
1632 using CompressedObj = art::mirror::CompressedReference<art::mirror::Object>;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001633 ResizeReferenceVisitor(ObjectPtr old_arr, ObjectPtr new_arr)
1634 : old_obj_(old_arr), new_obj_(new_arr) {}
Alex Lightc14ec8f2019-07-18 16:08:41 -07001635
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001636 // Ignore class roots.
1637 void VisitRootIfNonNull(CompressedObj* root) const
1638 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1639 if (root != nullptr) {
1640 VisitRoot(root);
1641 }
1642 }
1643 void VisitRoot(CompressedObj* root) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1644 if (root->AsMirrorPtr() == old_obj_) {
1645 root->Assign(new_obj_);
1646 art::WriteBarrier::ForEveryFieldWrite(new_obj_);
1647 }
1648 }
Alex Lightc14ec8f2019-07-18 16:08:41 -07001649
1650 void operator()(art::ObjPtr<art::mirror::Object> obj,
1651 art::MemberOffset off,
1652 bool is_static ATTRIBUTE_UNUSED) const
1653 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001654 if (obj->GetFieldObject<art::mirror::Object>(off) == old_obj_) {
Alex Lightb0ce4d22019-09-19 14:45:45 -07001655 VLOG(plugin) << "Updating field at offset " << off.Uint32Value() << " of type "
1656 << obj->GetClass()->PrettyClass();
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001657 obj->SetFieldObject</*transaction*/ false>(off, new_obj_);
Alex Lightc14ec8f2019-07-18 16:08:41 -07001658 }
1659 }
1660
1661 // java.lang.ref.Reference visitor.
1662 void operator()(art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
1663 art::ObjPtr<art::mirror::Reference> ref) const
1664 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1665 operator()(ref, art::mirror::Reference::ReferentOffset(), /* is_static */ false);
1666 }
1667
1668 private:
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001669 ObjectPtr old_obj_;
1670 ObjectPtr new_obj_;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001671 };
1672
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001673 ResizeReferenceVisitor rrv(old_obj_ptr, new_obj_ptr);
1674 if (ref->IsClass()) {
1675 // Class object native roots are the ArtField and ArtMethod 'declaring_class_' fields
1676 // which we don't want to be messing with as it would break ref-visitor assumptions about
1677 // what a class looks like. We want to keep the default behavior in other cases (such as
1678 // dex-cache) though. Unfortunately there is no way to tell from the visitor where exactly
1679 // the root came from.
1680 // TODO It might be nice to have the visitors told where the reference came from.
1681 ref->VisitReferences</*kVisitNativeRoots*/false>(rrv, rrv);
1682 } else {
1683 ref->VisitReferences</*kVisitNativeRoots*/true>(rrv, rrv);
1684 }
Alex Lightc14ec8f2019-07-18 16:08:41 -07001685 });
1686}
1687
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001688static void ReplaceStrongRoots(art::Thread* self, ObjectPtr old_obj_ptr, ObjectPtr new_obj_ptr)
1689 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
Alex Lightc14ec8f2019-07-18 16:08:41 -07001690 // replace root references expcept java frames.
1691 struct ResizeRootVisitor : public art::RootVisitor {
1692 public:
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001693 ResizeRootVisitor(ObjectPtr new_val, ObjectPtr old_val)
Alex Lightc14ec8f2019-07-18 16:08:41 -07001694 : new_val_(new_val), old_val_(old_val) {}
1695
1696 // TODO It's somewhat annoying to have to have this function implemented twice. It might be
1697 // good/useful to implement operator= for CompressedReference to allow us to use a template to
1698 // implement both of these.
1699 void VisitRoots(art::mirror::Object*** roots, size_t count, const art::RootInfo& info) override
1700 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1701 art::mirror::Object*** end = roots + count;
1702 for (art::mirror::Object** obj = *roots; roots != end; obj = *(++roots)) {
1703 if (*obj == old_val_) {
1704 // Java frames might have the JIT doing optimizations (for example loop-unrolling or
1705 // eliding bounds checks) so we need deopt them once we're done here.
1706 if (info.GetType() == art::RootType::kRootJavaFrame) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001707 const art::JavaFrameRootInfo& jfri =
1708 art::down_cast<const art::JavaFrameRootInfo&>(info);
1709 if (jfri.GetVReg() == art::JavaFrameRootInfo::kMethodDeclaringClass) {
Alex Lightb55ef652019-09-26 15:23:28 -07001710 info.Describe(VLOG_STREAM(plugin) << "Not changing declaring-class during stack"
1711 << " walk. Found obsolete java frame id ");
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001712 continue;
1713 } else {
Alex Lightb55ef652019-09-26 15:23:28 -07001714 info.Describe(VLOG_STREAM(plugin) << "Found java frame id ");
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001715 threads_with_roots_.insert(info.GetThreadId());
1716 }
Alex Lightc14ec8f2019-07-18 16:08:41 -07001717 }
1718 *obj = new_val_.Ptr();
1719 }
1720 }
1721 }
1722
1723 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
1724 size_t count,
1725 const art::RootInfo& info) override REQUIRES_SHARED(art::Locks::mutator_lock_) {
1726 art::mirror::CompressedReference<art::mirror::Object>** end = roots + count;
1727 for (art::mirror::CompressedReference<art::mirror::Object>* obj = *roots; roots != end;
1728 obj = *(++roots)) {
1729 if (obj->AsMirrorPtr() == old_val_) {
1730 // Java frames might have the JIT doing optimizations (for example loop-unrolling or
1731 // eliding bounds checks) so we need deopt them once we're done here.
1732 if (info.GetType() == art::RootType::kRootJavaFrame) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001733 const art::JavaFrameRootInfo& jfri =
1734 art::down_cast<const art::JavaFrameRootInfo&>(info);
1735 if (jfri.GetVReg() == art::JavaFrameRootInfo::kMethodDeclaringClass) {
Alex Lightb55ef652019-09-26 15:23:28 -07001736 info.Describe(VLOG_STREAM(plugin) << "Not changing declaring-class during stack"
1737 << " walk. Found obsolete java frame id ");
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001738 continue;
1739 } else {
Alex Lightb55ef652019-09-26 15:23:28 -07001740 info.Describe(VLOG_STREAM(plugin) << "Found java frame id ");
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001741 threads_with_roots_.insert(info.GetThreadId());
1742 }
Alex Lightc14ec8f2019-07-18 16:08:41 -07001743 }
1744 obj->Assign(new_val_);
1745 }
1746 }
1747 }
1748
1749 const std::unordered_set<uint32_t>& GetThreadsWithJavaFrameRoots() const {
1750 return threads_with_roots_;
1751 }
1752
1753 private:
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001754 ObjectPtr new_val_;
1755 ObjectPtr old_val_;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001756 std::unordered_set<uint32_t> threads_with_roots_;
1757 };
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001758 ResizeRootVisitor rrv(new_obj_ptr, old_obj_ptr);
Alex Lightc14ec8f2019-07-18 16:08:41 -07001759 art::Runtime::Current()->VisitRoots(&rrv, art::VisitRootFlags::kVisitRootFlagAllRoots);
1760 // Handle java Frames. Annoyingly the JIT can embed information about the length of the array into
1761 // the compiled code. By changing the length of the array we potentially invalidate these
1762 // assumptions and so could cause (eg) OOB array access or other issues.
1763 if (!rrv.GetThreadsWithJavaFrameRoots().empty()) {
1764 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
1765 art::ThreadList* thread_list = art::Runtime::Current()->GetThreadList();
1766 art::instrumentation::Instrumentation* instr = art::Runtime::Current()->GetInstrumentation();
1767 for (uint32_t id : rrv.GetThreadsWithJavaFrameRoots()) {
1768 art::Thread* t = thread_list->FindThreadByThreadId(id);
1769 CHECK(t != nullptr) << "id " << id << " does not refer to a valid thread."
1770 << " Where did the roots come from?";
Alex Lightb0ce4d22019-09-19 14:45:45 -07001771 VLOG(plugin) << "Instrumenting thread stack of thread " << *t;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001772 // TODO Use deopt manager. We need a version that doesn't acquire all the locks we
1773 // already have.
1774 // TODO We technically only need to do this if the frames are not already being interpreted.
1775 // The cost for doing an extra stack walk is unlikely to be worth it though.
1776 instr->InstrumentThreadStack(t);
1777 }
1778 }
1779}
1780
Alex Light72d7e942019-07-23 13:10:20 -07001781static void ReplaceWeakRoots(art::Thread* self,
1782 EventHandler* event_handler,
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001783 ObjectPtr old_obj_ptr,
1784 ObjectPtr new_obj_ptr)
1785 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
Alex Light72d7e942019-07-23 13:10:20 -07001786 // Handle tags. We want to do this seprately from other weak-refs (handled below) because we need
1787 // to send additional events and handle cases where the agent might have tagged the new
1788 // replacement object during the VMObjectAlloc. We do this by removing all tags associated with
1789 // both the obsolete and the new arrays. Then we send the ObsoleteObjectCreated event and cache
1790 // the new tag values. We next update all the other weak-references (the tags have been removed)
1791 // and finally update the tag table with the new values. Doing things in this way (1) keeps all
1792 // code relating to updating weak-references together and (2) ensures we don't end up in strange
1793 // situations where the order of weak-ref visiting affects the final tagging state. Since we have
1794 // the mutator_lock_ and gc-paused throughout this whole process no threads should be able to see
1795 // the interval where the objects are not tagged.
1796 std::unordered_map<ArtJvmTiEnv*, jlong> obsolete_tags;
1797 std::unordered_map<ArtJvmTiEnv*, jlong> non_obsolete_tags;
1798 event_handler->ForEachEnv(self, [&](ArtJvmTiEnv* env) {
1799 // Cannot have REQUIRES(art::Locks::mutator_lock_) since ForEachEnv doesn't require it.
1800 art::Locks::mutator_lock_->AssertExclusiveHeld(self);
1801 env->object_tag_table->Lock();
1802 // Get the tags and clear them (so we don't need to special-case the normal weak-ref visitor)
1803 jlong new_tag = 0;
1804 jlong obsolete_tag = 0;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001805 bool had_new_tag = env->object_tag_table->RemoveLocked(new_obj_ptr, &new_tag);
1806 bool had_obsolete_tag = env->object_tag_table->RemoveLocked(old_obj_ptr, &obsolete_tag);
Alex Light72d7e942019-07-23 13:10:20 -07001807 // Dispatch event.
1808 if (had_obsolete_tag || had_new_tag) {
1809 event_handler->DispatchEventOnEnv<ArtJvmtiEvent::kObsoleteObjectCreated>(env,
1810 self,
1811 &obsolete_tag,
1812 &new_tag);
1813 obsolete_tags[env] = obsolete_tag;
1814 non_obsolete_tags[env] = new_tag;
1815 }
1816 // 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 +00001817 // deal with the visit-weaks overwriting the initial new_obj_ptr tag and generally making things
Alex Light72d7e942019-07-23 13:10:20 -07001818 // difficult.
1819 env->object_tag_table->Unlock();
1820 });
1821 // Handle weak-refs.
Alex Lightc14ec8f2019-07-18 16:08:41 -07001822 struct ReplaceWeaksVisitor : public art::IsMarkedVisitor {
1823 public:
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001824 ReplaceWeaksVisitor(ObjectPtr old_obj, ObjectPtr new_obj)
1825 : old_obj_(old_obj), new_obj_(new_obj) {}
Alex Lightc14ec8f2019-07-18 16:08:41 -07001826
1827 art::mirror::Object* IsMarked(art::mirror::Object* obj)
1828 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001829 if (obj == old_obj_) {
1830 return new_obj_.Ptr();
Alex Lightc14ec8f2019-07-18 16:08:41 -07001831 } else {
1832 return obj;
1833 }
1834 }
1835
1836 private:
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001837 ObjectPtr old_obj_;
1838 ObjectPtr new_obj_;
Alex Lightc14ec8f2019-07-18 16:08:41 -07001839 };
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001840 ReplaceWeaksVisitor rwv(old_obj_ptr, new_obj_ptr);
Alex Lightc14ec8f2019-07-18 16:08:41 -07001841 art::Runtime::Current()->SweepSystemWeaks(&rwv);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001842 // 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 -07001843 event_handler->ForEachEnv(self, [&](ArtJvmTiEnv* env) {
1844 // Cannot have REQUIRES(art::Locks::mutator_lock_) since ForEachEnv doesn't require it.
1845 art::Locks::mutator_lock_->AssertExclusiveHeld(self);
1846 env->object_tag_table->Lock();
1847 if (obsolete_tags.find(env) != obsolete_tags.end()) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001848 env->object_tag_table->SetLocked(old_obj_ptr, obsolete_tags[env]);
Alex Light72d7e942019-07-23 13:10:20 -07001849 }
1850 if (non_obsolete_tags.find(env) != non_obsolete_tags.end()) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001851 env->object_tag_table->SetLocked(new_obj_ptr, non_obsolete_tags[env]);
Alex Light72d7e942019-07-23 13:10:20 -07001852 }
1853 env->object_tag_table->Unlock();
1854 });
Alex Lightc14ec8f2019-07-18 16:08:41 -07001855}
1856
Nicolas Geoffray5a2301d2019-09-18 06:11:22 +00001857} // namespace
1858
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001859void HeapExtensions::ReplaceReference(art::Thread* self,
1860 art::ObjPtr<art::mirror::Object> old_obj_ptr,
1861 art::ObjPtr<art::mirror::Object> new_obj_ptr) {
1862 ReplaceObjectReferences(old_obj_ptr, new_obj_ptr);
1863 ReplaceStrongRoots(self, old_obj_ptr, new_obj_ptr);
1864 ReplaceWeakRoots(self, HeapExtensions::gEventHandler, old_obj_ptr, new_obj_ptr);
1865}
1866
Alex Lightc14ec8f2019-07-18 16:08:41 -07001867jvmtiError HeapExtensions::ChangeArraySize(jvmtiEnv* env, jobject arr, jsize new_size) {
1868 if (ArtJvmTiEnv::AsArtJvmTiEnv(env)->capabilities.can_tag_objects != 1) {
1869 return ERR(MUST_POSSESS_CAPABILITY);
1870 }
1871 art::Thread* self = art::Thread::Current();
1872 ScopedNoUserCodeSuspension snucs(self);
1873 art::ScopedObjectAccess soa(self);
1874 if (arr == nullptr) {
1875 JVMTI_LOG(INFO, env) << "Cannot resize a null object";
1876 return ERR(NULL_POINTER);
1877 }
1878 art::ObjPtr<art::mirror::Class> klass(soa.Decode<art::mirror::Object>(arr)->GetClass());
1879 if (!klass->IsArrayClass()) {
1880 JVMTI_LOG(INFO, env) << klass->PrettyClass() << " is not an array class!";
1881 return ERR(ILLEGAL_ARGUMENT);
1882 }
1883 if (new_size < 0) {
1884 JVMTI_LOG(INFO, env) << "Cannot resize an array to a negative size";
1885 return ERR(ILLEGAL_ARGUMENT);
1886 }
1887 // Allocate the new copy.
1888 art::StackHandleScope<2> hs(self);
1889 art::Handle<art::mirror::Array> old_arr(hs.NewHandle(soa.Decode<art::mirror::Array>(arr)));
1890 art::MutableHandle<art::mirror::Array> new_arr(hs.NewHandle<art::mirror::Array>(nullptr));
1891 if (klass->IsObjectArrayClass()) {
1892 new_arr.Assign(
1893 art::mirror::ObjectArray<art::mirror::Object>::Alloc(self, old_arr->GetClass(), new_size));
1894 } else {
1895 // NB This also copies the old array but since we aren't suspended we need to do this again to
1896 // catch any concurrent modifications.
1897 new_arr.Assign(art::mirror::Array::CopyOf(old_arr, self, new_size));
1898 }
1899 if (new_arr.IsNull()) {
1900 self->AssertPendingOOMException();
1901 JVMTI_LOG(INFO, env) << "Unable to allocate " << old_arr->GetClass()->PrettyClass()
1902 << " (length: " << new_size << ") due to OOME. Error was: "
1903 << self->GetException()->Dump();
1904 self->ClearException();
1905 return ERR(OUT_OF_MEMORY);
1906 } else {
1907 self->AssertNoPendingException();
1908 }
1909 // Suspend everything.
1910 art::ScopedThreadSuspension sts(self, art::ThreadState::kSuspended);
1911 art::gc::ScopedGCCriticalSection sgccs(
1912 self, art::gc::GcCause::kGcCauseDebugger, art::gc::CollectorType::kCollectorTypeDebugger);
1913 art::ScopedSuspendAll ssa("Resize array!");
1914 // Replace internals.
1915 new_arr->SetLockWord(old_arr->GetLockWord(false), false);
1916 old_arr->SetLockWord(art::LockWord::Default(), false);
1917 // Copy the contents now when everything is suspended.
1918 int32_t size = std::min(old_arr->GetLength(), new_size);
1919 switch (old_arr->GetClass()->GetComponentType()->GetPrimitiveType()) {
1920 case art::Primitive::kPrimBoolean:
1921 new_arr->AsBooleanArray()->Memcpy(0, old_arr->AsBooleanArray(), 0, size);
1922 break;
1923 case art::Primitive::kPrimByte:
1924 new_arr->AsByteArray()->Memcpy(0, old_arr->AsByteArray(), 0, size);
1925 break;
1926 case art::Primitive::kPrimChar:
1927 new_arr->AsCharArray()->Memcpy(0, old_arr->AsCharArray(), 0, size);
1928 break;
1929 case art::Primitive::kPrimShort:
1930 new_arr->AsShortArray()->Memcpy(0, old_arr->AsShortArray(), 0, size);
1931 break;
1932 case art::Primitive::kPrimInt:
1933 new_arr->AsIntArray()->Memcpy(0, old_arr->AsIntArray(), 0, size);
1934 break;
1935 case art::Primitive::kPrimLong:
1936 new_arr->AsLongArray()->Memcpy(0, old_arr->AsLongArray(), 0, size);
1937 break;
1938 case art::Primitive::kPrimFloat:
1939 new_arr->AsFloatArray()->Memcpy(0, old_arr->AsFloatArray(), 0, size);
1940 break;
1941 case art::Primitive::kPrimDouble:
1942 new_arr->AsDoubleArray()->Memcpy(0, old_arr->AsDoubleArray(), 0, size);
1943 break;
1944 case art::Primitive::kPrimNot:
1945 for (int32_t i = 0; i < size; i++) {
1946 new_arr->AsObjectArray<art::mirror::Object>()->Set(
1947 i, old_arr->AsObjectArray<art::mirror::Object>()->Get(i));
1948 }
1949 break;
1950 case art::Primitive::kPrimVoid:
1951 LOG(FATAL) << "void-array is not a legal type!";
1952 UNREACHABLE();
1953 }
1954 // Actually replace all the pointers.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001955 ReplaceReference(self, old_arr.Get(), new_arr.Get());
Alex Lightc14ec8f2019-07-18 16:08:41 -07001956 return OK;
1957}
1958
Alex Light72d7e942019-07-23 13:10:20 -07001959void HeapExtensions::Register(EventHandler* eh) {
1960 gEventHandler = eh;
1961}
1962
Andreas Gampee54d9922016-10-11 19:55:37 -07001963} // namespace openjdkjvmti