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