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 "memory/oopFactory.hpp"
  30 #include "oops/oop.inline.hpp"
  31 #include "oops/objArrayOop.inline.hpp"
  32 #include "prims/stackwalk.hpp"
  33 #include "runtime/globals.hpp"
  34 #include "runtime/handles.inline.hpp"
  35 #include "runtime/javaCalls.hpp"
  36 #include "runtime/vframe.hpp"
  37 #include "utilities/globalDefinitions.hpp"
  38 
  39 // setup and cleanup actions
  40 void JavaFrameStream::setup_magic_on_entry(objArrayHandle frames_array) {
  41   frames_array->obj_at_put(magic_pos, _thread->threadObj());
  42   _anchor = address_value();
  43   assert(check_magic(frames_array), "invalid magic");
  44 }
  45 
  46 bool JavaFrameStream::check_magic(objArrayHandle frames_array) {
  47   oop   m1 = frames_array->obj_at(magic_pos);
  48   jlong m2 = _anchor;
  49   if (m1 == _thread->threadObj() && m2 == address_value())  return true;
  50   return false;
  51 }
  52 
  53 bool JavaFrameStream::cleanup_magic_on_exit(objArrayHandle frames_array) {
  54   bool ok = check_magic(frames_array);
  55   frames_array->obj_at_put(magic_pos, NULL);
  56   _anchor = 0L;
  57   return ok;
  58 }
  59 
  60 // Returns JavaFrameStream for the current stack being traversed.
  61 //
  62 // Parameters:
  63 //  thread         Current Java thread.
  64 //  magic          Magic value used for each stack walking
  65 //  frames_array   User-supplied buffers.  The 0th element is reserved
  66 //                 to this JavaFrameStream to use
  67 //
  68 JavaFrameStream* JavaFrameStream::from_current(JavaThread* thread, jlong magic,
  69                                                objArrayHandle frames_array)
  70 {
  71   assert(thread != NULL && thread->is_Java_thread(), "");
  72   oop m1 = frames_array->obj_at(magic_pos);
  73   if (m1 != thread->threadObj())      return NULL;
  74   if (magic == 0L)                    return NULL;
  75   JavaFrameStream* stream = (JavaFrameStream*) (intptr_t) magic;
  76   if (!stream->is_valid_in(thread, frames_array))   return NULL;
  77   return stream;
  78 }
  79 
  80 // Unpacks one or more frames into user-supplied buffers.
  81 // Updates the end index, and returns the number of unpacked frames.
  82 // Always start with the existing vfst.method and bci.
  83 // Do not call vfst.next to advance over the last returned value.
  84 // In other words, do not leave any stale data in the vfst.
  85 //
  86 // Parameters:
  87 //   mode             Restrict which frames to be decoded.
  88 //   JavaFrameStream  stream of javaVFrames
  89 //   max_nframes      Maximum number of frames to be filled.
  90 //   start_index      Start index to the user-supplied buffers.
  91 //   frames_array     Buffer to store Class or StackFrame in, starting at start_index.
  92 //                    frames array is a Class<?>[] array when only getting caller
  93 //                    reference, and a StackFrameInfo[] array (or derivative)
  94 //                    otherwise. It should never be null.
  95 //   end_index        End index to the user-supplied buffers with unpacked frames.
  96 //
  97 // Returns the number of frames whose information was transferred into the buffers.
  98 //
  99 int StackWalk::fill_in_frames(jlong mode, JavaFrameStream& stream,
 100                               int max_nframes, int start_index,
 101                               objArrayHandle  frames_array,
 102                               int& end_index, TRAPS) {
 103   if (TraceStackWalk) {
 104     tty->print_cr("fill_in_frames limit=%d start=%d frames length=%d",
 105                   max_nframes, start_index, frames_array->length());
 106   }
 107   assert(max_nframes > 0, "invalid max_nframes");
 108   assert(start_index + max_nframes <= frames_array->length(), "oob");
 109 
 110   int frames_decoded = 0;
 111   for (; !stream.at_end(); stream.next()) {
 112     Method* method = stream.method();
 113     int bci = stream.bci();
 114 
 115     if (method == NULL) continue;
 116     if (!ShowHiddenFrames && StackWalk::skip_hidden_frames(mode)) {
 117       if (method->is_hidden()) {
 118         if (TraceStackWalk) {
 119           tty->print("  hidden method: "); method->print_short_name();
 120           tty->print("\n");
 121         }
 122         continue;
 123       }
 124     }
 125 
 126     int index = end_index++;
 127     if (TraceStackWalk) {
 128       tty->print("  %d: frame method: ", index); method->print_short_name();
 129       tty->print_cr(" bci=%d", bci);
 130     }
 131 
 132     // fill in StackFrameInfo and initialize MemberName
 133     if (live_frame_info(mode)) {
 134       assert (use_frames_array(mode), "Bad mode for get live frame");
 135       Handle stackFrame(frames_array->obj_at(index));
 136       fill_live_stackframe(stackFrame, method, bci, stream.java_frame(), CHECK_0);
 137     } else if (need_method_info(mode)) {
 138       assert (use_frames_array(mode), "Bad mode for get stack frame");
 139       Handle stackFrame(frames_array->obj_at(index));
 140       fill_stackframe(stackFrame, method, bci);
 141     } else {
 142       assert (use_frames_array(mode) == false, "Bad mode for get caller class");
 143       frames_array->obj_at_put(index, method->method_holder()->java_mirror());
 144     }
 145     if (++frames_decoded >= max_nframes)  break;
 146   }
 147   return frames_decoded;
 148 }
 149 
 150 static oop create_primitive_value_instance(StackValueCollection* values, int i, TRAPS) {
 151   Klass* k = SystemDictionary::resolve_or_null(vmSymbols::java_lang_LiveStackFrameInfo(), CHECK_NULL);
 152   instanceKlassHandle ik (THREAD, k);
 153 
 154   JavaValue result(T_OBJECT);
 155   JavaCallArguments args;
 156   Symbol* signature = NULL;
 157 
 158   // ## TODO: type is only available in LocalVariable table, if present.
 159   // ## StackValue type is T_INT or T_OBJECT.
 160   switch (values->at(i)->type()) {
 161     case T_INT:
 162       args.push_int(values->int_at(i));
 163       signature = vmSymbols::asPrimitive_int_signature();
 164       break;
 165 
 166     case T_LONG:
 167       args.push_long(values->long_at(i));
 168       signature = vmSymbols::asPrimitive_long_signature();
 169       break;
 170 
 171     case T_FLOAT:
 172       args.push_float(values->float_at(i));
 173       signature = vmSymbols::asPrimitive_float_signature();
 174       break;
 175 
 176     case T_DOUBLE:
 177       args.push_double(values->double_at(i));
 178       signature = vmSymbols::asPrimitive_double_signature();
 179       break;
 180 
 181     case T_BYTE:
 182       args.push_int(values->int_at(i));
 183       signature = vmSymbols::asPrimitive_byte_signature();
 184       break;
 185 
 186     case T_SHORT:
 187       args.push_int(values->int_at(i));
 188       signature = vmSymbols::asPrimitive_short_signature();
 189       break;
 190 
 191     case T_CHAR:
 192       args.push_int(values->int_at(i));
 193       signature = vmSymbols::asPrimitive_char_signature();
 194       break;
 195 
 196     case T_BOOLEAN:
 197       args.push_int(values->int_at(i));
 198       signature = vmSymbols::asPrimitive_boolean_signature();
 199       break;
 200 
 201     case T_OBJECT:
 202       return values->obj_at(i)();
 203 
 204     case T_CONFLICT:
 205       // put a non-null slot
 206       args.push_int(0);
 207       signature = vmSymbols::asPrimitive_int_signature();
 208       break;
 209 
 210     default: ShouldNotReachHere();
 211   }
 212   JavaCalls::call_static(&result,
 213                          ik,
 214                          vmSymbols::asPrimitive_name(),
 215                          signature,
 216                          &args,
 217                          CHECK_NULL);
 218   return (instanceOop) result.get_jobject();
 219 }
 220 
 221 static objArrayHandle values_to_object_array(StackValueCollection* values, TRAPS) {
 222   objArrayHandle empty;
 223   int length = values->size();
 224   objArrayOop array_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(),
 225                                                    length, CHECK_(empty));
 226   objArrayHandle array_h(THREAD, array_oop);
 227   for (int i = 0; i < values->size(); i++) {
 228     StackValue* st = values->at(i);
 229     oop obj = create_primitive_value_instance(values, i, CHECK_(empty));
 230     if (obj != NULL)
 231       array_h->obj_at_put(i, obj);
 232   }
 233   return array_h;
 234 }
 235 
 236 static objArrayHandle monitors_to_object_array(GrowableArray<MonitorInfo*>* monitors, TRAPS) {
 237   int length = monitors->length();
 238   objArrayOop array_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(),
 239                                                    length, CHECK_(objArrayHandle()));
 240   objArrayHandle array_h(THREAD, array_oop);
 241   for (int i = 0; i < length; i++) {
 242     MonitorInfo* monitor = monitors->at(i);
 243     array_h->obj_at_put(i, monitor->owner());
 244   }
 245   return array_h;
 246 }
 247 
 248 // Fill StackFrameInfo with declaringClass and bci and initialize memberName
 249 void StackWalk::fill_stackframe(Handle stackFrame, const methodHandle& method, int bci) {
 250   java_lang_StackFrameInfo::set_declaringClass(stackFrame(), method->method_holder()->java_mirror());
 251   java_lang_StackFrameInfo::set_method_and_bci(stackFrame(), method, bci);
 252 }
 253 
 254 // Fill LiveStackFrameInfo with locals, monitors, and expressions
 255 void StackWalk::fill_live_stackframe(Handle stackFrame, const methodHandle& method,
 256                                      int bci, javaVFrame* jvf, TRAPS) {
 257   fill_stackframe(stackFrame, method, bci);
 258   if (jvf != NULL) {
 259     StackValueCollection* locals = jvf->locals();
 260     StackValueCollection* expressions = jvf->expressions();
 261     GrowableArray<MonitorInfo*>* monitors = jvf->monitors();
 262 
 263     if (!locals->is_empty()) {
 264       objArrayHandle locals_h = values_to_object_array(locals, CHECK);
 265       java_lang_LiveStackFrameInfo::set_locals(stackFrame(), locals_h());
 266     }
 267     if (!expressions->is_empty()) {
 268       objArrayHandle expressions_h = values_to_object_array(expressions, CHECK);
 269       java_lang_LiveStackFrameInfo::set_operands(stackFrame(), expressions_h());
 270     }
 271     if (monitors->length() > 0) {
 272       objArrayHandle monitors_h = monitors_to_object_array(monitors, CHECK);
 273       java_lang_LiveStackFrameInfo::set_monitors(stackFrame(), monitors_h());
 274     }
 275   }
 276 }
 277 
 278 // Begins stack walking.
 279 //
 280 // Parameters:
 281 //   stackStream    StackStream object
 282 //   mode           Stack walking mode.
 283 //   skip_frames    Number of frames to be skipped.
 284 //   frame_count    Number of frames to be traversed.
 285 //   start_index    Start index to the user-supplied buffers.
 286 //   frames_array   Buffer to store StackFrame in, starting at start_index.
 287 //                  frames array is a Class<?>[] array when only getting caller
 288 //                  reference, and a StackFrameInfo[] array (or derivative)
 289 //                  otherwise. It should never be null.
 290 //
 291 // Returns Object returned from AbstractStackWalker::doStackWalk call.
 292 //
 293 oop StackWalk::walk(Handle stackStream, jlong mode,
 294                     int skip_frames, int frame_count, int start_index,
 295                     objArrayHandle frames_array,
 296                     TRAPS) {
 297   ResourceMark rm(THREAD);
 298   JavaThread* jt = (JavaThread*)THREAD;
 299   if (TraceStackWalk) {
 300     tty->print_cr("Start walking: mode " JLONG_FORMAT " skip %d frames batch size %d",
 301                   mode, skip_frames, frame_count);
 302   }
 303 
 304   if (frames_array.is_null()) {
 305     THROW_MSG_(vmSymbols::java_lang_NullPointerException(), "frames_array is NULL", NULL);
 306   }
 307 
 308   Klass* stackWalker_klass = SystemDictionary::StackWalker_klass();
 309   Klass* abstractStackWalker_klass = SystemDictionary::AbstractStackWalker_klass();
 310 
 311   methodHandle m_doStackWalk(THREAD, Universe::do_stack_walk_method());
 312 
 313   // Setup traversal onto my stack.
 314   RegisterMap regMap(jt, true);
 315   JavaFrameStream stream(jt, &regMap);
 316   {
 317     while (!stream.at_end()) {
 318       InstanceKlass* ik = stream.method()->method_holder();
 319       if (ik != stackWalker_klass &&
 320             ik != abstractStackWalker_klass && ik->super() != abstractStackWalker_klass)  {
 321         break;
 322       }
 323 
 324       if (TraceStackWalk) {
 325         tty->print("  skip "); stream.method()->print_short_name(); tty->print("\n");
 326       }
 327       stream.next();
 328     }
 329 
 330     // stack frame has been traversed individually and resume stack walk
 331     // from the stack frame at depth == skip_frames.
 332     for (int n=0; n < skip_frames && !stream.at_end(); stream.next(), n++) {
 333       if (TraceStackWalk) {
 334         tty->print("  skip "); stream.method()->print_short_name();
 335         tty->print_cr(" frame id: " PTR_FORMAT " pc: " PTR_FORMAT,
 336                       p2i(stream.java_frame()->fr().id()),
 337                       p2i(stream.java_frame()->fr().pc()));
 338       }
 339     }
 340   }
 341 
 342   int end_index = start_index;
 343   int numFrames = 0;
 344   if (!stream.at_end()) {
 345     numFrames = fill_in_frames(mode, stream, frame_count, start_index,
 346                                frames_array, end_index, CHECK_NULL);
 347     if (numFrames < 1) {
 348       THROW_MSG_(vmSymbols::java_lang_InternalError(), "stack walk: decode failed", NULL);
 349     }
 350   }
 351 
 352   // JVM_CallStackWalk walks the stack and fills in stack frames, then calls to
 353   // Java method java.lang.StackStreamFactory.AbstractStackWalker::doStackWalk
 354   // which calls the implementation to consume the stack frames.
 355   // When JVM_CallStackWalk returns, it invalidates the stack stream.
 356   JavaValue result(T_OBJECT);
 357   JavaCallArguments args(stackStream);
 358   args.push_long(stream.address_value());
 359   args.push_int(skip_frames);
 360   args.push_int(frame_count);
 361   args.push_int(start_index);
 362   args.push_int(end_index);
 363 
 364   // Link the thread and vframe stream into the callee-visible object
 365   stream.setup_magic_on_entry(frames_array);
 366 
 367   JavaCalls::call(&result, m_doStackWalk, &args, THREAD);
 368 
 369   // Do this before anything else happens, to disable any lingering stream objects
 370   bool ok = stream.cleanup_magic_on_exit(frames_array);
 371 
 372   // Throw pending exception if we must
 373   (void) (CHECK_NULL);
 374 
 375   if (!ok) {
 376     THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: corrupted buffers on exit", NULL);
 377   }
 378 
 379   // Return normally
 380   return (oop)result.get_jobject();
 381 }
 382 
 383 // Walk the next batch of stack frames
 384 //
 385 // Parameters:
 386 //   stackStream    StackStream object
 387 //   mode           Stack walking mode.
 388 //   magic          Must be valid value to continue the stack walk
 389 //   frame_count    Number of frames to be decoded.
 390 //   start_index    Start index to the user-supplied buffers.
 391 //   frames_array   Buffer to store StackFrame in, starting at start_index.
 392 //
 393 // Returns the end index of frame filled in the buffer.
 394 //
 395 jint StackWalk::moreFrames(Handle stackStream, jlong mode, jlong magic,
 396                            int frame_count, int start_index,
 397                            objArrayHandle frames_array,
 398                            TRAPS)
 399 {
 400   JavaThread* jt = (JavaThread*)THREAD;
 401   JavaFrameStream* existing_stream = JavaFrameStream::from_current(jt, magic, frames_array);
 402   if (existing_stream == NULL) {
 403     THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: corrupted buffers", 0L);
 404   }
 405 
 406   if (frames_array.is_null()) {
 407     THROW_MSG_(vmSymbols::java_lang_NullPointerException(), "frames_array is NULL", 0L);
 408   }
 409 
 410   if (TraceStackWalk) {
 411     tty->print_cr("StackWalk::moreFrames frame_count %d existing_stream " PTR_FORMAT " start %d frames %d",
 412                   frame_count, p2i(existing_stream), start_index, frames_array->length());
 413   }
 414   int end_index = start_index;
 415   if (frame_count <= 0) {
 416     return end_index;        // No operation.
 417   }
 418 
 419   int count = frame_count + start_index;
 420   assert (frames_array->length() >= count, "not enough space in buffers");
 421 
 422   JavaFrameStream& stream = (*existing_stream);
 423   if (!stream.at_end()) {
 424     stream.next(); // advance past the last frame decoded in previous batch
 425     if (!stream.at_end()) {
 426       int n = fill_in_frames(mode, stream, frame_count, start_index,
 427                              frames_array, end_index, CHECK_0);
 428       if (n < 1) {
 429         THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: later decode failed", 0L);
 430       }
 431       return end_index;
 432     }
 433   }
 434   return end_index;
 435 }