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 
 117     // skip hidden frames for default StackWalker option (i.e. SHOW_HIDDEN_FRAMES
 118     // not set) and when StackWalker::getCallerClass is called
 119     if (!ShowHiddenFrames && (skip_hidden_frames(mode) || get_caller_class(mode))) {
 120       if (method->is_hidden()) {
 121         if (TraceStackWalk) {
 122           tty->print("  hidden method: "); method->print_short_name();
 123           tty->print("\n");
 124         }
 125         continue;
 126       }
 127     }
 128 
 129     int index = end_index++;
 130     if (TraceStackWalk) {
 131       tty->print("  %d: frame method: ", index); method->print_short_name();
 132       tty->print_cr(" bci=%d", bci);
 133     }
 134 
 135     // fill in StackFrameInfo and initialize MemberName
 136     if (live_frame_info(mode)) {
 137       assert (use_frames_array(mode), "Bad mode for get live frame");
 138       Handle stackFrame(frames_array->obj_at(index));
 139       fill_live_stackframe(stackFrame, method, bci, stream.java_frame(), CHECK_0);
 140     } else if (need_method_info(mode)) {
 141       assert (use_frames_array(mode), "Bad mode for get stack frame");
 142       Handle stackFrame(frames_array->obj_at(index));
 143       fill_stackframe(stackFrame, method, bci);
 144     } else {
 145       assert (get_caller_class(mode) == true, "Bad mode for get caller class");
 146       if (index == start_index && method->caller_sensitive()) {
 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 
 152       frames_array->obj_at_put(index, method->method_holder()->java_mirror());
 153     }
 154     if (++frames_decoded >= max_nframes)  break;
 155   }
 156   return frames_decoded;
 157 }
 158 
 159 static oop create_primitive_value_instance(StackValueCollection* values, int i, TRAPS) {
 160   Klass* k = SystemDictionary::resolve_or_null(vmSymbols::java_lang_LiveStackFrameInfo(), CHECK_NULL);
 161   instanceKlassHandle ik (THREAD, k);
 162 
 163   JavaValue result(T_OBJECT);
 164   JavaCallArguments args;
 165   Symbol* signature = NULL;
 166 
 167   // ## TODO: type is only available in LocalVariable table, if present.
 168   // ## StackValue type is T_INT or T_OBJECT.
 169   switch (values->at(i)->type()) {
 170     case T_INT:
 171       args.push_int(values->int_at(i));
 172       signature = vmSymbols::asPrimitive_int_signature();
 173       break;
 174 
 175     case T_LONG:
 176       args.push_long(values->long_at(i));
 177       signature = vmSymbols::asPrimitive_long_signature();
 178       break;
 179 
 180     case T_FLOAT:
 181       args.push_float(values->float_at(i));
 182       signature = vmSymbols::asPrimitive_float_signature();
 183       break;
 184 
 185     case T_DOUBLE:
 186       args.push_double(values->double_at(i));
 187       signature = vmSymbols::asPrimitive_double_signature();
 188       break;
 189 
 190     case T_BYTE:
 191       args.push_int(values->int_at(i));
 192       signature = vmSymbols::asPrimitive_byte_signature();
 193       break;
 194 
 195     case T_SHORT:
 196       args.push_int(values->int_at(i));
 197       signature = vmSymbols::asPrimitive_short_signature();
 198       break;
 199 
 200     case T_CHAR:
 201       args.push_int(values->int_at(i));
 202       signature = vmSymbols::asPrimitive_char_signature();
 203       break;
 204 
 205     case T_BOOLEAN:
 206       args.push_int(values->int_at(i));
 207       signature = vmSymbols::asPrimitive_boolean_signature();
 208       break;
 209 
 210     case T_OBJECT:
 211       return values->obj_at(i)();
 212 
 213     case T_CONFLICT:
 214       // put a non-null slot
 215       args.push_int(0);
 216       signature = vmSymbols::asPrimitive_int_signature();
 217       break;
 218 
 219     default: ShouldNotReachHere();
 220   }
 221   JavaCalls::call_static(&result,
 222                          ik,
 223                          vmSymbols::asPrimitive_name(),
 224                          signature,
 225                          &args,
 226                          CHECK_NULL);
 227   return (instanceOop) result.get_jobject();
 228 }
 229 
 230 static objArrayHandle values_to_object_array(StackValueCollection* values, TRAPS) {
 231   objArrayHandle empty;
 232   int length = values->size();
 233   objArrayOop array_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(),
 234                                                    length, CHECK_(empty));
 235   objArrayHandle array_h(THREAD, array_oop);
 236   for (int i = 0; i < values->size(); i++) {
 237     StackValue* st = values->at(i);
 238     oop obj = create_primitive_value_instance(values, i, CHECK_(empty));
 239     if (obj != NULL)
 240       array_h->obj_at_put(i, obj);
 241   }
 242   return array_h;
 243 }
 244 
 245 static objArrayHandle monitors_to_object_array(GrowableArray<MonitorInfo*>* monitors, TRAPS) {
 246   int length = monitors->length();
 247   objArrayOop array_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(),
 248                                                    length, CHECK_(objArrayHandle()));
 249   objArrayHandle array_h(THREAD, array_oop);
 250   for (int i = 0; i < length; i++) {
 251     MonitorInfo* monitor = monitors->at(i);
 252     array_h->obj_at_put(i, monitor->owner());
 253   }
 254   return array_h;
 255 }
 256 
 257 // Fill StackFrameInfo with declaringClass and bci and initialize memberName
 258 void StackWalk::fill_stackframe(Handle stackFrame, const methodHandle& method, int bci) {
 259   java_lang_StackFrameInfo::set_declaringClass(stackFrame(), method->method_holder()->java_mirror());
 260   java_lang_StackFrameInfo::set_method_and_bci(stackFrame(), method, bci);
 261 }
 262 
 263 // Fill LiveStackFrameInfo with locals, monitors, and expressions
 264 void StackWalk::fill_live_stackframe(Handle stackFrame, const methodHandle& method,
 265                                      int bci, javaVFrame* jvf, TRAPS) {
 266   fill_stackframe(stackFrame, method, bci);
 267   if (jvf != NULL) {
 268     StackValueCollection* locals = jvf->locals();
 269     StackValueCollection* expressions = jvf->expressions();
 270     GrowableArray<MonitorInfo*>* monitors = jvf->monitors();
 271 
 272     if (!locals->is_empty()) {
 273       objArrayHandle locals_h = values_to_object_array(locals, CHECK);
 274       java_lang_LiveStackFrameInfo::set_locals(stackFrame(), locals_h());
 275     }
 276     if (!expressions->is_empty()) {
 277       objArrayHandle expressions_h = values_to_object_array(expressions, CHECK);
 278       java_lang_LiveStackFrameInfo::set_operands(stackFrame(), expressions_h());
 279     }
 280     if (monitors->length() > 0) {
 281       objArrayHandle monitors_h = monitors_to_object_array(monitors, CHECK);
 282       java_lang_LiveStackFrameInfo::set_monitors(stackFrame(), monitors_h());
 283     }
 284   }
 285 }
 286 
 287 // Begins stack walking.
 288 //
 289 // Parameters:
 290 //   stackStream    StackStream object
 291 //   mode           Stack walking mode.
 292 //   skip_frames    Number of frames to be skipped.
 293 //   frame_count    Number of frames to be traversed.
 294 //   start_index    Start index to the user-supplied buffers.
 295 //   frames_array   Buffer to store StackFrame in, starting at start_index.
 296 //                  frames array is a Class<?>[] array when only getting caller
 297 //                  reference, and a StackFrameInfo[] array (or derivative)
 298 //                  otherwise. It should never be null.
 299 //
 300 // Returns Object returned from AbstractStackWalker::doStackWalk call.
 301 //
 302 oop StackWalk::walk(Handle stackStream, jlong mode,
 303                     int skip_frames, int frame_count, int start_index,
 304                     objArrayHandle frames_array,
 305                     TRAPS) {
 306   ResourceMark rm(THREAD);
 307   JavaThread* jt = (JavaThread*)THREAD;
 308   if (TraceStackWalk) {
 309     tty->print_cr("Start walking: mode " JLONG_FORMAT " skip %d frames batch size %d",
 310                   mode, skip_frames, frame_count);
 311   }
 312 
 313   if (frames_array.is_null()) {
 314     THROW_MSG_(vmSymbols::java_lang_NullPointerException(), "frames_array is NULL", NULL);
 315   }
 316 
 317   Klass* stackWalker_klass = SystemDictionary::StackWalker_klass();
 318   Klass* abstractStackWalker_klass = SystemDictionary::AbstractStackWalker_klass();
 319 
 320   methodHandle m_doStackWalk(THREAD, Universe::do_stack_walk_method());
 321 
 322   // Setup traversal onto my stack.
 323   RegisterMap regMap(jt, true);
 324   JavaFrameStream stream(jt, &regMap);
 325   {
 326     while (!stream.at_end()) {
 327       InstanceKlass* ik = stream.method()->method_holder();
 328       if (ik != stackWalker_klass &&
 329             ik != abstractStackWalker_klass && ik->super() != abstractStackWalker_klass)  {
 330         break;
 331       }
 332 
 333       if (TraceStackWalk) {
 334         tty->print("  skip "); stream.method()->print_short_name(); tty->print("\n");
 335       }
 336       stream.next();
 337     }
 338 
 339     // stack frame has been traversed individually and resume stack walk
 340     // from the stack frame at depth == skip_frames.
 341     for (int n=0; n < skip_frames && !stream.at_end(); stream.next(), n++) {
 342       if (TraceStackWalk) {
 343         tty->print("  skip "); stream.method()->print_short_name();
 344         tty->print_cr(" frame id: " PTR_FORMAT " pc: " PTR_FORMAT,
 345                       p2i(stream.java_frame()->fr().id()),
 346                       p2i(stream.java_frame()->fr().pc()));
 347       }
 348     }
 349   }
 350 
 351   int end_index = start_index;
 352   int numFrames = 0;
 353   if (!stream.at_end()) {
 354     numFrames = fill_in_frames(mode, stream, frame_count, start_index,
 355                                frames_array, end_index, CHECK_NULL);
 356     if (numFrames < 1) {
 357       THROW_MSG_(vmSymbols::java_lang_InternalError(), "stack walk: decode failed", NULL);
 358     }
 359   }
 360 
 361   // JVM_CallStackWalk walks the stack and fills in stack frames, then calls to
 362   // Java method java.lang.StackStreamFactory.AbstractStackWalker::doStackWalk
 363   // which calls the implementation to consume the stack frames.
 364   // When JVM_CallStackWalk returns, it invalidates the stack stream.
 365   JavaValue result(T_OBJECT);
 366   JavaCallArguments args(stackStream);
 367   args.push_long(stream.address_value());
 368   args.push_int(skip_frames);
 369   args.push_int(frame_count);
 370   args.push_int(start_index);
 371   args.push_int(end_index);
 372 
 373   // Link the thread and vframe stream into the callee-visible object
 374   stream.setup_magic_on_entry(frames_array);
 375 
 376   JavaCalls::call(&result, m_doStackWalk, &args, THREAD);
 377 
 378   // Do this before anything else happens, to disable any lingering stream objects
 379   bool ok = stream.cleanup_magic_on_exit(frames_array);
 380 
 381   // Throw pending exception if we must
 382   (void) (CHECK_NULL);
 383 
 384   if (!ok) {
 385     THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: corrupted buffers on exit", NULL);
 386   }
 387 
 388   // Return normally
 389   return (oop)result.get_jobject();
 390 }
 391 
 392 // Walk the next batch of stack frames
 393 //
 394 // Parameters:
 395 //   stackStream    StackStream object
 396 //   mode           Stack walking mode.
 397 //   magic          Must be valid value to continue the stack walk
 398 //   frame_count    Number of frames to be decoded.
 399 //   start_index    Start index to the user-supplied buffers.
 400 //   frames_array   Buffer to store StackFrame in, starting at start_index.
 401 //
 402 // Returns the end index of frame filled in the buffer.
 403 //
 404 jint StackWalk::moreFrames(Handle stackStream, jlong mode, jlong magic,
 405                            int frame_count, int start_index,
 406                            objArrayHandle frames_array,
 407                            TRAPS)
 408 {
 409   JavaThread* jt = (JavaThread*)THREAD;
 410   JavaFrameStream* existing_stream = JavaFrameStream::from_current(jt, magic, frames_array);
 411   if (existing_stream == NULL) {
 412     THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: corrupted buffers", 0L);
 413   }
 414 
 415   if (frames_array.is_null()) {
 416     THROW_MSG_(vmSymbols::java_lang_NullPointerException(), "frames_array is NULL", 0L);
 417   }
 418 
 419   if (TraceStackWalk) {
 420     tty->print_cr("StackWalk::moreFrames frame_count %d existing_stream " PTR_FORMAT " start %d frames %d",
 421                   frame_count, p2i(existing_stream), start_index, frames_array->length());
 422   }
 423   int end_index = start_index;
 424   if (frame_count <= 0) {
 425     return end_index;        // No operation.
 426   }
 427 
 428   int count = frame_count + start_index;
 429   assert (frames_array->length() >= count, "not enough space in buffers");
 430 
 431   JavaFrameStream& stream = (*existing_stream);
 432   if (!stream.at_end()) {
 433     stream.next(); // advance past the last frame decoded in previous batch
 434     if (!stream.at_end()) {
 435       int n = fill_in_frames(mode, stream, frame_count, start_index,
 436                              frames_array, end_index, CHECK_0);
 437       if (n < 1) {
 438         THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: later decode failed", 0L);
 439       }
 440       return end_index;
 441     }
 442   }
 443   return end_index;
 444 }