1/*
2 * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include "precompiled.hpp"
26#include "classfile/javaClasses.hpp"
27#include "classfile/javaClasses.inline.hpp"
28#include "classfile/vmSymbols.hpp"
29#include "logging/log.hpp"
30#include "memory/oopFactory.hpp"
31#include "oops/oop.inline.hpp"
32#include "oops/objArrayOop.inline.hpp"
33#include "prims/stackwalk.hpp"
34#include "runtime/globals.hpp"
35#include "runtime/handles.inline.hpp"
36#include "runtime/javaCalls.hpp"
37#include "runtime/vframe.hpp"
38#include "utilities/globalDefinitions.hpp"
39
40// setup and cleanup actions
41void BaseFrameStream::setup_magic_on_entry(objArrayHandle frames_array) {
42  frames_array->obj_at_put(magic_pos, _thread->threadObj());
43  _anchor = address_value();
44  assert(check_magic(frames_array), "invalid magic");
45}
46
47bool BaseFrameStream::check_magic(objArrayHandle frames_array) {
48  oop   m1 = frames_array->obj_at(magic_pos);
49  jlong m2 = _anchor;
50  if (m1 == _thread->threadObj() && m2 == address_value())  return true;
51  return false;
52}
53
54bool BaseFrameStream::cleanup_magic_on_exit(objArrayHandle frames_array) {
55  bool ok = check_magic(frames_array);
56  frames_array->obj_at_put(magic_pos, NULL);
57  _anchor = 0L;
58  return ok;
59}
60
61JavaFrameStream::JavaFrameStream(JavaThread* thread, int mode)
62  : BaseFrameStream(thread), _vfst(thread) {
63  _need_method_info = StackWalk::need_method_info(mode);
64}
65
66// Returns the BaseFrameStream for the current stack being traversed.
67//
68// Parameters:
69//  thread         Current Java thread.
70//  magic          Magic value used for each stack walking
71//  frames_array   User-supplied buffers.  The 0th element is reserved
72//                 for this BaseFrameStream to use
73//
74BaseFrameStream* BaseFrameStream::from_current(JavaThread* thread, jlong magic,
75                                               objArrayHandle frames_array)
76{
77  assert(thread != NULL && thread->is_Java_thread(), "");
78  oop m1 = frames_array->obj_at(magic_pos);
79  if (m1 != thread->threadObj())      return NULL;
80  if (magic == 0L)                    return NULL;
81  BaseFrameStream* stream = (BaseFrameStream*) (intptr_t) magic;
82  if (!stream->is_valid_in(thread, frames_array))   return NULL;
83  return stream;
84}
85
86// Unpacks one or more frames into user-supplied buffers.
87// Updates the end index, and returns the number of unpacked frames.
88// Always start with the existing vfst.method and bci.
89// Do not call vfst.next to advance over the last returned value.
90// In other words, do not leave any stale data in the vfst.
91//
92// Parameters:
93//   mode             Restrict which frames to be decoded.
94//   BaseFrameStream  stream of frames
95//   max_nframes      Maximum number of frames to be filled.
96//   start_index      Start index to the user-supplied buffers.
97//   frames_array     Buffer to store Class or StackFrame in, starting at start_index.
98//                    frames array is a Class<?>[] array when only getting caller
99//                    reference, and a StackFrameInfo[] array (or derivative)
100//                    otherwise. It should never be null.
101//   end_index        End index to the user-supplied buffers with unpacked frames.
102//
103// Returns the number of frames whose information was transferred into the buffers.
104//
105int StackWalk::fill_in_frames(jlong mode, BaseFrameStream& stream,
106                              int max_nframes, int start_index,
107                              objArrayHandle  frames_array,
108                              int& end_index, TRAPS) {
109  log_debug(stackwalk)("fill_in_frames limit=%d start=%d frames length=%d",
110                       max_nframes, start_index, frames_array->length());
111  assert(max_nframes > 0, "invalid max_nframes");
112  assert(start_index + max_nframes <= frames_array->length(), "oob");
113
114  int frames_decoded = 0;
115  for (; !stream.at_end(); stream.next()) {
116    Method* method = stream.method();
117
118    if (method == NULL) continue;
119
120    // skip hidden frames for default StackWalker option (i.e. SHOW_HIDDEN_FRAMES
121    // not set) and when StackWalker::getCallerClass is called
122    if (!ShowHiddenFrames && (skip_hidden_frames(mode) || get_caller_class(mode))) {
123      if (method->is_hidden()) {
124        if (log_is_enabled(Debug, stackwalk)) {
125          ResourceMark rm(THREAD);
126          outputStream* st = Log(stackwalk)::debug_stream();
127          st->print("  hidden method: ");
128          method->print_short_name(st);
129          st->cr();
130        }
131        continue;
132      }
133    }
134
135    int index = end_index++;
136    if (log_is_enabled(Debug, stackwalk)) {
137      ResourceMark rm(THREAD);
138      outputStream* st = Log(stackwalk)::debug_stream();
139      st->print("  %d: frame method: ", index);
140      method->print_short_name(st);
141      st->print_cr(" bci=%d", stream.bci());
142    }
143
144    if (!need_method_info(mode) && get_caller_class(mode) &&
145          index == start_index && method->caller_sensitive()) {
146      ResourceMark rm(THREAD);
147      THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(),
148        err_msg("StackWalker::getCallerClass called from @CallerSensitive %s method",
149                method->name_and_sig_as_C_string()));
150    }
151    // fill in StackFrameInfo and initialize MemberName
152    stream.fill_frame(index, frames_array, method, CHECK_0);
153    if (++frames_decoded >= max_nframes)  break;
154  }
155  return frames_decoded;
156}
157
158// Fill in the LiveStackFrameInfo at the given index in frames_array
159void LiveFrameStream::fill_frame(int index, objArrayHandle  frames_array,
160                                 const methodHandle& method, TRAPS) {
161  Handle stackFrame(THREAD, frames_array->obj_at(index));
162  fill_live_stackframe(stackFrame, method, CHECK);
163}
164
165// Fill in the StackFrameInfo at the given index in frames_array
166void JavaFrameStream::fill_frame(int index, objArrayHandle  frames_array,
167                                 const methodHandle& method, TRAPS) {
168  if (_need_method_info) {
169    Handle stackFrame(THREAD, frames_array->obj_at(index));
170    fill_stackframe(stackFrame, method);
171  } else {
172    frames_array->obj_at_put(index, method->method_holder()->java_mirror());
173  }
174}
175
176// Create and return a LiveStackFrame.PrimitiveSlot (if needed) for the
177// StackValue at the given index. 'type' is expected to be T_INT, T_LONG,
178// T_OBJECT, or T_CONFLICT.
179oop LiveFrameStream::create_primitive_slot_instance(StackValueCollection* values,
180                                                    int i, BasicType type, TRAPS) {
181  Klass* k = SystemDictionary::resolve_or_null(vmSymbols::java_lang_LiveStackFrameInfo(), CHECK_NULL);
182  instanceKlassHandle ik (THREAD, k);
183
184  JavaValue result(T_OBJECT);
185  JavaCallArguments args;
186  Symbol* signature = NULL;
187
188  // ## TODO: type is only available in LocalVariable table, if present.
189  // ## StackValue type is T_INT or T_OBJECT (or converted to T_LONG on 64-bit)
190  switch (type) {
191    case T_INT:
192      args.push_int(values->int_at(i));
193      signature = vmSymbols::asPrimitive_int_signature();
194      break;
195
196    case T_LONG:
197      args.push_long(values->long_at(i));
198      signature = vmSymbols::asPrimitive_long_signature();
199      break;
200
201    case T_FLOAT:
202    case T_DOUBLE:
203    case T_BYTE:
204    case T_SHORT:
205    case T_CHAR:
206    case T_BOOLEAN:
207      THROW_MSG_(vmSymbols::java_lang_InternalError(), "Unexpected StackValue type", NULL);
208
209    case T_OBJECT:
210      return values->obj_at(i)();
211
212    case T_CONFLICT:
213      // put a non-null slot
214      #ifdef _LP64
215        args.push_long(0);
216        signature = vmSymbols::asPrimitive_long_signature();
217      #else
218        args.push_int(0);
219        signature = vmSymbols::asPrimitive_int_signature();
220      #endif
221
222      break;
223
224    default: ShouldNotReachHere();
225  }
226  JavaCalls::call_static(&result,
227                         ik,
228                         vmSymbols::asPrimitive_name(),
229                         signature,
230                         &args,
231                         CHECK_NULL);
232  return (instanceOop) result.get_jobject();
233}
234
235objArrayHandle LiveFrameStream::values_to_object_array(StackValueCollection* values, TRAPS) {
236  objArrayHandle empty;
237  int length = values->size();
238  objArrayOop array_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(),
239                                                   length, CHECK_(empty));
240  objArrayHandle array_h(THREAD, array_oop);
241  for (int i = 0; i < values->size(); i++) {
242    StackValue* st = values->at(i);
243    BasicType type = st->type();
244    int index = i;
245#ifdef _LP64
246    if (type != T_OBJECT && type != T_CONFLICT) {
247        intptr_t ret = st->get_int(); // read full 64-bit slot
248        type = T_LONG;                // treat as long
249        index--;                      // undo +1 in StackValueCollection::long_at
250    }
251#endif
252    oop obj = create_primitive_slot_instance(values, index, type, CHECK_(empty));
253    if (obj != NULL) {
254      array_h->obj_at_put(i, obj);
255    }
256  }
257  return array_h;
258}
259
260objArrayHandle LiveFrameStream::monitors_to_object_array(GrowableArray<MonitorInfo*>* monitors, TRAPS) {
261  int length = monitors->length();
262  objArrayOop array_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(),
263                                                   length, CHECK_(objArrayHandle()));
264  objArrayHandle array_h(THREAD, array_oop);
265  for (int i = 0; i < length; i++) {
266    MonitorInfo* monitor = monitors->at(i);
267    array_h->obj_at_put(i, monitor->owner());
268  }
269  return array_h;
270}
271
272// Fill StackFrameInfo with declaringClass and bci and initialize memberName
273void BaseFrameStream::fill_stackframe(Handle stackFrame, const methodHandle& method) {
274  java_lang_StackFrameInfo::set_declaringClass(stackFrame(), method->method_holder()->java_mirror());
275  java_lang_StackFrameInfo::set_method_and_bci(stackFrame(), method, bci());
276}
277
278// Fill LiveStackFrameInfo with locals, monitors, and expressions
279void LiveFrameStream::fill_live_stackframe(Handle stackFrame,
280                                           const methodHandle& method, TRAPS) {
281  fill_stackframe(stackFrame, method);
282  if (_jvf != NULL) {
283    StackValueCollection* locals = _jvf->locals();
284    StackValueCollection* expressions = _jvf->expressions();
285    GrowableArray<MonitorInfo*>* monitors = _jvf->monitors();
286
287    int mode = 0;
288    if (_jvf->is_interpreted_frame()) {
289      mode = MODE_INTERPRETED;
290    } else if (_jvf->is_compiled_frame()) {
291      mode = MODE_COMPILED;
292    }
293
294    if (!locals->is_empty()) {
295      objArrayHandle locals_h = values_to_object_array(locals, CHECK);
296      java_lang_LiveStackFrameInfo::set_locals(stackFrame(), locals_h());
297    }
298    if (!expressions->is_empty()) {
299      objArrayHandle expressions_h = values_to_object_array(expressions, CHECK);
300      java_lang_LiveStackFrameInfo::set_operands(stackFrame(), expressions_h());
301    }
302    if (monitors->length() > 0) {
303      objArrayHandle monitors_h = monitors_to_object_array(monitors, CHECK);
304      java_lang_LiveStackFrameInfo::set_monitors(stackFrame(), monitors_h());
305    }
306    java_lang_LiveStackFrameInfo::set_mode(stackFrame(), mode);
307  }
308}
309
310// Begins stack walking.
311//
312// Parameters:
313//   stackStream    StackStream object
314//   mode           Stack walking mode.
315//   skip_frames    Number of frames to be skipped.
316//   frame_count    Number of frames to be traversed.
317//   start_index    Start index to the user-supplied buffers.
318//   frames_array   Buffer to store StackFrame in, starting at start_index.
319//                  frames array is a Class<?>[] array when only getting caller
320//                  reference, and a StackFrameInfo[] array (or derivative)
321//                  otherwise. It should never be null.
322//
323// Returns Object returned from AbstractStackWalker::doStackWalk call.
324//
325oop StackWalk::walk(Handle stackStream, jlong mode,
326                    int skip_frames, int frame_count, int start_index,
327                    objArrayHandle frames_array,
328                    TRAPS) {
329  ResourceMark rm(THREAD);
330  JavaThread* jt = (JavaThread*)THREAD;
331  log_debug(stackwalk)("Start walking: mode " JLONG_FORMAT " skip %d frames batch size %d",
332                       mode, skip_frames, frame_count);
333
334  if (frames_array.is_null()) {
335    THROW_MSG_(vmSymbols::java_lang_NullPointerException(), "frames_array is NULL", NULL);
336  }
337
338  // Setup traversal onto my stack.
339  if (live_frame_info(mode)) {
340    assert (use_frames_array(mode), "Bad mode for get live frame");
341    RegisterMap regMap(jt, true);
342    LiveFrameStream stream(jt, &regMap);
343    return fetchFirstBatch(stream, stackStream, mode, skip_frames, frame_count,
344                           start_index, frames_array, THREAD);
345  } else {
346    JavaFrameStream stream(jt, mode);
347    return fetchFirstBatch(stream, stackStream, mode, skip_frames, frame_count,
348                           start_index, frames_array, THREAD);
349  }
350}
351
352oop StackWalk::fetchFirstBatch(BaseFrameStream& stream, Handle stackStream,
353                               jlong mode, int skip_frames, int frame_count,
354                               int start_index, objArrayHandle frames_array, TRAPS) {
355  methodHandle m_doStackWalk(THREAD, Universe::do_stack_walk_method());
356
357  {
358    Klass* stackWalker_klass = SystemDictionary::StackWalker_klass();
359    Klass* abstractStackWalker_klass = SystemDictionary::AbstractStackWalker_klass();
360    while (!stream.at_end()) {
361      InstanceKlass* ik = stream.method()->method_holder();
362      if (ik != stackWalker_klass &&
363            ik != abstractStackWalker_klass && ik->super() != abstractStackWalker_klass)  {
364        break;
365      }
366
367      if (log_is_enabled(Debug, stackwalk)) {
368        ResourceMark rm(THREAD);
369        outputStream* st = Log(stackwalk)::debug_stream();
370        st->print("  skip ");
371        stream.method()->print_short_name(st);
372        st->cr();
373      }
374      stream.next();
375    }
376
377    // stack frame has been traversed individually and resume stack walk
378    // from the stack frame at depth == skip_frames.
379    for (int n=0; n < skip_frames && !stream.at_end(); stream.next(), n++) {
380      if (log_is_enabled(Debug, stackwalk)) {
381        ResourceMark rm(THREAD);
382        outputStream* st = Log(stackwalk)::debug_stream();
383        st->print("  skip ");
384        stream.method()->print_short_name(st);
385        st->cr();
386      }
387    }
388  }
389
390  int end_index = start_index;
391  int numFrames = 0;
392  if (!stream.at_end()) {
393    numFrames = fill_in_frames(mode, stream, frame_count, start_index,
394                               frames_array, end_index, CHECK_NULL);
395    if (numFrames < 1) {
396      THROW_MSG_(vmSymbols::java_lang_InternalError(), "stack walk: decode failed", NULL);
397    }
398  }
399
400  // JVM_CallStackWalk walks the stack and fills in stack frames, then calls to
401  // Java method java.lang.StackStreamFactory.AbstractStackWalker::doStackWalk
402  // which calls the implementation to consume the stack frames.
403  // When JVM_CallStackWalk returns, it invalidates the stack stream.
404  JavaValue result(T_OBJECT);
405  JavaCallArguments args(stackStream);
406  args.push_long(stream.address_value());
407  args.push_int(skip_frames);
408  args.push_int(frame_count);
409  args.push_int(start_index);
410  args.push_int(end_index);
411
412  // Link the thread and vframe stream into the callee-visible object
413  stream.setup_magic_on_entry(frames_array);
414
415  JavaCalls::call(&result, m_doStackWalk, &args, THREAD);
416
417  // Do this before anything else happens, to disable any lingering stream objects
418  bool ok = stream.cleanup_magic_on_exit(frames_array);
419
420  // Throw pending exception if we must
421  (void) (CHECK_NULL);
422
423  if (!ok) {
424    THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: corrupted buffers on exit", NULL);
425  }
426
427  // Return normally
428  return (oop)result.get_jobject();
429}
430
431// Walk the next batch of stack frames
432//
433// Parameters:
434//   stackStream    StackStream object
435//   mode           Stack walking mode.
436//   magic          Must be valid value to continue the stack walk
437//   frame_count    Number of frames to be decoded.
438//   start_index    Start index to the user-supplied buffers.
439//   frames_array   Buffer to store StackFrame in, starting at start_index.
440//
441// Returns the end index of frame filled in the buffer.
442//
443jint StackWalk::fetchNextBatch(Handle stackStream, jlong mode, jlong magic,
444                               int frame_count, int start_index,
445                               objArrayHandle frames_array,
446                               TRAPS)
447{
448  JavaThread* jt = (JavaThread*)THREAD;
449  BaseFrameStream* existing_stream = BaseFrameStream::from_current(jt, magic, frames_array);
450  if (existing_stream == NULL) {
451    THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: corrupted buffers", 0L);
452  }
453
454  if (frames_array.is_null()) {
455    THROW_MSG_(vmSymbols::java_lang_NullPointerException(), "frames_array is NULL", 0L);
456  }
457
458  log_debug(stackwalk)("StackWalk::fetchNextBatch frame_count %d existing_stream "
459                       PTR_FORMAT " start %d frames %d",
460                       frame_count, p2i(existing_stream), start_index, frames_array->length());
461  int end_index = start_index;
462  if (frame_count <= 0) {
463    return end_index;        // No operation.
464  }
465
466  int count = frame_count + start_index;
467  assert (frames_array->length() >= count, "not enough space in buffers");
468
469  BaseFrameStream& stream = (*existing_stream);
470  if (!stream.at_end()) {
471    stream.next(); // advance past the last frame decoded in previous batch
472    if (!stream.at_end()) {
473      int n = fill_in_frames(mode, stream, frame_count, start_index,
474                             frames_array, end_index, CHECK_0);
475      if (n < 1) {
476        THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: later decode failed", 0L);
477      }
478      return end_index;
479    }
480  }
481  return end_index;
482}
483