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