blob: 373944f179519456b81008b96d7c837c3b447701 [file] [log] [blame]
Andreas Gampeb5eb94a2016-10-27 19:23:09 -07001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_stack.h"
33
Andreas Gampeeba32fb2017-01-12 17:40:05 -080034#include <algorithm>
Andreas Gampea1a27c62017-01-11 16:37:16 -080035#include <list>
36#include <unordered_map>
37#include <vector>
38
Andreas Gampea1d2f952017-04-20 22:53:58 -070039#include "art_field-inl.h"
Alex Lighte814f9d2017-07-31 16:14:39 -070040#include "art_method-inl.h"
Andreas Gampea1d2f952017-04-20 22:53:58 -070041#include "art_jvmti.h"
Steven Morelande431e272017-07-18 16:53:49 -070042#include "art_method-inl.h"
Andreas Gampe6237cd32017-06-22 22:17:38 -070043#include "barrier.h"
Andreas Gampea1a27c62017-01-11 16:37:16 -080044#include "base/bit_utils.h"
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070045#include "base/enums.h"
Andreas Gampea1a27c62017-01-11 16:37:16 -080046#include "base/mutex.h"
David Sehr9e734c72018-01-04 17:56:19 -080047#include "dex/code_item_accessors-inl.h"
48#include "dex/dex_file.h"
49#include "dex/dex_file_annotations.h"
50#include "dex/dex_file_types.h"
Alex Light88e1ddd2017-08-21 13:09:55 -070051#include "gc_root.h"
Andreas Gampeeba32fb2017-01-12 17:40:05 -080052#include "handle_scope-inl.h"
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070053#include "jni_env_ext.h"
Andreas Gampe13b27842016-11-07 16:48:23 -080054#include "jni_internal.h"
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070055#include "mirror/class.h"
56#include "mirror/dex_cache.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070057#include "nativehelper/scoped_local_ref.h"
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070058#include "scoped_thread_state_change-inl.h"
59#include "stack.h"
Alex Lighte814f9d2017-07-31 16:14:39 -070060#include "ti_thread.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070061#include "thread-current-inl.h"
Andreas Gampea1a27c62017-01-11 16:37:16 -080062#include "thread_list.h"
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070063#include "thread_pool.h"
Alex Light88e1ddd2017-08-21 13:09:55 -070064#include "ti_thread.h"
Andreas Gampea1d2f952017-04-20 22:53:58 -070065#include "well_known_classes.h"
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070066
67namespace openjdkjvmti {
68
Andreas Gampe6db6b4d2017-06-12 16:36:33 -070069template <typename FrameFn>
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070070struct GetStackTraceVisitor : public art::StackVisitor {
71 GetStackTraceVisitor(art::Thread* thread_in,
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070072 size_t start_,
Andreas Gampe6db6b4d2017-06-12 16:36:33 -070073 size_t stop_,
74 FrameFn fn_)
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070075 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Andreas Gampe6db6b4d2017-06-12 16:36:33 -070076 fn(fn_),
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070077 start(start_),
78 stop(stop_) {}
Andreas Gampe6db6b4d2017-06-12 16:36:33 -070079 GetStackTraceVisitor(const GetStackTraceVisitor&) = default;
80 GetStackTraceVisitor(GetStackTraceVisitor&&) = default;
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070081
82 bool VisitFrame() REQUIRES_SHARED(art::Locks::mutator_lock_) {
83 art::ArtMethod* m = GetMethod();
84 if (m->IsRuntimeMethod()) {
85 return true;
86 }
87
88 if (start == 0) {
89 m = m->GetInterfaceMethodIfProxy(art::kRuntimePointerSize);
Andreas Gampe13b27842016-11-07 16:48:23 -080090 jmethodID id = art::jni::EncodeArtMethod(m);
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070091
Andreas Gampe2340e3f2016-12-12 19:37:19 -080092 uint32_t dex_pc = GetDexPc(false);
Andreas Gampee2abbc62017-09-15 11:59:26 -070093 jlong dex_location = (dex_pc == art::dex::kDexNoIndex) ? -1 : static_cast<jlong>(dex_pc);
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070094
Andreas Gampe2340e3f2016-12-12 19:37:19 -080095 jvmtiFrameInfo info = { id, dex_location };
Andreas Gampe6db6b4d2017-06-12 16:36:33 -070096 fn(info);
Andreas Gampeb5eb94a2016-10-27 19:23:09 -070097
98 if (stop == 1) {
99 return false; // We're done.
100 } else if (stop > 0) {
101 stop--;
102 }
103 } else {
104 start--;
105 }
106
107 return true;
108 }
109
Andreas Gampe6db6b4d2017-06-12 16:36:33 -0700110 FrameFn fn;
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700111 size_t start;
112 size_t stop;
113};
114
Andreas Gampe6db6b4d2017-06-12 16:36:33 -0700115template <typename FrameFn>
116GetStackTraceVisitor<FrameFn> MakeStackTraceVisitor(art::Thread* thread_in,
117 size_t start,
118 size_t stop,
119 FrameFn fn) {
120 return GetStackTraceVisitor<FrameFn>(thread_in, start, stop, fn);
121}
122
123struct GetStackTraceVectorClosure : public art::Closure {
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700124 public:
Andreas Gampe6db6b4d2017-06-12 16:36:33 -0700125 GetStackTraceVectorClosure(size_t start, size_t stop)
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700126 : start_input(start),
127 stop_input(stop),
128 start_result(0),
129 stop_result(0) {}
130
Andreas Gampea1a27c62017-01-11 16:37:16 -0800131 void Run(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe6db6b4d2017-06-12 16:36:33 -0700132 auto frames_fn = [&](jvmtiFrameInfo info) {
133 frames.push_back(info);
134 };
135 auto visitor = MakeStackTraceVisitor(self, start_input, stop_input, frames_fn);
136 visitor.WalkStack(/* include_transitions */ false);
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700137
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700138 start_result = visitor.start;
139 stop_result = visitor.stop;
140 }
141
142 const size_t start_input;
143 const size_t stop_input;
144
145 std::vector<jvmtiFrameInfo> frames;
146 size_t start_result;
147 size_t stop_result;
148};
149
Andreas Gampea1a27c62017-01-11 16:37:16 -0800150static jvmtiError TranslateFrameVector(const std::vector<jvmtiFrameInfo>& frames,
151 jint start_depth,
152 size_t start_result,
153 jint max_frame_count,
154 jvmtiFrameInfo* frame_buffer,
155 jint* count_ptr) {
156 size_t collected_frames = frames.size();
157
158 // Assume we're here having collected something.
159 DCHECK_GT(max_frame_count, 0);
160
161 // Frames from the top.
162 if (start_depth >= 0) {
163 if (start_result != 0) {
164 // Not enough frames.
165 return ERR(ILLEGAL_ARGUMENT);
166 }
167 DCHECK_LE(collected_frames, static_cast<size_t>(max_frame_count));
168 if (frames.size() > 0) {
169 memcpy(frame_buffer, frames.data(), collected_frames * sizeof(jvmtiFrameInfo));
170 }
171 *count_ptr = static_cast<jint>(frames.size());
172 return ERR(NONE);
173 }
174
175 // Frames from the bottom.
176 if (collected_frames < static_cast<size_t>(-start_depth)) {
177 return ERR(ILLEGAL_ARGUMENT);
178 }
179
180 size_t count = std::min(static_cast<size_t>(-start_depth), static_cast<size_t>(max_frame_count));
181 memcpy(frame_buffer,
182 &frames.data()[collected_frames + start_depth],
183 count * sizeof(jvmtiFrameInfo));
184 *count_ptr = static_cast<jint>(count);
185 return ERR(NONE);
186}
187
Andreas Gampe850a0fe2017-06-12 18:37:19 -0700188struct GetStackTraceDirectClosure : public art::Closure {
189 public:
190 GetStackTraceDirectClosure(jvmtiFrameInfo* frame_buffer_, size_t start, size_t stop)
191 : frame_buffer(frame_buffer_),
192 start_input(start),
193 stop_input(stop),
194 index(0) {
195 DCHECK_GE(start_input, 0u);
196 }
197
198 void Run(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
199 auto frames_fn = [&](jvmtiFrameInfo info) {
200 frame_buffer[index] = info;
201 ++index;
202 };
203 auto visitor = MakeStackTraceVisitor(self, start_input, stop_input, frames_fn);
204 visitor.WalkStack(/* include_transitions */ false);
205 }
206
207 jvmtiFrameInfo* frame_buffer;
208
209 const size_t start_input;
210 const size_t stop_input;
211
212 size_t index = 0;
213};
214
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700215jvmtiError StackUtil::GetStackTrace(jvmtiEnv* jvmti_env ATTRIBUTE_UNUSED,
216 jthread java_thread,
217 jint start_depth,
218 jint max_frame_count,
219 jvmtiFrameInfo* frame_buffer,
220 jint* count_ptr) {
Andreas Gampe28c4a232017-06-21 21:21:31 -0700221 // It is not great that we have to hold these locks for so long, but it is necessary to ensure
222 // that the thread isn't dying on us.
223 art::ScopedObjectAccess soa(art::Thread::Current());
Alex Lightb1e31a82017-10-04 16:57:36 -0700224 art::Locks::thread_list_lock_->ExclusiveLock(soa.Self());
Andreas Gampe28c4a232017-06-21 21:21:31 -0700225
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700226 art::Thread* thread;
Alex Light7ddc23d2017-09-22 15:33:41 -0700227 jvmtiError thread_error = ERR(INTERNAL);
228 if (!ThreadUtil::GetAliveNativeThread(java_thread, soa, &thread, &thread_error)) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700229 art::Locks::thread_list_lock_->ExclusiveUnlock(soa.Self());
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800230 return thread_error;
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700231 }
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800232 DCHECK(thread != nullptr);
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700233
234 art::ThreadState state = thread->GetState();
Alex Light7ddc23d2017-09-22 15:33:41 -0700235 if (state == art::ThreadState::kStarting || thread->IsStillStarting()) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700236 art::Locks::thread_list_lock_->ExclusiveUnlock(soa.Self());
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700237 return ERR(THREAD_NOT_ALIVE);
238 }
239
240 if (max_frame_count < 0) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700241 art::Locks::thread_list_lock_->ExclusiveUnlock(soa.Self());
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700242 return ERR(ILLEGAL_ARGUMENT);
243 }
244 if (frame_buffer == nullptr || count_ptr == nullptr) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700245 art::Locks::thread_list_lock_->ExclusiveUnlock(soa.Self());
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700246 return ERR(NULL_POINTER);
247 }
248
249 if (max_frame_count == 0) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700250 art::Locks::thread_list_lock_->ExclusiveUnlock(soa.Self());
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700251 *count_ptr = 0;
252 return ERR(NONE);
253 }
254
Andreas Gampe850a0fe2017-06-12 18:37:19 -0700255 if (start_depth >= 0) {
256 // Fast path: Regular order of stack trace. Fill into the frame_buffer directly.
257 GetStackTraceDirectClosure closure(frame_buffer,
258 static_cast<size_t>(start_depth),
259 static_cast<size_t>(max_frame_count));
Alex Lightb1e31a82017-10-04 16:57:36 -0700260 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Lightd9aff132017-10-31 22:30:05 +0000261 if (!ThreadUtil::RequestGCSafeSynchronousCheckpoint(thread, &closure)) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700262 return ERR(THREAD_NOT_ALIVE);
263 }
Andreas Gampe850a0fe2017-06-12 18:37:19 -0700264 *count_ptr = static_cast<jint>(closure.index);
265 if (closure.index < static_cast<size_t>(start_depth)) {
266 return ERR(ILLEGAL_ARGUMENT);
267 }
268 return ERR(NONE);
Alex Lightb1e31a82017-10-04 16:57:36 -0700269 } else {
270 GetStackTraceVectorClosure closure(0, 0);
271 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Lightd9aff132017-10-31 22:30:05 +0000272 if (!ThreadUtil::RequestGCSafeSynchronousCheckpoint(thread, &closure)) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700273 return ERR(THREAD_NOT_ALIVE);
274 }
275
276 return TranslateFrameVector(closure.frames,
277 start_depth,
278 closure.start_result,
279 max_frame_count,
280 frame_buffer,
281 count_ptr);
Andreas Gampe850a0fe2017-06-12 18:37:19 -0700282 }
Andreas Gampea1a27c62017-01-11 16:37:16 -0800283}
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700284
Andreas Gampef1221a12017-06-21 21:20:47 -0700285template <typename Data>
286struct GetAllStackTracesVectorClosure : public art::Closure {
Andreas Gampe6237cd32017-06-22 22:17:38 -0700287 GetAllStackTracesVectorClosure(size_t stop, Data* data_)
288 : barrier(0), stop_input(stop), data(data_) {}
Andreas Gampef1221a12017-06-21 21:20:47 -0700289
290 void Run(art::Thread* thread) OVERRIDE
291 REQUIRES_SHARED(art::Locks::mutator_lock_)
292 REQUIRES(!data->mutex) {
293 art::Thread* self = art::Thread::Current();
Andreas Gampe6237cd32017-06-22 22:17:38 -0700294 Work(thread, self);
295 barrier.Pass(self);
296 }
Andreas Gampef1221a12017-06-21 21:20:47 -0700297
Andreas Gampe6237cd32017-06-22 22:17:38 -0700298 void Work(art::Thread* thread, art::Thread* self)
299 REQUIRES_SHARED(art::Locks::mutator_lock_)
300 REQUIRES(!data->mutex) {
Andreas Gampef1221a12017-06-21 21:20:47 -0700301 // Skip threads that are still starting.
302 if (thread->IsStillStarting()) {
303 return;
304 }
305
306 std::vector<jvmtiFrameInfo>* thread_frames = data->GetFrameStorageFor(self, thread);
307 if (thread_frames == nullptr) {
308 return;
309 }
310
311 // Now collect the data.
312 auto frames_fn = [&](jvmtiFrameInfo info) {
313 thread_frames->push_back(info);
314 };
315 auto visitor = MakeStackTraceVisitor(thread, 0u, stop_input, frames_fn);
316 visitor.WalkStack(/* include_transitions */ false);
317 }
318
Andreas Gampe6237cd32017-06-22 22:17:38 -0700319 art::Barrier barrier;
Andreas Gampef1221a12017-06-21 21:20:47 -0700320 const size_t stop_input;
321 Data* data;
322};
323
Andreas Gampe6237cd32017-06-22 22:17:38 -0700324template <typename Data>
325static void RunCheckpointAndWait(Data* data, size_t max_frame_count) {
326 GetAllStackTracesVectorClosure<Data> closure(max_frame_count, data);
327 size_t barrier_count = art::Runtime::Current()->GetThreadList()->RunCheckpoint(&closure, nullptr);
328 if (barrier_count == 0) {
329 return;
330 }
331 art::Thread* self = art::Thread::Current();
332 art::ScopedThreadStateChange tsc(self, art::ThreadState::kWaitingForCheckPointsToRun);
333 closure.barrier.Increment(self, barrier_count);
334}
335
Andreas Gampea1a27c62017-01-11 16:37:16 -0800336jvmtiError StackUtil::GetAllStackTraces(jvmtiEnv* env,
337 jint max_frame_count,
338 jvmtiStackInfo** stack_info_ptr,
339 jint* thread_count_ptr) {
340 if (max_frame_count < 0) {
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700341 return ERR(ILLEGAL_ARGUMENT);
342 }
Andreas Gampea1a27c62017-01-11 16:37:16 -0800343 if (stack_info_ptr == nullptr || thread_count_ptr == nullptr) {
344 return ERR(NULL_POINTER);
345 }
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700346
Andreas Gampef1221a12017-06-21 21:20:47 -0700347 struct AllStackTracesData {
348 AllStackTracesData() : mutex("GetAllStackTraces", art::LockLevel::kAbortLock) {}
349 ~AllStackTracesData() {
350 JNIEnv* jni_env = art::Thread::Current()->GetJniEnv();
351 for (jthread global_thread_ref : thread_peers) {
352 jni_env->DeleteGlobalRef(global_thread_ref);
353 }
Andreas Gampea1a27c62017-01-11 16:37:16 -0800354 }
355
Andreas Gampef1221a12017-06-21 21:20:47 -0700356 std::vector<jvmtiFrameInfo>* GetFrameStorageFor(art::Thread* self, art::Thread* thread)
357 REQUIRES_SHARED(art::Locks::mutator_lock_)
358 REQUIRES(!mutex) {
359 art::MutexLock mu(self, mutex);
Andreas Gampea1a27c62017-01-11 16:37:16 -0800360
361 threads.push_back(thread);
Andreas Gampea1a27c62017-01-11 16:37:16 -0800362
Andreas Gampef1221a12017-06-21 21:20:47 -0700363 jthread peer = art::Runtime::Current()->GetJavaVM()->AddGlobalRef(
364 self, thread->GetPeerFromOtherThread());
365 thread_peers.push_back(peer);
366
Andreas Gampead9173d2017-06-22 16:33:08 -0700367 frames.emplace_back(new std::vector<jvmtiFrameInfo>());
368 return frames.back().get();
Andreas Gampef1221a12017-06-21 21:20:47 -0700369 }
370
371 art::Mutex mutex;
372
373 // Storage. Only access directly after completion.
374
375 std::vector<art::Thread*> threads;
376 // "thread_peers" contains global references to their peers.
377 std::vector<jthread> thread_peers;
378
Andreas Gampead9173d2017-06-22 16:33:08 -0700379 std::vector<std::unique_ptr<std::vector<jvmtiFrameInfo>>> frames;
Andreas Gampef1221a12017-06-21 21:20:47 -0700380 };
381
382 AllStackTracesData data;
Andreas Gampe6237cd32017-06-22 22:17:38 -0700383 RunCheckpointAndWait(&data, static_cast<size_t>(max_frame_count));
Andreas Gampef1221a12017-06-21 21:20:47 -0700384
385 art::Thread* current = art::Thread::Current();
386
387 // Convert the data into our output format.
Andreas Gampea1a27c62017-01-11 16:37:16 -0800388
389 // Note: we use an array of jvmtiStackInfo for convenience. The spec says we need to
390 // allocate one big chunk for this and the actual frames, which means we need
391 // to either be conservative or rearrange things later (the latter is implemented).
Andreas Gampef1221a12017-06-21 21:20:47 -0700392 std::unique_ptr<jvmtiStackInfo[]> stack_info_array(new jvmtiStackInfo[data.frames.size()]);
Andreas Gampea1a27c62017-01-11 16:37:16 -0800393 std::vector<std::unique_ptr<jvmtiFrameInfo[]>> frame_infos;
Andreas Gampef1221a12017-06-21 21:20:47 -0700394 frame_infos.reserve(data.frames.size());
Andreas Gampea1a27c62017-01-11 16:37:16 -0800395
396 // Now run through and add data for each thread.
397 size_t sum_frames = 0;
Andreas Gampef1221a12017-06-21 21:20:47 -0700398 for (size_t index = 0; index < data.frames.size(); ++index) {
Andreas Gampea1a27c62017-01-11 16:37:16 -0800399 jvmtiStackInfo& stack_info = stack_info_array.get()[index];
400 memset(&stack_info, 0, sizeof(jvmtiStackInfo));
401
Andreas Gampead9173d2017-06-22 16:33:08 -0700402 const std::vector<jvmtiFrameInfo>& thread_frames = *data.frames[index].get();
Andreas Gampea1a27c62017-01-11 16:37:16 -0800403
Andreas Gampef1221a12017-06-21 21:20:47 -0700404 // For the time being, set the thread to null. We'll fix it up in the second stage.
Andreas Gampea1a27c62017-01-11 16:37:16 -0800405 stack_info.thread = nullptr;
406 stack_info.state = JVMTI_THREAD_STATE_SUSPENDED;
407
408 size_t collected_frames = thread_frames.size();
409 if (max_frame_count == 0 || collected_frames == 0) {
410 stack_info.frame_count = 0;
411 stack_info.frame_buffer = nullptr;
412 continue;
413 }
414 DCHECK_LE(collected_frames, static_cast<size_t>(max_frame_count));
415
416 jvmtiFrameInfo* frame_info = new jvmtiFrameInfo[collected_frames];
417 frame_infos.emplace_back(frame_info);
418
419 jint count;
420 jvmtiError translate_result = TranslateFrameVector(thread_frames,
421 0,
422 0,
423 static_cast<jint>(collected_frames),
424 frame_info,
425 &count);
426 DCHECK(translate_result == JVMTI_ERROR_NONE);
427 stack_info.frame_count = static_cast<jint>(collected_frames);
428 stack_info.frame_buffer = frame_info;
429 sum_frames += static_cast<size_t>(count);
430 }
431
432 // No errors, yet. Now put it all into an output buffer.
Andreas Gampef1221a12017-06-21 21:20:47 -0700433 size_t rounded_stack_info_size = art::RoundUp(sizeof(jvmtiStackInfo) * data.frames.size(),
Andreas Gampea1a27c62017-01-11 16:37:16 -0800434 alignof(jvmtiFrameInfo));
435 size_t chunk_size = rounded_stack_info_size + sum_frames * sizeof(jvmtiFrameInfo);
436 unsigned char* chunk_data;
437 jvmtiError alloc_result = env->Allocate(chunk_size, &chunk_data);
438 if (alloc_result != ERR(NONE)) {
439 return alloc_result;
440 }
441
442 jvmtiStackInfo* stack_info = reinterpret_cast<jvmtiStackInfo*>(chunk_data);
443 // First copy in all the basic data.
Andreas Gampef1221a12017-06-21 21:20:47 -0700444 memcpy(stack_info, stack_info_array.get(), sizeof(jvmtiStackInfo) * data.frames.size());
Andreas Gampea1a27c62017-01-11 16:37:16 -0800445
446 // Now copy the frames and fix up the pointers.
447 jvmtiFrameInfo* frame_info = reinterpret_cast<jvmtiFrameInfo*>(
448 chunk_data + rounded_stack_info_size);
Andreas Gampef1221a12017-06-21 21:20:47 -0700449 for (size_t i = 0; i < data.frames.size(); ++i) {
Andreas Gampea1a27c62017-01-11 16:37:16 -0800450 jvmtiStackInfo& old_stack_info = stack_info_array.get()[i];
451 jvmtiStackInfo& new_stack_info = stack_info[i];
452
Andreas Gampef1221a12017-06-21 21:20:47 -0700453 // Translate the global ref into a local ref.
454 new_stack_info.thread =
455 static_cast<JNIEnv*>(current->GetJniEnv())->NewLocalRef(data.thread_peers[i]);
Andreas Gampea1a27c62017-01-11 16:37:16 -0800456
457 if (old_stack_info.frame_count > 0) {
458 // Only copy when there's data - leave the nullptr alone.
459 size_t frames_size = static_cast<size_t>(old_stack_info.frame_count) * sizeof(jvmtiFrameInfo);
460 memcpy(frame_info, old_stack_info.frame_buffer, frames_size);
461 new_stack_info.frame_buffer = frame_info;
462 frame_info += old_stack_info.frame_count;
463 }
464 }
465
466 *stack_info_ptr = stack_info;
Andreas Gampef1221a12017-06-21 21:20:47 -0700467 *thread_count_ptr = static_cast<jint>(data.frames.size());
Andreas Gampea1a27c62017-01-11 16:37:16 -0800468
Andreas Gampeb5eb94a2016-10-27 19:23:09 -0700469 return ERR(NONE);
470}
471
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800472jvmtiError StackUtil::GetThreadListStackTraces(jvmtiEnv* env,
473 jint thread_count,
474 const jthread* thread_list,
475 jint max_frame_count,
476 jvmtiStackInfo** stack_info_ptr) {
477 if (max_frame_count < 0) {
478 return ERR(ILLEGAL_ARGUMENT);
479 }
480 if (thread_count < 0) {
481 return ERR(ILLEGAL_ARGUMENT);
482 }
483 if (thread_count == 0) {
484 *stack_info_ptr = nullptr;
485 return ERR(NONE);
486 }
487 if (stack_info_ptr == nullptr || stack_info_ptr == nullptr) {
488 return ERR(NULL_POINTER);
489 }
490
491 art::Thread* current = art::Thread::Current();
492 art::ScopedObjectAccess soa(current); // Now we know we have the shared lock.
493
Andreas Gampef1221a12017-06-21 21:20:47 -0700494 struct SelectStackTracesData {
495 SelectStackTracesData() : mutex("GetSelectStackTraces", art::LockLevel::kAbortLock) {}
496
497 std::vector<jvmtiFrameInfo>* GetFrameStorageFor(art::Thread* self, art::Thread* thread)
498 REQUIRES_SHARED(art::Locks::mutator_lock_)
499 REQUIRES(!mutex) {
500 art::ObjPtr<art::mirror::Object> peer = thread->GetPeerFromOtherThread();
501 for (size_t index = 0; index != handles.size(); ++index) {
502 if (peer == handles[index].Get()) {
503 // Found the thread.
504 art::MutexLock mu(self, mutex);
505
506 threads.push_back(thread);
507 thread_list_indices.push_back(index);
508
Andreas Gampead9173d2017-06-22 16:33:08 -0700509 frames.emplace_back(new std::vector<jvmtiFrameInfo>());
510 return frames.back().get();
Andreas Gampef1221a12017-06-21 21:20:47 -0700511 }
512 }
513 return nullptr;
514 }
515
516 art::Mutex mutex;
517
518 // Selection data.
519
520 std::vector<art::Handle<art::mirror::Object>> handles;
521
522 // Storage. Only access directly after completion.
523
524 std::vector<art::Thread*> threads;
525 std::vector<size_t> thread_list_indices;
526
Andreas Gampead9173d2017-06-22 16:33:08 -0700527 std::vector<std::unique_ptr<std::vector<jvmtiFrameInfo>>> frames;
Andreas Gampef1221a12017-06-21 21:20:47 -0700528 };
529
530 SelectStackTracesData data;
531
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800532 // Decode all threads to raw pointers. Put them into a handle scope to avoid any moving GC bugs.
533 art::VariableSizedHandleScope hs(current);
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800534 for (jint i = 0; i != thread_count; ++i) {
535 if (thread_list[i] == nullptr) {
536 return ERR(INVALID_THREAD);
537 }
538 if (!soa.Env()->IsInstanceOf(thread_list[i], art::WellKnownClasses::java_lang_Thread)) {
539 return ERR(INVALID_THREAD);
540 }
Andreas Gampef1221a12017-06-21 21:20:47 -0700541 data.handles.push_back(hs.NewHandle(soa.Decode<art::mirror::Object>(thread_list[i])));
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800542 }
543
Andreas Gampe6237cd32017-06-22 22:17:38 -0700544 RunCheckpointAndWait(&data, static_cast<size_t>(max_frame_count));
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800545
546 // Convert the data into our output format.
547
548 // Note: we use an array of jvmtiStackInfo for convenience. The spec says we need to
549 // allocate one big chunk for this and the actual frames, which means we need
550 // to either be conservative or rearrange things later (the latter is implemented).
Andreas Gampef1221a12017-06-21 21:20:47 -0700551 std::unique_ptr<jvmtiStackInfo[]> stack_info_array(new jvmtiStackInfo[data.frames.size()]);
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800552 std::vector<std::unique_ptr<jvmtiFrameInfo[]>> frame_infos;
Andreas Gampef1221a12017-06-21 21:20:47 -0700553 frame_infos.reserve(data.frames.size());
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800554
555 // Now run through and add data for each thread.
556 size_t sum_frames = 0;
Andreas Gampef1221a12017-06-21 21:20:47 -0700557 for (size_t index = 0; index < data.frames.size(); ++index) {
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800558 jvmtiStackInfo& stack_info = stack_info_array.get()[index];
559 memset(&stack_info, 0, sizeof(jvmtiStackInfo));
560
Andreas Gampef1221a12017-06-21 21:20:47 -0700561 art::Thread* self = data.threads[index];
Andreas Gampead9173d2017-06-22 16:33:08 -0700562 const std::vector<jvmtiFrameInfo>& thread_frames = *data.frames[index].get();
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800563
564 // For the time being, set the thread to null. We don't have good ScopedLocalRef
565 // infrastructure.
Nicolas Geoffrayffc8cad2017-02-10 10:59:22 +0000566 DCHECK(self->GetPeerFromOtherThread() != nullptr);
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800567 stack_info.thread = nullptr;
568 stack_info.state = JVMTI_THREAD_STATE_SUSPENDED;
569
570 size_t collected_frames = thread_frames.size();
571 if (max_frame_count == 0 || collected_frames == 0) {
572 stack_info.frame_count = 0;
573 stack_info.frame_buffer = nullptr;
574 continue;
575 }
576 DCHECK_LE(collected_frames, static_cast<size_t>(max_frame_count));
577
578 jvmtiFrameInfo* frame_info = new jvmtiFrameInfo[collected_frames];
579 frame_infos.emplace_back(frame_info);
580
581 jint count;
582 jvmtiError translate_result = TranslateFrameVector(thread_frames,
583 0,
584 0,
585 static_cast<jint>(collected_frames),
586 frame_info,
587 &count);
588 DCHECK(translate_result == JVMTI_ERROR_NONE);
589 stack_info.frame_count = static_cast<jint>(collected_frames);
590 stack_info.frame_buffer = frame_info;
591 sum_frames += static_cast<size_t>(count);
592 }
593
594 // No errors, yet. Now put it all into an output buffer. Note that this is not frames.size(),
595 // potentially.
596 size_t rounded_stack_info_size = art::RoundUp(sizeof(jvmtiStackInfo) * thread_count,
597 alignof(jvmtiFrameInfo));
598 size_t chunk_size = rounded_stack_info_size + sum_frames * sizeof(jvmtiFrameInfo);
599 unsigned char* chunk_data;
600 jvmtiError alloc_result = env->Allocate(chunk_size, &chunk_data);
601 if (alloc_result != ERR(NONE)) {
602 return alloc_result;
603 }
604
605 jvmtiStackInfo* stack_info = reinterpret_cast<jvmtiStackInfo*>(chunk_data);
606 jvmtiFrameInfo* frame_info = reinterpret_cast<jvmtiFrameInfo*>(
607 chunk_data + rounded_stack_info_size);
608
609 for (size_t i = 0; i < static_cast<size_t>(thread_count); ++i) {
610 // Check whether we found a running thread for this.
611 // Note: For simplicity, and with the expectation that the list is usually small, use a simple
612 // search. (The list is *not* sorted!)
Andreas Gampef1221a12017-06-21 21:20:47 -0700613 auto it = std::find(data.thread_list_indices.begin(), data.thread_list_indices.end(), i);
614 if (it == data.thread_list_indices.end()) {
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800615 // No native thread. Must be new or dead. We need to fill out the stack info now.
616 // (Need to read the Java "started" field to know whether this is starting or terminated.)
617 art::ObjPtr<art::mirror::Object> peer = soa.Decode<art::mirror::Object>(thread_list[i]);
618 art::ObjPtr<art::mirror::Class> klass = peer->GetClass();
619 art::ArtField* started_field = klass->FindDeclaredInstanceField("started", "Z");
620 CHECK(started_field != nullptr);
621 bool started = started_field->GetBoolean(peer) != 0;
622 constexpr jint kStartedState = JVMTI_JAVA_LANG_THREAD_STATE_NEW;
623 constexpr jint kTerminatedState = JVMTI_THREAD_STATE_TERMINATED |
624 JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED;
625 stack_info[i].thread = reinterpret_cast<JNIEnv*>(soa.Env())->NewLocalRef(thread_list[i]);
626 stack_info[i].state = started ? kTerminatedState : kStartedState;
627 stack_info[i].frame_count = 0;
628 stack_info[i].frame_buffer = nullptr;
629 } else {
630 // Had a native thread and frames.
Andreas Gampef1221a12017-06-21 21:20:47 -0700631 size_t f_index = it - data.thread_list_indices.begin();
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800632
633 jvmtiStackInfo& old_stack_info = stack_info_array.get()[f_index];
634 jvmtiStackInfo& new_stack_info = stack_info[i];
635
636 memcpy(&new_stack_info, &old_stack_info, sizeof(jvmtiStackInfo));
637 new_stack_info.thread = reinterpret_cast<JNIEnv*>(soa.Env())->NewLocalRef(thread_list[i]);
638 if (old_stack_info.frame_count > 0) {
639 // Only copy when there's data - leave the nullptr alone.
640 size_t frames_size =
641 static_cast<size_t>(old_stack_info.frame_count) * sizeof(jvmtiFrameInfo);
642 memcpy(frame_info, old_stack_info.frame_buffer, frames_size);
643 new_stack_info.frame_buffer = frame_info;
644 frame_info += old_stack_info.frame_count;
645 }
646 }
647 }
648
Andreas Gampef1221a12017-06-21 21:20:47 -0700649 *stack_info_ptr = stack_info;
Andreas Gampeeba32fb2017-01-12 17:40:05 -0800650
651 return ERR(NONE);
652}
653
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800654// Walks up the stack counting Java frames. This is not StackVisitor::ComputeNumFrames, as
655// runtime methods and transitions must not be counted.
656struct GetFrameCountVisitor : public art::StackVisitor {
657 explicit GetFrameCountVisitor(art::Thread* thread)
658 : art::StackVisitor(thread, nullptr, art::StackVisitor::StackWalkKind::kIncludeInlinedFrames),
659 count(0) {}
660
661 bool VisitFrame() REQUIRES_SHARED(art::Locks::mutator_lock_) {
662 art::ArtMethod* m = GetMethod();
663 const bool do_count = !(m == nullptr || m->IsRuntimeMethod());
664 if (do_count) {
665 count++;
666 }
667 return true;
668 }
669
670 size_t count;
671};
672
673struct GetFrameCountClosure : public art::Closure {
674 public:
675 GetFrameCountClosure() : count(0) {}
676
677 void Run(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
678 GetFrameCountVisitor visitor(self);
679 visitor.WalkStack(false);
680
681 count = visitor.count;
682 }
683
684 size_t count;
685};
686
687jvmtiError StackUtil::GetFrameCount(jvmtiEnv* env ATTRIBUTE_UNUSED,
688 jthread java_thread,
689 jint* count_ptr) {
Andreas Gampe28c4a232017-06-21 21:21:31 -0700690 // It is not great that we have to hold these locks for so long, but it is necessary to ensure
691 // that the thread isn't dying on us.
692 art::ScopedObjectAccess soa(art::Thread::Current());
Alex Lightb1e31a82017-10-04 16:57:36 -0700693 art::Locks::thread_list_lock_->ExclusiveLock(soa.Self());
Andreas Gampe28c4a232017-06-21 21:21:31 -0700694
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800695 art::Thread* thread;
Alex Light7ddc23d2017-09-22 15:33:41 -0700696 jvmtiError thread_error = ERR(INTERNAL);
697 if (!ThreadUtil::GetAliveNativeThread(java_thread, soa, &thread, &thread_error)) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700698 art::Locks::thread_list_lock_->ExclusiveUnlock(soa.Self());
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800699 return thread_error;
700 }
Alex Light7ddc23d2017-09-22 15:33:41 -0700701
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800702 DCHECK(thread != nullptr);
Alex Light7ddc23d2017-09-22 15:33:41 -0700703 art::ThreadState state = thread->GetState();
704 if (state == art::ThreadState::kStarting || thread->IsStillStarting()) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700705 art::Locks::thread_list_lock_->ExclusiveUnlock(soa.Self());
Alex Light7ddc23d2017-09-22 15:33:41 -0700706 return ERR(THREAD_NOT_ALIVE);
707 }
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800708
709 if (count_ptr == nullptr) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700710 art::Locks::thread_list_lock_->ExclusiveUnlock(soa.Self());
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800711 return ERR(NULL_POINTER);
712 }
713
714 GetFrameCountClosure closure;
Alex Lightb1e31a82017-10-04 16:57:36 -0700715 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Lightd9aff132017-10-31 22:30:05 +0000716 if (!ThreadUtil::RequestGCSafeSynchronousCheckpoint(thread, &closure)) {
Alex Light7ddc23d2017-09-22 15:33:41 -0700717 return ERR(THREAD_NOT_ALIVE);
718 }
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800719
720 *count_ptr = closure.count;
721 return ERR(NONE);
722}
723
724// Walks up the stack 'n' callers, when used with Thread::WalkStack.
725struct GetLocationVisitor : public art::StackVisitor {
726 GetLocationVisitor(art::Thread* thread, size_t n_in)
727 : art::StackVisitor(thread, nullptr, art::StackVisitor::StackWalkKind::kIncludeInlinedFrames),
728 n(n_in),
729 count(0),
730 caller(nullptr),
731 caller_dex_pc(0) {}
732
733 bool VisitFrame() REQUIRES_SHARED(art::Locks::mutator_lock_) {
734 art::ArtMethod* m = GetMethod();
735 const bool do_count = !(m == nullptr || m->IsRuntimeMethod());
736 if (do_count) {
737 DCHECK(caller == nullptr);
738 if (count == n) {
739 caller = m;
740 caller_dex_pc = GetDexPc(false);
741 return false;
742 }
743 count++;
744 }
745 return true;
746 }
747
748 const size_t n;
749 size_t count;
750 art::ArtMethod* caller;
751 uint32_t caller_dex_pc;
752};
753
754struct GetLocationClosure : public art::Closure {
755 public:
756 explicit GetLocationClosure(size_t n_in) : n(n_in), method(nullptr), dex_pc(0) {}
757
758 void Run(art::Thread* self) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
759 GetLocationVisitor visitor(self, n);
760 visitor.WalkStack(false);
761
762 method = visitor.caller;
763 dex_pc = visitor.caller_dex_pc;
764 }
765
766 const size_t n;
767 art::ArtMethod* method;
768 uint32_t dex_pc;
769};
770
771jvmtiError StackUtil::GetFrameLocation(jvmtiEnv* env ATTRIBUTE_UNUSED,
772 jthread java_thread,
773 jint depth,
774 jmethodID* method_ptr,
775 jlocation* location_ptr) {
Andreas Gampe28c4a232017-06-21 21:21:31 -0700776 // It is not great that we have to hold these locks for so long, but it is necessary to ensure
777 // that the thread isn't dying on us.
778 art::ScopedObjectAccess soa(art::Thread::Current());
Alex Lightb1e31a82017-10-04 16:57:36 -0700779 art::Locks::thread_list_lock_->ExclusiveLock(soa.Self());
Andreas Gampe28c4a232017-06-21 21:21:31 -0700780
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800781 art::Thread* thread;
Alex Light7ddc23d2017-09-22 15:33:41 -0700782 jvmtiError thread_error = ERR(INTERNAL);
783 if (!ThreadUtil::GetAliveNativeThread(java_thread, soa, &thread, &thread_error)) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700784 art::Locks::thread_list_lock_->ExclusiveUnlock(soa.Self());
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800785 return thread_error;
786 }
787 DCHECK(thread != nullptr);
788
Alex Light7ddc23d2017-09-22 15:33:41 -0700789 art::ThreadState state = thread->GetState();
790 if (state == art::ThreadState::kStarting || thread->IsStillStarting()) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700791 art::Locks::thread_list_lock_->ExclusiveUnlock(soa.Self());
Alex Light7ddc23d2017-09-22 15:33:41 -0700792 return ERR(THREAD_NOT_ALIVE);
793 }
794
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800795 if (depth < 0) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700796 art::Locks::thread_list_lock_->ExclusiveUnlock(soa.Self());
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800797 return ERR(ILLEGAL_ARGUMENT);
798 }
799 if (method_ptr == nullptr || location_ptr == nullptr) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700800 art::Locks::thread_list_lock_->ExclusiveUnlock(soa.Self());
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800801 return ERR(NULL_POINTER);
802 }
803
804 GetLocationClosure closure(static_cast<size_t>(depth));
Alex Lightb1e31a82017-10-04 16:57:36 -0700805 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Lightd9aff132017-10-31 22:30:05 +0000806 if (!ThreadUtil::RequestGCSafeSynchronousCheckpoint(thread, &closure)) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700807 return ERR(THREAD_NOT_ALIVE);
808 }
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800809
810 if (closure.method == nullptr) {
811 return ERR(NO_MORE_FRAMES);
812 }
813
814 *method_ptr = art::jni::EncodeArtMethod(closure.method);
Alex Light3dea2122017-10-11 15:56:48 +0000815 if (closure.method->IsNative() || closure.method->IsProxyMethod()) {
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800816 *location_ptr = -1;
817 } else {
Andreas Gampee2abbc62017-09-15 11:59:26 -0700818 if (closure.dex_pc == art::dex::kDexNoIndex) {
Andreas Gampef6f3b5f2017-01-13 09:21:42 -0800819 return ERR(INTERNAL);
820 }
821 *location_ptr = static_cast<jlocation>(closure.dex_pc);
822 }
823
824 return ERR(NONE);
825}
826
Alex Light88e1ddd2017-08-21 13:09:55 -0700827struct MonitorVisitor : public art::StackVisitor, public art::SingleRootVisitor {
828 // We need a context because VisitLocks needs it retrieve the monitor objects.
829 explicit MonitorVisitor(art::Thread* thread)
830 REQUIRES_SHARED(art::Locks::mutator_lock_)
831 : art::StackVisitor(thread,
832 art::Context::Create(),
833 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames),
834 hs(art::Thread::Current()),
835 current_stack_depth(0) {}
836
837 ~MonitorVisitor() {
838 delete context_;
839 }
840
841 bool VisitFrame() OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
842 art::Locks::mutator_lock_->AssertSharedHeld(art::Thread::Current());
843 if (!GetMethod()->IsRuntimeMethod()) {
844 art::Monitor::VisitLocks(this, AppendOwnedMonitors, this);
845 ++current_stack_depth;
846 }
847 return true;
848 }
849
850 static void AppendOwnedMonitors(art::mirror::Object* owned_monitor, void* arg)
851 REQUIRES_SHARED(art::Locks::mutator_lock_) {
852 art::Locks::mutator_lock_->AssertSharedHeld(art::Thread::Current());
853 MonitorVisitor* visitor = reinterpret_cast<MonitorVisitor*>(arg);
854 art::ObjPtr<art::mirror::Object> mon(owned_monitor);
855 // Filter out duplicates.
856 for (const art::Handle<art::mirror::Object>& monitor : visitor->monitors) {
857 if (monitor.Get() == mon.Ptr()) {
858 return;
859 }
860 }
861 visitor->monitors.push_back(visitor->hs.NewHandle(mon));
862 visitor->stack_depths.push_back(visitor->current_stack_depth);
863 }
864
865 void VisitRoot(art::mirror::Object* obj, const art::RootInfo& info ATTRIBUTE_UNUSED)
866 OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
867 for (const art::Handle<art::mirror::Object>& m : monitors) {
868 if (m.Get() == obj) {
869 return;
870 }
871 }
872 monitors.push_back(hs.NewHandle(obj));
873 stack_depths.push_back(-1);
874 }
875
876 art::VariableSizedHandleScope hs;
877 jint current_stack_depth;
878 std::vector<art::Handle<art::mirror::Object>> monitors;
879 std::vector<jint> stack_depths;
880};
881
882template<typename Fn>
883struct MonitorInfoClosure : public art::Closure {
884 public:
885 MonitorInfoClosure(art::ScopedObjectAccess& soa, Fn handle_results)
886 : soa_(soa), err_(OK), handle_results_(handle_results) {}
887
888 void Run(art::Thread* target) OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
889 art::Locks::mutator_lock_->AssertSharedHeld(art::Thread::Current());
890 // Find the monitors on the stack.
891 MonitorVisitor visitor(target);
892 visitor.WalkStack(/* include_transitions */ false);
893 // Find any other monitors, including ones acquired in native code.
894 art::RootInfo root_info(art::kRootVMInternal);
Ian Rogers55256cb2017-12-21 17:07:11 -0800895 target->GetJniEnv()->VisitMonitorRoots(&visitor, root_info);
Alex Light88e1ddd2017-08-21 13:09:55 -0700896 err_ = handle_results_(soa_, visitor);
897 }
898
899 jvmtiError GetError() {
900 return err_;
901 }
902
903 private:
904 art::ScopedObjectAccess& soa_;
905 jvmtiError err_;
906 Fn handle_results_;
907};
908
909
910template <typename Fn>
911static jvmtiError GetOwnedMonitorInfoCommon(jthread thread, Fn handle_results) {
912 art::Thread* self = art::Thread::Current();
913 art::ScopedObjectAccess soa(self);
914 MonitorInfoClosure<Fn> closure(soa, handle_results);
915 bool called_method = false;
916 {
Alex Lightb1e31a82017-10-04 16:57:36 -0700917 art::Locks::thread_list_lock_->ExclusiveLock(self);
Alex Light7ddc23d2017-09-22 15:33:41 -0700918 art::Thread* target = nullptr;
919 jvmtiError err = ERR(INTERNAL);
920 if (!ThreadUtil::GetAliveNativeThread(thread, soa, &target, &err)) {
Alex Lightb1e31a82017-10-04 16:57:36 -0700921 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light7ddc23d2017-09-22 15:33:41 -0700922 return err;
Alex Light88e1ddd2017-08-21 13:09:55 -0700923 }
924 if (target != self) {
925 called_method = true;
Alex Lightb1e31a82017-10-04 16:57:36 -0700926 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Lightd9aff132017-10-31 22:30:05 +0000927 if (!ThreadUtil::RequestGCSafeSynchronousCheckpoint(target, &closure)) {
Alex Light88e1ddd2017-08-21 13:09:55 -0700928 return ERR(THREAD_NOT_ALIVE);
929 }
Alex Lightb1e31a82017-10-04 16:57:36 -0700930 } else {
931 art::Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light88e1ddd2017-08-21 13:09:55 -0700932 }
933 }
934 // Cannot call the closure on the current thread if we have thread_list_lock since we need to call
935 // into the verifier which can cause the current thread to suspend for gc. Suspending would be a
936 // bad thing to do if we hold the ThreadListLock. For other threads since we are running it on a
937 // checkpoint we are fine but if the thread is the current one we need to drop the mutex first.
938 if (!called_method) {
939 closure.Run(self);
940 }
941 return closure.GetError();
942}
943
944jvmtiError StackUtil::GetOwnedMonitorStackDepthInfo(jvmtiEnv* env,
945 jthread thread,
946 jint* info_cnt,
947 jvmtiMonitorStackDepthInfo** info_ptr) {
948 if (info_cnt == nullptr || info_ptr == nullptr) {
949 return ERR(NULL_POINTER);
950 }
951 auto handle_fun = [&] (art::ScopedObjectAccess& soa, MonitorVisitor& visitor)
952 REQUIRES_SHARED(art::Locks::mutator_lock_) {
953 auto nbytes = sizeof(jvmtiMonitorStackDepthInfo) * visitor.monitors.size();
954 jvmtiError err = env->Allocate(nbytes, reinterpret_cast<unsigned char**>(info_ptr));
955 if (err != OK) {
956 return err;
957 }
958 *info_cnt = visitor.monitors.size();
959 for (size_t i = 0; i < visitor.monitors.size(); i++) {
960 (*info_ptr)[i] = {
961 soa.Env()->AddLocalReference<jobject>(visitor.monitors[i].Get()),
962 visitor.stack_depths[i]
963 };
964 }
965 return OK;
966 };
967 return GetOwnedMonitorInfoCommon(thread, handle_fun);
968}
969
970jvmtiError StackUtil::GetOwnedMonitorInfo(jvmtiEnv* env,
971 jthread thread,
972 jint* owned_monitor_count_ptr,
973 jobject** owned_monitors_ptr) {
974 if (owned_monitors_ptr == nullptr || owned_monitors_ptr == nullptr) {
975 return ERR(NULL_POINTER);
976 }
977 auto handle_fun = [&] (art::ScopedObjectAccess& soa, MonitorVisitor& visitor)
978 REQUIRES_SHARED(art::Locks::mutator_lock_) {
979 auto nbytes = sizeof(jobject) * visitor.monitors.size();
980 jvmtiError err = env->Allocate(nbytes, reinterpret_cast<unsigned char**>(owned_monitors_ptr));
981 if (err != OK) {
982 return err;
983 }
984 *owned_monitor_count_ptr = visitor.monitors.size();
985 for (size_t i = 0; i < visitor.monitors.size(); i++) {
986 (*owned_monitors_ptr)[i] =
987 soa.Env()->AddLocalReference<jobject>(visitor.monitors[i].Get());
988 }
989 return OK;
990 };
991 return GetOwnedMonitorInfoCommon(thread, handle_fun);
992}
993
Alex Lighte814f9d2017-07-31 16:14:39 -0700994jvmtiError StackUtil::NotifyFramePop(jvmtiEnv* env, jthread thread, jint depth) {
995 if (depth < 0) {
996 return ERR(ILLEGAL_ARGUMENT);
997 }
998 ArtJvmTiEnv* tienv = ArtJvmTiEnv::AsArtJvmTiEnv(env);
999 art::Thread* self = art::Thread::Current();
1000 art::Thread* target;
1001 do {
1002 ThreadUtil::SuspendCheck(self);
1003 art::MutexLock ucsl_mu(self, *art::Locks::user_code_suspension_lock_);
1004 // Make sure we won't be suspended in the middle of holding the thread_suspend_count_lock_ by a
1005 // user-code suspension. We retry and do another SuspendCheck to clear this.
1006 if (ThreadUtil::WouldSuspendForUserCodeLocked(self)) {
1007 continue;
1008 }
1009 // From now on we know we cannot get suspended by user-code.
1010 // NB This does a SuspendCheck (during thread state change) so we need to make sure we don't
1011 // have the 'suspend_lock' locked here.
1012 art::ScopedObjectAccess soa(self);
1013 art::MutexLock tll_mu(self, *art::Locks::thread_list_lock_);
Alex Light7ddc23d2017-09-22 15:33:41 -07001014 jvmtiError err = ERR(INTERNAL);
1015 if (!ThreadUtil::GetAliveNativeThread(thread, soa, &target, &err)) {
1016 return err;
1017 }
1018 if (target != self) {
Alex Lighte814f9d2017-07-31 16:14:39 -07001019 // TODO This is part of the spec but we could easily avoid needing to do it. We would just put
1020 // all the logic into a sync-checkpoint.
1021 art::MutexLock tscl_mu(self, *art::Locks::thread_suspend_count_lock_);
1022 if (target->GetUserCodeSuspendCount() == 0) {
1023 return ERR(THREAD_NOT_SUSPENDED);
1024 }
1025 }
1026 // We hold the user_code_suspension_lock_ so the target thread is staying suspended until we are
1027 // done (unless it's 'self' in which case we don't care since we aren't going to be returning).
1028 // TODO We could implement this using a synchronous checkpoint and not bother with any of the
1029 // suspension stuff. The spec does specifically say to return THREAD_NOT_SUSPENDED though.
1030 // Find the requested stack frame.
1031 std::unique_ptr<art::Context> context(art::Context::Create());
1032 FindFrameAtDepthVisitor visitor(target, context.get(), depth);
1033 visitor.WalkStack();
1034 if (!visitor.FoundFrame()) {
1035 return ERR(NO_MORE_FRAMES);
1036 }
1037 art::ArtMethod* method = visitor.GetMethod();
1038 if (method->IsNative()) {
1039 return ERR(OPAQUE_FRAME);
1040 }
1041 // From here we are sure to succeed.
1042 bool needs_instrument = false;
1043 // Get/create a shadow frame
1044 art::ShadowFrame* shadow_frame = visitor.GetCurrentShadowFrame();
1045 if (shadow_frame == nullptr) {
1046 needs_instrument = true;
1047 const size_t frame_id = visitor.GetFrameId();
David Sehr0225f8e2018-01-31 08:52:24 +00001048 const uint16_t num_regs = method->DexInstructionData().RegistersSize();
Alex Lighte814f9d2017-07-31 16:14:39 -07001049 shadow_frame = target->FindOrCreateDebuggerShadowFrame(frame_id,
1050 num_regs,
1051 method,
1052 visitor.GetDexPc());
1053 }
Alex Lightb6106d52017-10-18 15:02:15 -07001054 {
1055 art::WriterMutexLock lk(self, tienv->event_info_mutex_);
1056 // Mark shadow frame as needs_notify_pop_
1057 shadow_frame->SetNotifyPop(true);
1058 tienv->notify_frames.insert(shadow_frame);
1059 }
Alex Lighte814f9d2017-07-31 16:14:39 -07001060 // Make sure can we will go to the interpreter and use the shadow frames.
1061 if (needs_instrument) {
1062 art::Runtime::Current()->GetInstrumentation()->InstrumentThreadStack(target);
1063 }
1064 return OK;
1065 } while (true);
1066}
1067
Andreas Gampeb5eb94a2016-10-27 19:23:09 -07001068} // namespace openjdkjvmti