--- old/hotspot/make/share/makefiles/mapfile-vers 2015-11-09 17:14:47.000000000 -0800 +++ new/hotspot/make/share/makefiles/mapfile-vers 2015-11-09 17:14:47.000000000 -0800 @@ -7,6 +7,7 @@ JVM_ActiveProcessorCount; JVM_ArrayCopy; JVM_AssertionStatusDirectives; + JVM_CallStackWalk; JVM_ClassDepth; JVM_ClassLoaderDepth; JVM_Clone; @@ -37,6 +38,7 @@ JVM_DumpAllStacks; JVM_DumpThreads; JVM_FillInStackTrace; + JVM_FillStackFrames; JVM_FindClassFromCaller; JVM_FindClassFromClass; JVM_FindClassFromBootLoader; @@ -134,6 +136,7 @@ JVM_MonitorNotify; JVM_MonitorNotifyAll; JVM_MonitorWait; + JVM_MoreStackWalk; JVM_NanoTime; JVM_NativePath; JVM_NewArray; @@ -151,6 +154,7 @@ JVM_SetClassSigners; JVM_SetNativeThreadName; JVM_SetPrimitiveArrayElement; + JVM_SetMethodInfo; JVM_SetThreadPriority; JVM_Sleep; JVM_StartThread; --- old/hotspot/src/share/vm/classfile/javaClasses.cpp 2015-11-09 17:14:47.000000000 -0800 +++ new/hotspot/src/share/vm/classfile/javaClasses.cpp 2015-11-09 17:14:47.000000000 -0800 @@ -1315,43 +1315,11 @@ // After this many redefines, the stack trace is unreliable. const int MAX_VERSION = USHRT_MAX; -// Helper backtrace functions to store bci|version together. -static inline int merge_bci_and_version(int bci, int version) { - // only store u2 for version, checking for overflow. - if (version > USHRT_MAX || version < 0) version = MAX_VERSION; - assert((jushort)bci == bci, "bci should be short"); - return build_int_from_shorts(version, bci); -} - -static inline int bci_at(unsigned int merged) { - return extract_high_short_from_int(merged); -} -static inline int version_at(unsigned int merged) { - return extract_low_short_from_int(merged); -} - static inline bool version_matches(Method* method, int version) { assert(version < MAX_VERSION, "version is too big"); return method != NULL && (method->constants()->version() == version); } -static inline int get_line_number(Method* method, int bci) { - int line_number = 0; - if (method->is_native()) { - // Negative value different from -1 below, enabling Java code in - // class java.lang.StackTraceElement to distinguish "native" from - // "no LineNumberTable". JDK tests for -2. - line_number = -2; - } else { - // Returns -1 if no LineNumberTable, and otherwise actual line number - line_number = method->line_number_from_bci(bci); - if (line_number == -1 && ShowHiddenFrames) { - line_number = bci + 1000000; - } - } - return line_number; -} - // This class provides a simple wrapper over the internal structure of // exception backtrace to insulate users of the backtrace from needing // to know what it looks like. @@ -1473,7 +1441,7 @@ } _methods->short_at_put(_index, method->orig_method_idnum()); - _bcis->int_at_put(_index, merge_bci_and_version(bci, method->constants()->version())); + _bcis->int_at_put(_index, BackTrace::merge_bci_and_version(bci, method->constants()->version())); _cprefs->short_at_put(_index, method->name_index()); // We need to save the mirrors in the backtrace to keep the class @@ -1485,19 +1453,6 @@ }; -Symbol* get_source_file_name(InstanceKlass* holder, int version) { - // Find the specific ik version that contains this source_file_name_index - // via the previous versions list, but use the current version's - // constant pool to look it up. The previous version's index has been - // merged for the current constant pool. - InstanceKlass* ik = holder->get_klass_version(version); - // This version has been cleaned up. - if (ik == NULL) return NULL; - int source_file_name_index = ik->source_file_name_index(); - return (source_file_name_index == 0) ? - (Symbol*)NULL : holder->constants()->symbol_at(source_file_name_index); -} - // Print stack trace element to resource allocated buffer char* java_lang_Throwable::print_stack_element_to_buffer(Handle mirror, int method_id, int version, int bci, int cpref) { @@ -1515,7 +1470,7 @@ buf_len += (int)strlen(method_name); char* source_file_name = NULL; - Symbol* source = get_source_file_name(holder, version); + Symbol* source = BackTrace::get_source_file_name(holder, version); if (source != NULL) { source_file_name = source->as_C_string(); buf_len += (int)strlen(source_file_name); @@ -1530,7 +1485,7 @@ if (!version_matches(method, version)) { strcat(buf, "(Redefined)"); } else { - int line_number = get_line_number(method, bci); + int line_number = BackTrace::get_line_number(method, bci); if (line_number == -2) { strcat(buf, "(Native Method)"); } else { @@ -1599,8 +1554,8 @@ // NULL mirror means end of stack trace if (mirror.is_null()) goto handle_cause; int method = methods->short_at(index); - int version = version_at(bcis->int_at(index)); - int bci = bci_at(bcis->int_at(index)); + int version = BackTrace::version_at(bcis->int_at(index)); + int bci = BackTrace::bci_at(bcis->int_at(index)); int cpref = cprefs->short_at(index); print_stack_element(st, mirror, method, version, bci, cpref); } @@ -1887,8 +1842,8 @@ assert(methods != NULL && bcis != NULL && mirrors != NULL, "sanity check"); int method = methods->short_at(chunk_index); - int version = version_at(bcis->int_at(chunk_index)); - int bci = bci_at(bcis->int_at(chunk_index)); + int version = BackTrace::version_at(bcis->int_at(chunk_index)); + int bci = BackTrace::bci_at(bcis->int_at(chunk_index)); int cpref = cprefs->short_at(chunk_index); Handle mirror(THREAD, mirrors->obj_at(chunk_index)); @@ -1911,11 +1866,18 @@ } Handle element = ik->allocate_instance_handle(CHECK_0); + java_lang_StackTraceElement::init(element, mirror, method_id, version, bci, cpref, CHECK_0); + return element(); +} + +void java_lang_StackTraceElement::init(Handle element, Handle mirror, int method_id, + int version, int bci, int cpref, TRAPS) { + // Fill in class name ResourceMark rm(THREAD); InstanceKlass* holder = InstanceKlass::cast(java_lang_Class::as_Klass(mirror())); const char* str = holder->external_name(); - oop classname = StringTable::intern((char*) str, CHECK_0); + oop classname = StringTable::intern((char*) str, CHECK); java_lang_StackTraceElement::set_declaringClass(element(), classname); Method* method = holder->method_with_orig_idnum(method_id, version); @@ -1924,7 +1886,7 @@ Symbol* sym = (method != NULL) ? method->name() : holder->constants()->symbol_at(cpref); // Fill in method name - oop methodname = StringTable::intern(sym, CHECK_0); + oop methodname = StringTable::intern(sym, CHECK); java_lang_StackTraceElement::set_methodName(element(), methodname); if (!version_matches(method, version)) { @@ -1933,16 +1895,15 @@ java_lang_StackTraceElement::set_lineNumber(element(), -1); } else { // Fill in source file name and line number. - Symbol* source = get_source_file_name(holder, version); + Symbol* source = BackTrace::get_source_file_name(holder, version); if (ShowHiddenFrames && source == NULL) source = vmSymbols::unknown_class_name(); - oop filename = StringTable::intern(source, CHECK_0); + oop filename = StringTable::intern(source, CHECK); java_lang_StackTraceElement::set_fileName(element(), filename); - int line_number = get_line_number(method, bci); + int line_number = BackTrace::get_line_number(method, bci); java_lang_StackTraceElement::set_lineNumber(element(), line_number); } - return element(); } oop java_lang_StackTraceElement::create(methodHandle method, int bci, TRAPS) { @@ -1952,6 +1913,105 @@ return create(mirror, method_id, method->constants()->version(), bci, cpref, THREAD); } +int java_lang_StackFrameInfo::bci(oop stackFrame) { + int value = stackFrame->int_field(bci_offset); + if (MemberNameInStackFrame) { + return value; + } else { + return BackTrace::bci_at(value); + } +} + +oop java_lang_StackFrameInfo::member_name(oop stackFrame) { + return stackFrame->obj_field(memberName_offset); +} + +Method* java_lang_StackFrameInfo::get_method(Handle stackFrame, InstanceKlass* holder, TRAPS) { + if (MemberNameInStackFrame) { + Handle mname(THREAD, stackFrame->obj_field(memberName_offset)); + Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mname()); + // we should expand MemberName::name when Throwable uses StackTrace + // MethodHandles::expand_MemberName(mname, MethodHandles::_suppress_defc|MethodHandles::_suppress_type, CHECK_NULL); + return method; + } else { + int bci_version = stackFrame->int_field(bci_offset); + int version = BackTrace::version_at(bci_version); + int mid_cpref = stackFrame->int_field(mid_offset); + int mid = BackTrace::mid_at(mid_cpref); + int cpref = BackTrace::cpref_at(mid_cpref); + return holder->method_with_orig_idnum(mid, version); + } +} + +Symbol* java_lang_StackFrameInfo::get_file_name(Handle stackFrame, InstanceKlass* holder) { + if (MemberNameInStackFrame) { + return holder->source_file_name(); + } else { + int bci_version = stackFrame->int_field(bci_offset); + int version = BackTrace::version_at(bci_version); + Symbol* source = BackTrace::get_source_file_name(holder, version); + if (source == NULL) { + source = vmSymbols::unknown_class_name(); + } + return source; + } +} + +void java_lang_StackFrameInfo::fill_methodInfo(Handle stackFrame, TRAPS) { + ResourceMark rm(THREAD); + oop k = stackFrame->obj_field(declaringClass_offset); + InstanceKlass* holder = InstanceKlass::cast(java_lang_Class::as_Klass(k)); + Method* method = java_lang_StackFrameInfo::get_method(stackFrame, holder, CHECK); + int bci = java_lang_StackFrameInfo::bci(stackFrame()); + + // The method can be NULL if the requested class version is gone + Symbol* sym = (method != NULL) ? method->name() : NULL; + if (MemberNameInStackFrame) { + assert(sym != NULL, "MemberName must have method name"); + } else { + bci = BackTrace::bci_at(bci); // merged with version + // The method can be NULL if the requested class version is gone + if (sym == NULL) { + int mid_cpref = stackFrame->int_field(mid_offset); + int cpref = BackTrace::cpref_at(mid_cpref); + sym = holder->constants()->symbol_at(cpref); + } + } + + // set method name + oop methodname = StringTable::intern(sym, CHECK); + java_lang_StackFrameInfo::set_methodName(stackFrame(), methodname); + + // set file name and line number + Symbol* source = get_file_name(stackFrame, holder); + if (source != NULL) { + oop filename = StringTable::intern(source, CHECK); + java_lang_StackFrameInfo::set_fileName(stackFrame(), filename); + } + if (method != NULL) { + int line_number = BackTrace::get_line_number(method, bci); + java_lang_StackFrameInfo::set_lineNumber(stackFrame(), line_number); + } +} + +void java_lang_StackFrameInfo::compute_offsets() { + Klass* k = SystemDictionary::StackFrameInfo_klass(); + compute_offset(declaringClass_offset, k, vmSymbols::declaringClass_name(), vmSymbols::class_signature()); + compute_offset(memberName_offset, k, vmSymbols::memberName_name(), vmSymbols::object_signature()); + compute_offset(mid_offset, k, vmSymbols::mid_name(), vmSymbols::int_signature()); + compute_offset(bci_offset, k, vmSymbols::bci_name(), vmSymbols::int_signature()); + compute_offset(methodName_offset, k, vmSymbols::methodName_name(), vmSymbols::string_signature()); + compute_offset(fileName_offset, k, vmSymbols::fileName_name(), vmSymbols::string_signature()); + compute_offset(lineNumber_offset, k, vmSymbols::lineNumber_name(), vmSymbols::int_signature()); +} + +void java_lang_LiveStackFrameInfo::compute_offsets() { + Klass* k = SystemDictionary::LiveStackFrameInfo_klass(); + compute_offset(monitors_offset, k, vmSymbols::monitors_name(), vmSymbols::object_array_signature()); + compute_offset(locals_offset, k, vmSymbols::locals_name(), vmSymbols::object_array_signature()); + compute_offset(operands_offset, k, vmSymbols::operands_name(), vmSymbols::object_array_signature()); +} + void java_lang_reflect_AccessibleObject::compute_offsets() { Klass* k = SystemDictionary::reflect_AccessibleObject_klass(); compute_offset(override_offset, k, vmSymbols::override_name(), vmSymbols::bool_signature()); @@ -3268,6 +3328,16 @@ int java_lang_StackTraceElement::methodName_offset; int java_lang_StackTraceElement::fileName_offset; int java_lang_StackTraceElement::lineNumber_offset; +int java_lang_StackFrameInfo::declaringClass_offset; +int java_lang_StackFrameInfo::memberName_offset; +int java_lang_StackFrameInfo::mid_offset; +int java_lang_StackFrameInfo::bci_offset; +int java_lang_StackFrameInfo::methodName_offset; +int java_lang_StackFrameInfo::fileName_offset; +int java_lang_StackFrameInfo::lineNumber_offset; +int java_lang_LiveStackFrameInfo::monitors_offset; +int java_lang_LiveStackFrameInfo::locals_offset; +int java_lang_LiveStackFrameInfo::operands_offset; int java_lang_AssertionStatusDirectives::classes_offset; int java_lang_AssertionStatusDirectives::classEnabled_offset; int java_lang_AssertionStatusDirectives::packages_offset; @@ -3297,6 +3367,41 @@ element->int_field_put(lineNumber_offset, value); } +// Support for java_lang_StackFrameInfo +void java_lang_StackFrameInfo::set_declaringClass(oop element, oop value) { + element->obj_field_put(declaringClass_offset, value); +} + +void java_lang_StackFrameInfo::set_mid(oop element, int value) { + element->int_field_put(mid_offset, value); +} +void java_lang_StackFrameInfo::set_bci(oop element, int value) { + element->int_field_put(bci_offset, value); +} + +void java_lang_StackFrameInfo::set_fileName(oop element, oop value) { + element->obj_field_put(fileName_offset, value); +} + +void java_lang_StackFrameInfo::set_methodName(oop element, oop value) { + element->obj_field_put(methodName_offset, value); +} + +void java_lang_StackFrameInfo::set_lineNumber(oop element, int value) { + element->int_field_put(lineNumber_offset, value); +} + +void java_lang_LiveStackFrameInfo::set_monitors(oop element, oop value) { + element->obj_field_put(monitors_offset, value); +} + +void java_lang_LiveStackFrameInfo::set_locals(oop element, oop value) { + element->obj_field_put(locals_offset, value); +} + +void java_lang_LiveStackFrameInfo::set_operands(oop element, oop value) { + element->obj_field_put(operands_offset, value); +} // Support for java Assertions - java_lang_AssertionStatusDirectives. @@ -3430,6 +3535,8 @@ sun_reflect_ConstantPool::compute_offsets(); sun_reflect_UnsafeStaticFieldAccessorImpl::compute_offsets(); java_lang_reflect_Parameter::compute_offsets(); + java_lang_StackFrameInfo::compute_offsets(); + java_lang_LiveStackFrameInfo::compute_offsets(); // generated interpreter code wants to know about the offsets we just computed: AbstractAssembler::update_delayed_values(); --- old/hotspot/src/share/vm/classfile/javaClasses.hpp 2015-11-09 17:14:48.000000000 -0800 +++ new/hotspot/src/share/vm/classfile/javaClasses.hpp 2015-11-09 17:14:48.000000000 -0800 @@ -1348,11 +1348,93 @@ // Create an instance of StackTraceElement static oop create(Handle mirror, int method, int version, int bci, int cpref, TRAPS); static oop create(methodHandle method, int bci, TRAPS); + static void init(Handle element, Handle mirror, int method, int version, int bci, int cpref, TRAPS); + + + // Debugging + friend class JavaClasses; +}; + + +class BackTrace: AllStatic { + public: + // Helper backtrace functions to store bci|version together. + static int merge_bci_and_version(int bci, int version); + + static int merge_mid_and_cpref(int mid, int cpref); + + static int bci_at(unsigned int merged); + + static int version_at(unsigned int merged); + + static int mid_at(unsigned int merged); + + static int cpref_at(unsigned int merged); + + static int get_line_number(methodHandle method, int bci); + + static Symbol* get_source_file_name(InstanceKlass* holder, int version); + + // Debugging + friend class JavaClasses; +}; + +// Interface to java.lang.StackFrameInfo objects + +class java_lang_StackFrameInfo: AllStatic { +private: + static int declaringClass_offset; + static int memberName_offset; + static int mid_offset; + static int bci_offset; + + static int methodName_offset; + static int fileName_offset; + static int lineNumber_offset; + + static Method* get_method(Handle stackFrame, InstanceKlass* holder, TRAPS); + static Symbol* get_file_name(Handle stackFrame, InstanceKlass* holder); + +public: + // Setters + static void set_declaringClass(oop info, oop value); + static void set_methodName(oop info, oop value); + static void set_fileName(oop info, oop value); + static void set_lineNumber(oop info, int value); + + static void set_mid(oop info, int value); + static void set_bci(oop info, int value); + + static void compute_offsets(); + + static int bci(oop info); + static oop member_name(oop info); + + // set method info in an instance of StackFrameInfo + static void fill_methodInfo(Handle info, TRAPS); // Debugging friend class JavaClasses; }; +class java_lang_LiveStackFrameInfo: AllStatic { + private: + + static int monitors_offset; + static int locals_offset; + static int operands_offset; + + public: + + static void set_monitors(oop info, oop value); + static void set_locals(oop info, oop value); + static void set_operands(oop info, oop value); + + static void compute_offsets(); + + // Debugging + friend class JavaClasses; +}; // Interface to java.lang.AssertionStatusDirectives objects --- old/hotspot/src/share/vm/classfile/javaClasses.inline.hpp 2015-11-09 17:14:48.000000000 -0800 +++ new/hotspot/src/share/vm/classfile/javaClasses.inline.hpp 2015-11-09 17:14:48.000000000 -0800 @@ -73,4 +73,68 @@ return obj != NULL && is_subclass(obj->klass()); } +inline int BackTrace::merge_bci_and_version(int bci, int version) { + // only store u2 for version, checking for overflow. + if (version > USHRT_MAX || version < 0) version = USHRT_MAX; + assert((jushort)bci == bci, "bci should be short"); + return build_int_from_shorts(version, bci); +} + +inline int BackTrace::merge_mid_and_cpref(int mid, int cpref) { + // only store u2 for mid and cpref, checking for overflow. + assert((jushort)mid == mid, "mid should be short"); + assert((jushort)cpref == cpref, "cpref should be short"); + return build_int_from_shorts(cpref, mid); +} + +inline int BackTrace::bci_at(unsigned int merged) { + return extract_high_short_from_int(merged); +} + +inline int BackTrace::version_at(unsigned int merged) { + return extract_low_short_from_int(merged); +} + +inline int BackTrace::mid_at(unsigned int merged) { + return extract_high_short_from_int(merged); +} + +inline int BackTrace::cpref_at(unsigned int merged) { + return extract_low_short_from_int(merged); +} + +inline int BackTrace::get_line_number(methodHandle method, int bci) { + int line_number = 0; + if (method->is_native()) { + // Negative value different from -1 below, enabling Java code in + // class java.lang.StackTraceElement to distinguish "native" from + // "no LineNumberTable". JDK tests for -2. + line_number = -2; + } else { + // Returns -1 if no LineNumberTable, and otherwise actual line number + line_number = method->line_number_from_bci(bci); + if (line_number == -1 && ShowHiddenFrames) { + line_number = bci + 1000000; + } + } + return line_number; +} + +/* + * Returns the source file name of a given InstanceKlass and version + */ +inline Symbol* BackTrace::get_source_file_name(InstanceKlass* holder, int version) { + // Find the specific ik version that contains this source_file_name_index + // via the previous versions list, but use the current version's + // constant pool to look it up. The previous version's index has been + // merged for the current constant pool. + InstanceKlass* ik = holder->get_klass_version(version); + if (ik != NULL) { + return ik->source_file_name(); + } + + // This version has been cleaned up. + return NULL; +} + #endif // SHARE_VM_CLASSFILE_JAVACLASSES_INLINE_HPP --- old/hotspot/src/share/vm/classfile/systemDictionary.hpp 2015-11-09 17:14:49.000000000 -0800 +++ new/hotspot/src/share/vm/classfile/systemDictionary.hpp 2015-11-09 17:14:48.000000000 -0800 @@ -179,11 +179,15 @@ do_klass(sun_misc_Launcher_klass, sun_misc_Launcher, Pre ) \ do_klass(CodeSource_klass, java_security_CodeSource, Pre ) \ \ - /* It's NULL in non-1.4 JDKs. */ \ do_klass(StackTraceElement_klass, java_lang_StackTraceElement, Opt ) \ + \ /* It's okay if this turns out to be NULL in non-1.4 JDKs. */ \ do_klass(nio_Buffer_klass, java_nio_Buffer, Opt ) \ \ + /* Stack Walking */ \ + do_klass(StackFrameInfo_klass, java_lang_StackFrameInfo, Opt ) \ + do_klass(LiveStackFrameInfo_klass, java_lang_LiveStackFrameInfo, Opt ) \ + \ /* Preload boxing klasses */ \ do_klass(Boolean_klass, java_lang_Boolean, Pre ) \ do_klass(Character_klass, java_lang_Character, Pre ) \ --- old/hotspot/src/share/vm/classfile/vmSymbols.hpp 2015-11-09 17:14:49.000000000 -0800 +++ new/hotspot/src/share/vm/classfile/vmSymbols.hpp 2015-11-09 17:14:49.000000000 -0800 @@ -308,6 +308,22 @@ /* Support for JVMCI */ \ JVMCI_VM_SYMBOLS_DO(template, do_alias) \ \ + template(java_lang_StackWalker, "java/lang/StackWalker") \ + template(java_lang_StackFrameInfo, "java/lang/StackFrameInfo") \ + template(java_lang_LiveStackFrameInfo, "java/lang/LiveStackFrameInfo") \ + template(java_lang_StackStreamFactory_AbstractStackWalker, "java/lang/StackStreamFactory$AbstractStackWalker") \ + template(doStackWalk_name, "doStackWalk") \ + template(doStackWalk_signature, "(JIIII)Ljava/lang/Object;") \ + template(asPrimitive_name, "asPrimitive") \ + template(asPrimitive_int_signature, "(I)Ljava/lang/LiveStackFrame$PrimitiveValue;") \ + template(asPrimitive_long_signature, "(J)Ljava/lang/LiveStackFrame$PrimitiveValue;") \ + template(asPrimitive_short_signature, "(S)Ljava/lang/LiveStackFrame$PrimitiveValue;") \ + template(asPrimitive_byte_signature, "(B)Ljava/lang/LiveStackFrame$PrimitiveValue;") \ + template(asPrimitive_char_signature, "(C)Ljava/lang/LiveStackFrame$PrimitiveValue;") \ + template(asPrimitive_float_signature, "(F)Ljava/lang/LiveStackFrame$PrimitiveValue;") \ + template(asPrimitive_double_signature, "(D)Ljava/lang/LiveStackFrame$PrimitiveValue;") \ + template(asPrimitive_boolean_signature, "(Z)Ljava/lang/LiveStackFrame$PrimitiveValue;") \ + \ /* common method and field names */ \ template(object_initializer_name, "") \ template(class_initializer_name, "") \ @@ -408,6 +424,16 @@ template(append_name, "append") \ template(klass_name, "klass") \ template(array_klass_name, "array_klass") \ + template(declaringClass_name, "declaringClass") \ + template(memberName_name, "memberName") \ + template(mid_name, "mid") \ + template(bci_name, "bci") \ + template(methodName_name, "methodName") \ + template(fileName_name, "fileName") \ + template(lineNumber_name, "lineNumber") \ + template(monitors_name, "monitors") \ + template(locals_name, "locals") \ + template(operands_name, "operands") \ template(oop_size_name, "oop_size") \ template(static_oop_field_count_name, "static_oop_field_count") \ template(protection_domain_name, "protection_domain") \ @@ -512,6 +538,7 @@ template(class_array_signature, "[Ljava/lang/Class;") \ template(classloader_signature, "Ljava/lang/ClassLoader;") \ template(object_signature, "Ljava/lang/Object;") \ + template(object_array_signature, "[Ljava/lang/Object;") \ template(class_signature, "Ljava/lang/Class;") \ template(string_signature, "Ljava/lang/String;") \ template(reference_signature, "Ljava/lang/ref/Reference;") \ --- old/hotspot/src/share/vm/prims/jvm.cpp 2015-11-09 17:14:50.000000000 -0800 +++ new/hotspot/src/share/vm/prims/jvm.cpp 2015-11-09 17:14:49.000000000 -0800 @@ -46,6 +46,7 @@ #include "prims/jvmtiThreadState.hpp" #include "prims/nativeLookup.hpp" #include "prims/privilegedStack.hpp" +#include "prims/stackwalk.hpp" #include "runtime/arguments.hpp" #include "runtime/atomic.inline.hpp" #include "runtime/handles.inline.hpp" @@ -547,6 +548,94 @@ JVM_END +// java.lang.StackWalker ////////////////////////////////////////////////////// + + +JVM_ENTRY(jobject, JVM_CallStackWalk(JNIEnv *env, jobject stackStream, jlong mode, + jint skip_frames, jint frame_count, jint start_index, + jobjectArray classes, + jobjectArray frames)) + JVMWrapper("JVM_CallStackWalk"); + JavaThread* jt = (JavaThread*) THREAD; + if (!jt->is_Java_thread() || !jt->has_last_Java_frame()) { + THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: no stack trace", NULL); + } + + Handle stackStream_h(THREAD, JNIHandles::resolve_non_null(stackStream)); + objArrayOop ca = objArrayOop(JNIHandles::resolve_non_null(classes)); + objArrayHandle classes_array_h(THREAD, ca); + + // frames array is null when only getting caller reference + objArrayOop fa = objArrayOop(JNIHandles::resolve(frames)); + objArrayHandle frames_array_h(THREAD, fa); + + int limit = start_index+frame_count; + if (classes_array_h->length() < limit) { + THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), "not enough space in buffers", NULL); + } + + Handle result = StackWalk::walk(stackStream_h, mode, skip_frames, frame_count, + start_index, classes_array_h, + frames_array_h, CHECK_NULL); + return JNIHandles::make_local(env, result()); +JVM_END + + +JVM_ENTRY(jint, JVM_MoreStackWalk(JNIEnv *env, jobject stackStream, jlong mode, jlong anchor, + jint frame_count, jint start_index, + jobjectArray classes, + jobjectArray frames)) + JVMWrapper("JVM_MoreStackWalk"); + JavaThread* jt = (JavaThread*) THREAD; + objArrayOop ca = objArrayOop(JNIHandles::resolve_non_null(classes)); + objArrayHandle classes_array_h(THREAD, ca); + + // frames array is null when only getting caller reference + objArrayOop fa = objArrayOop(JNIHandles::resolve(frames)); + objArrayHandle frames_array_h(THREAD, fa); + + int limit = start_index+frame_count; + if (classes_array_h->length() < limit) { + THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "not enough space in buffers"); + } + + Handle stackStream_h(THREAD, JNIHandles::resolve_non_null(stackStream)); + return StackWalk::moreFrames(stackStream_h, mode, anchor, frame_count, + start_index, classes_array_h, + frames_array_h, CHECK_0); +JVM_END + +JVM_ENTRY(void, JVM_FillStackFrames(JNIEnv *env, jclass stackStream, + jint start_index, + jobjectArray frames, + jint from_index, jint to_index)) + JVMWrapper("JVM_FillStackFrames"); + if (TraceStackWalk) { + tty->print("JVM_FillStackFrames() start_index=%d from_index=%d to_index=%d\n", + start_index, from_index, to_index); + } + + JavaThread* jt = (JavaThread*) THREAD; + + objArrayOop fa = objArrayOop(JNIHandles::resolve_non_null(frames)); + objArrayHandle frames_array_h(THREAD, fa); + + if (frames_array_h->length() < to_index) { + THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "array length not matched"); + } + + for (int i=from_index; i < to_index; i++) { + Handle stackFrame(THREAD, frames_array_h->obj_at(i)); + java_lang_StackFrameInfo::fill_methodInfo(stackFrame, CHECK); + } +JVM_END + +JVM_ENTRY(void, JVM_SetMethodInfo(JNIEnv *env, jobject frame)) + JVMWrapper("JVM_SetMethodInfo"); + Handle stackFrame(THREAD, JNIHandles::resolve(frame)); + java_lang_StackFrameInfo::fill_methodInfo(stackFrame, CHECK); +JVM_END + // java.lang.Object /////////////////////////////////////////////// --- old/hotspot/src/share/vm/prims/jvm.h 2015-11-09 17:14:50.000000000 -0800 +++ new/hotspot/src/share/vm/prims/jvm.h 2015-11-09 17:14:50.000000000 -0800 @@ -201,6 +201,30 @@ JVM_GetStackTraceElement(JNIEnv *env, jobject throwable, jint index); /* + * java.lang.StackWalker + */ +JNIEXPORT jobject JNICALL +JVM_CallStackWalk(JNIEnv *env, jobject stackStream, jlong mode, + jint skip_frames, jint frame_count, jint start_index, + jobjectArray classes, + jobjectArray frames); + +JNIEXPORT jint JNICALL +JVM_MoreStackWalk(JNIEnv *env, jobject stackStream, jlong mode, jlong anchor, + jint frame_count, jint start_index, + jobjectArray classes, + jobjectArray frames); + +JNIEXPORT void JNICALL +JVM_FillStackFrames(JNIEnv* env, jclass cls, + int start_index, + jobjectArray frames, + jint from_index, jint toIndex); + +JNIEXPORT void JNICALL +JVM_SetMethodInfo(JNIEnv* env, jobject frame); + +/* * java.lang.Thread */ JNIEXPORT void JNICALL --- old/hotspot/src/share/vm/runtime/globals.hpp 2015-11-09 17:14:51.000000000 -0800 +++ new/hotspot/src/share/vm/runtime/globals.hpp 2015-11-09 17:14:51.000000000 -0800 @@ -3123,6 +3123,12 @@ "exceptions (0 means all)") \ range(0, max_jint/2) \ \ + product(bool, TraceStackWalk, false, \ + "Trace stack walking") \ + \ + product(bool, MemberNameInStackFrame, true, \ + "Use MemberName in StackFrame") \ + \ /* notice: the max range value here is max_jint, not max_intx */ \ /* because of overflow issue */ \ NOT_EMBEDDED(diagnostic(intx, GuaranteedSafepointInterval, 1000, \ --- old/hotspot/src/share/vm/runtime/vframe.hpp 2015-11-09 17:14:51.000000000 -0800 +++ new/hotspot/src/share/vm/runtime/vframe.hpp 2015-11-09 17:14:51.000000000 -0800 @@ -317,10 +317,18 @@ intptr_t* frame_id() const { return _frame.id(); } address frame_pc() const { return _frame.pc(); } + javaVFrame* java_frame() { + vframe* vf = vframe::new_vframe(&_frame, &_reg_map, _thread); + if (vf->is_java_frame()) { + return (javaVFrame*)vf; + } + return NULL; + } + CodeBlob* cb() const { return _frame.cb(); } nmethod* nm() const { - assert( cb() != NULL && cb()->is_nmethod(), "usage"); - return (nmethod*) cb(); + assert( cb() != NULL && cb()->is_nmethod(), "usage"); + return (nmethod*) cb(); } // Frame type --- old/jdk/make/mapfiles/libjava/mapfile-vers 2015-11-09 17:14:52.000000000 -0800 +++ new/jdk/make/mapfiles/libjava/mapfile-vers 2015-11-09 17:14:52.000000000 -0800 @@ -138,9 +138,13 @@ Java_java_lang_Double_longBitsToDouble; Java_java_lang_Double_doubleToRawLongBits; Java_java_lang_reflect_Proxy_defineClass0; - Java_java_lang_Shutdown_runAllFinalizers; Java_java_lang_Float_intBitsToFloat; Java_java_lang_Float_floatToRawIntBits; + Java_java_lang_StackFrameInfo_fillInStackFrames; + Java_java_lang_StackFrameInfo_setMethodInfo; + Java_java_lang_StackStreamFactory_00024AbstractStackWalker_callStackWalk; + Java_java_lang_StackStreamFactory_00024AbstractStackWalker_fetchStackFrames; + Java_java_lang_Shutdown_runAllFinalizers; Java_java_lang_StrictMath_IEEEremainder; Java_java_lang_StrictMath_acos; Java_java_lang_StrictMath_asin; --- old/jdk/src/java.base/share/classes/java/lang/System.java 2015-11-09 17:14:52.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/System.java 2015-11-09 17:14:52.000000000 -0800 @@ -28,13 +28,13 @@ import java.lang.reflect.Executable; import java.lang.annotation.Annotation; import java.security.AccessControlContext; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.security.ProtectionDomain; import java.util.Properties; import java.util.PropertyPermission; import java.util.StringTokenizer; import java.util.Map; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.AllPermission; import java.nio.channels.Channel; import java.nio.channels.spi.SelectorProvider; import sun.nio.ch.Interruptible; @@ -1250,12 +1250,6 @@ public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) { Shutdown.add(slot, registerShutdownInProgress, hook); } - public int getStackTraceDepth(Throwable t) { - return t.getStackTraceDepth(); - } - public StackTraceElement getStackTraceElement(Throwable t, int i) { - return t.getStackTraceElement(i); - } public String newStringUnsafe(char[] chars) { return new String(chars, true); } --- old/jdk/src/java.base/share/classes/java/lang/Thread.java 2015-11-09 17:14:53.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/Thread.java 2015-11-09 17:14:53.000000000 -0800 @@ -1329,11 +1329,9 @@ /** * Prints a stack trace of the current thread to the standard error stream. * This method is used only for debugging. - * - * @see Throwable#printStackTrace() */ public static void dumpStack() { - new Exception("Stack trace").printStackTrace(); + StackStreamFactory.makeStackTrace().printStackTrace(System.err); } /** @@ -1556,7 +1554,7 @@ return stackTrace; } else { // Don't need JVM help for current thread - return (new Exception()).getStackTrace(); + return StackStreamFactory.makeStackTrace().getStackTraceElements(); } } --- old/jdk/src/java.base/share/classes/java/lang/Throwable.java 2015-11-09 17:14:53.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/Throwable.java 2015-11-09 17:14:53.000000000 -0800 @@ -24,6 +24,8 @@ */ package java.lang; +import sun.misc.VM; + import java.io.*; import java.util.*; @@ -778,7 +780,11 @@ public synchronized Throwable fillInStackTrace() { if (stackTrace != null || backtrace != null /* Out of protocol state */ ) { - fillInStackTrace(0); + if (backtrace == null && StackStreamFactory.useStackTrace(this)) { + backtrace = StackStreamFactory.makeStackTrace(this); + } else { + fillInStackTrace(0); + } stackTrace = UNASSIGNED_STACK; } return this; @@ -819,10 +825,14 @@ // backtrace if this is the first call to this method if (stackTrace == UNASSIGNED_STACK || (stackTrace == null && backtrace != null) /* Out of protocol state */) { - int depth = getStackTraceDepth(); - stackTrace = new StackTraceElement[depth]; - for (int i=0; i < depth; i++) - stackTrace[i] = getStackTraceElement(i); + if (backtrace instanceof StackStreamFactory.StackTrace) { + stackTrace = ((StackStreamFactory.StackTrace)backtrace).getStackTraceElements(); + } else { + int depth = getStackTraceDepth(); + stackTrace = new StackTraceElement[depth]; + for (int i = 0; i < depth; i++) + stackTrace[i] = getStackTraceElement(i); + } } else if (stackTrace == null) { return UNASSIGNED_STACK; } --- old/jdk/src/java.base/share/classes/java/lang/invoke/MemberName.java 2015-11-09 17:14:54.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/invoke/MemberName.java 2015-11-09 17:14:54.000000000 -0800 @@ -1077,4 +1077,13 @@ // System.out.println("Hello world! My methods are:"); // System.out.println(Factory.INSTANCE.getMethods(MemberName.class, true, null)); // } + + static { + // Allow privileged classes outside of java.lang + jdk.internal.misc.SharedSecrets.setJavaLangInvokeAccess(new jdk.internal.misc.JavaLangInvokeAccess() { + public Object newMemberName() { + return new MemberName(); + } + }); + } } --- old/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangAccess.java 2015-11-09 17:14:54.000000000 -0800 +++ new/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangAccess.java 2015-11-09 17:14:54.000000000 -0800 @@ -103,16 +103,6 @@ void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook); /** - * Returns the number of stack frames represented by the given throwable. - */ - int getStackTraceDepth(Throwable t); - - /** - * Returns the ith StackTraceElement for the given throwable. - */ - StackTraceElement getStackTraceElement(Throwable t, int i); - - /** * Returns a new string backed by the provided character array. The * character array is not copied and must never be modified after the * String is created, in order to fulfill String's contract. --- old/jdk/src/java.base/share/classes/jdk/internal/misc/SharedSecrets.java 2015-11-09 17:14:55.000000000 -0800 +++ new/jdk/src/java.base/share/classes/jdk/internal/misc/SharedSecrets.java 2015-11-09 17:14:55.000000000 -0800 @@ -45,6 +45,7 @@ private static final Unsafe unsafe = Unsafe.getUnsafe(); private static JavaUtilJarAccess javaUtilJarAccess; private static JavaLangAccess javaLangAccess; + private static JavaLangInvokeAccess javaLangInvokeAccess; private static JavaLangRefAccess javaLangRefAccess; private static JavaIOAccess javaIOAccess; private static JavaNetAccess javaNetAccess; @@ -80,6 +81,14 @@ return javaLangAccess; } + public static void setJavaLangInvokeAccess(JavaLangInvokeAccess jlia) { + javaLangInvokeAccess = jlia; + } + + public static JavaLangInvokeAccess getJavaLangInvokeAccess() { + return javaLangInvokeAccess; + } + public static void setJavaLangRefAccess(JavaLangRefAccess jlra) { javaLangRefAccess = jlra; } --- old/jdk/src/java.base/share/classes/sun/util/logging/PlatformLogger.java 2015-11-09 17:14:55.000000000 -0800 +++ new/jdk/src/java.base/share/classes/sun/util/logging/PlatformLogger.java 2015-11-09 17:14:55.000000000 -0800 @@ -32,15 +32,13 @@ import java.io.StringWriter; import java.security.AccessController; import java.security.PrivilegedAction; -import java.time.Clock; -import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import jdk.internal.misc.JavaLangAccess; -import jdk.internal.misc.SharedSecrets; +import java.util.Optional; +import java.util.function.Predicate; /** * Platform logger provides an API for the JRE components to log @@ -539,44 +537,56 @@ throwable); } - // Returns the caller's class and method's name; best effort - // if cannot infer, return the logger's name. - private String getCallerInfo() { - String sourceClassName = null; - String sourceMethodName = null; + /* + * CallerFinder is a stateful predicate. + */ + static final class CallerFinder implements Predicate { + static final StackWalker WALKER = StackWalker.create(); - JavaLangAccess access = SharedSecrets.getJavaLangAccess(); - Throwable throwable = new Throwable(); - int depth = access.getStackTraceDepth(throwable); - - String logClassName = "sun.util.logging.PlatformLogger"; - boolean lookingForLogger = true; - for (int ix = 0; ix < depth; ix++) { - // Calling getStackTraceElement directly prevents the VM - // from paying the cost of building the entire stack frame. - StackTraceElement frame = - access.getStackTraceElement(throwable, ix); - String cname = frame.getClassName(); + /** + * Returns StackTraceElement of the caller's frame. + * @return StackTraceElement of the caller's frame. + */ + Optional get() { + return WALKER.walk(s -> s.filter(this).findFirst()); + } + + private boolean lookingForLogger = true; + + /** + * Returns true if we have found the caller's frame, false if the frame + * must be skipped. + * + * @param t The frame info. + * @return true if we have found the caller's frame, false if the frame + * must be skipped. + */ + @Override + public boolean test(StackWalker.StackFrame t) { + final String cname = t.getClassName(); + // We should skip all frames until we have found the logger, + // because these frames could be frames introduced by e.g. custom + // sub classes of Handler. if (lookingForLogger) { - // Skip all frames until we have found the first logger frame. - if (cname.equals(logClassName)) { - lookingForLogger = false; - } - } else { - if (!cname.equals(logClassName)) { - // We've found the relevant frame. - sourceClassName = cname; - sourceMethodName = frame.getMethodName(); - break; - } + lookingForLogger = !cname.equals("sun.util.logging.PlatformLogger"); + return false; } + // Once the logger is found - we should skip all frames that + // point to packages which contain artifacts that could be + // inserted between the logger and its caller. These could be + // logger wrappers from j.u.l or sun.util.logging (e.g. the + // PlatformLogger or artifacts between the PlatformLogger and + // the actual logger) or frames inserted by use of reflection + // and/or doPrivileged calls. + return !cname.startsWith("java.util.logging.") + && !cname.startsWith("sun.util.logging.") + && !cname.startsWith("java.security.AccessController"); } + } - if (sourceClassName != null) { - return sourceClassName + " " + sourceMethodName; - } else { - return name; - } + private String getCallerInfo() { + Optional frame = new CallerFinder().get(); + return frame.map(f -> f.getClassName() + " " + f.getMethodName()).orElse(name); } } --- old/jdk/src/java.base/share/native/include/jvm.h 2015-11-09 17:14:56.000000000 -0800 +++ new/jdk/src/java.base/share/native/include/jvm.h 2015-11-09 17:14:56.000000000 -0800 @@ -178,6 +178,30 @@ JVM_GetStackTraceElement(JNIEnv *env, jobject throwable, jint index); /* + * java.lang.StackWalker + */ +JNIEXPORT jobject JNICALL +JVM_CallStackWalk(JNIEnv *env, jobject stackStream, jlong mode, + jint skip_frames, jint frame_count, jint start_index, + jobjectArray classes, + jobjectArray frames); + +JNIEXPORT jint JNICALL +JVM_MoreStackWalk(JNIEnv *env, jobject stackStream, jlong mode, jlong anchor, + jint frame_count, jint start_index, + jobjectArray classes, + jobjectArray frames); + +JNIEXPORT void JNICALL +JVM_FillStackFrames(JNIEnv* env, jclass cls, + jint start_index, + jobjectArray stackFrames, + jint from_index, jint toIndex); + +JNIEXPORT void JNICALL +JVM_SetMethodInfo(JNIEnv* env, jobject frame); + +/* * java.lang.Thread */ JNIEXPORT void JNICALL --- old/jdk/src/java.logging/share/classes/java/util/logging/LogRecord.java 2015-11-09 17:14:56.000000000 -0800 +++ new/jdk/src/java.logging/share/classes/java/util/logging/LogRecord.java 2015-11-09 17:14:56.000000000 -0800 @@ -30,9 +30,9 @@ import java.util.concurrent.atomic.AtomicLong; import java.io.*; import java.time.Clock; - -import jdk.internal.misc.JavaLangAccess; -import jdk.internal.misc.SharedSecrets; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.function.Predicate; /** * LogRecord objects are used to pass logging requests between @@ -639,43 +639,62 @@ // Private method to infer the caller's class and method names private void inferCaller() { needToInferCaller = false; - JavaLangAccess access = SharedSecrets.getJavaLangAccess(); - Throwable throwable = new Throwable(); - int depth = access.getStackTraceDepth(throwable); - - boolean lookingForLogger = true; - for (int ix = 0; ix < depth; ix++) { - // Calling getStackTraceElement directly prevents the VM - // from paying the cost of building the entire stack frame. - StackTraceElement frame = - access.getStackTraceElement(throwable, ix); - String cname = frame.getClassName(); - boolean isLoggerImpl = isLoggerImplFrame(cname); - if (lookingForLogger) { - // Skip all frames until we have found the first logger frame. - if (isLoggerImpl) { - lookingForLogger = false; - } - } else { - if (!isLoggerImpl) { - // skip reflection call - if (!cname.startsWith("java.lang.reflect.") && !cname.startsWith("sun.reflect.")) { - // We've found the relevant frame. - setSourceClassName(cname); - setSourceMethodName(frame.getMethodName()); - return; - } - } - } - } + // Skip all frames until we have found the first logger frame. + Optional frame = new CallerFinder().get(); + frame.ifPresent(f -> { + setSourceClassName(f.getClassName()); + setSourceMethodName(f.getMethodName()); + }); + // We haven't found a suitable frame, so just punt. This is // OK as we are only committed to making a "best effort" here. } - private boolean isLoggerImplFrame(String cname) { - // the log record could be created for a platform logger - return (cname.equals("java.util.logging.Logger") || - cname.startsWith("java.util.logging.LoggingProxyImpl") || - cname.startsWith("sun.util.logging.")); + /* + * CallerFinder is a stateful predicate. + */ + static final class CallerFinder implements Predicate { + static final StackWalker WALKER = StackWalker.create(); + + /** + * Returns StackTraceElement of the caller's frame. + * @return StackTraceElement of the caller's frame. + */ + Optional get() { + return WALKER.walk((s) -> s.filter(this).findFirst()); + } + + private boolean lookingForLogger = true; + /** + * Returns true if we have found the caller's frame, false if the frame + * must be skipped. + * + * @param t The frame info. + * @return true if we have found the caller's frame, false if the frame + * must be skipped. + */ + @Override + public boolean test(StackWalker.StackFrame t) { + final String cname = t.getClassName(); + // We should skip all frames until we have found the logger, + // because these frames could be frames introduced by e.g. custom + // sub classes of Handler. + if (lookingForLogger) { + lookingForLogger = !cname.equals("java.util.logging.Logger") && + !cname.startsWith("java.util.logging.LoggingProxyImpl") && + !cname.startsWith("sun.util.logging."); + return false; + } + // Once the logger is found - we should skip all frames that + // point to packages which contain artifacts that could be + // inserted between the logger and its caller. These could be + // logger wrappers from j.u.l or sun.uti.logging (e.g. the + // PlatformLogger or artifacts between the PlatformLogger and + // the actual logger) or frames inserted by use of reflection + // and/or doPrivileged calls. + return !cname.startsWith("java.util.logging.") + && !cname.startsWith("sun.util.logging.") + && !cname.startsWith("java.security.AccessController"); + } } } --- /dev/null 2015-11-09 17:14:57.000000000 -0800 +++ new/hotspot/src/share/vm/prims/stackwalk.cpp 2015-11-09 17:14:57.000000000 -0800 @@ -0,0 +1,539 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "precompiled.hpp" +#include "classfile/javaClasses.hpp" +#include "classfile/javaClasses.inline.hpp" +#include "classfile/vmSymbols.hpp" +#include "memory/oopFactory.hpp" +#include "oops/oop.inline.hpp" +#include "oops/objArrayOop.inline.hpp" +#include "prims/stackwalk.hpp" +#include "runtime/globals.hpp" +#include "runtime/handles.inline.hpp" +#include "runtime/javaCalls.hpp" +#include "runtime/vframe.hpp" +#include "utilities/globalDefinitions.hpp" + +Klass* StackWalk::_abstractStackWalker_klass = NULL; +Klass* StackWalk::_stackWalker_klass = NULL; + +// setup and cleanup actions +void StackWalkAnchor::setup_magic_on_entry() { + _frames->obj_at_put(StackWalk::magic_pos, _thread->threadObj()); + _anchor = address_value(); + assert(check_magic(), "invalid magic"); +} + +bool StackWalkAnchor::check_magic() { + oop m1 = _frames->obj_at(StackWalk::magic_pos); + jlong m2 = _anchor; + if (m1 == _thread->threadObj() && m2 == address_value()) return true; + return false; +} + +bool StackWalkAnchor::cleanup_magic_on_exit() { + bool ok = check_magic(); + _frames->obj_at_put(StackWalk::magic_pos, NULL); + _anchor = 0L; + return ok; +} + +/** + * Returns StackWalkAnchor for the current stack being traversed. + * + * @argument thread. Current Java thread. + * @argument magic. Magic value used for each stack walking + * @argument classes_array User-supplied buffers. The 0th element is reserved + * to this StackWalkAnchor to use + */ +StackWalkAnchor* StackWalkAnchor::from_current(JavaThread* thread, jlong magic, + objArrayHandle classes_array) +{ + assert(thread != NULL && thread->is_Java_thread(), ""); + oop m1 = classes_array->obj_at(StackWalk::magic_pos); + if (m1 != thread->threadObj()) return NULL; + if (magic == 0L) return NULL; + StackWalkAnchor* anchor = (StackWalkAnchor*) (intptr_t) magic; + if (!anchor->is_valid_in(thread)) return NULL; + return anchor; +} + +/* + * Unpacks one or more frames into user-supplied buffers. + * Updates the end index, and returns the number of unpacked frames. + * Always start with the existing vfst.method and bci. + * Do not call vfst.next to advance over the last returned value. + * In other words, do not leave any stale data in the vfst. + * + * @argument mode. Restrict which frames to be decoded. + * @argument decode_limit. Maximum of frames to be decoded. + * @argument start_index. Start index to the user-supplied buffers. + * @argument classes_array. Buffer to store classes in, starting at start_index. + * @argument frames_array. Buffer to store StackFrame in, starting at start_index. + * NULL if not used. + * @argument end_index. End index to the user-supplied buffers + * with unpacked frames. + * + * @return Number of frames whose information was transferred into the buffers. + */ +int StackWalkAnchor::decode_frames(jlong mode, int decode_limit, int start_index, + objArrayHandle classes_array, + objArrayHandle frames_array, + int& end_index, TRAPS) { + if (TraceStackWalk) { + tty->print_cr("decode_frames limit=%d start=%d frames length=%d", + decode_limit, start_index, classes_array->length()); + } + assert(decode_limit > 0, "invalid decode_limit"); + assert(start_index + decode_limit <= classes_array->length(), "oob"); + + int frames_decoded = 0; + for (; !_vfst.at_end(); _vfst.next()) { + Method* method = _vfst.method(); + int bci = _vfst.bci(); + + if (method == NULL) continue; + if (!ShowHiddenFrames && StackWalk::skip_hidden_frames(mode)) { + if (method->is_hidden()) { + if (TraceStackWalk) { + tty->print(" hidden method: "); method->print_short_name(); + } + continue; + } + } + + int index = end_index++; + if (TraceStackWalk) { + tty->print(" %d: frame method: ", index); method->print_short_name(); + tty->print_cr(" bci=%d", bci); + } + + classes_array->obj_at_put(index, method->method_holder()->java_mirror()); + // fill in StackFrameInfo and initialize MemberName + if (StackWalk::live_frame_info(mode)) { + Handle stackFrame(frames_array->obj_at(index)); + StackWalk::fill_live_stackframe(method, bci, stackFrame, _vfst.java_frame(), CHECK_0); + } else if (StackWalk::need_method_info(mode)) { + Handle stackFrame(frames_array->obj_at(index)); + StackWalk::fill_frame_buffer(method, bci, stackFrame); + } + if (++frames_decoded >= decode_limit) break; + } + return frames_decoded; +} + +static oop create_primitive_value_instance(StackValueCollection* values, int i, TRAPS) { + Klass* k = SystemDictionary::resolve_or_null(vmSymbols::java_lang_LiveStackFrameInfo(), CHECK_NULL); + instanceKlassHandle ik (THREAD, k); + + JavaValue result(T_OBJECT); + JavaCallArguments args; + Symbol* signature; + + // ## TODO: type is only available in LocalVariable table, if present. + // ## StackValue type is T_INT or T_OBJECT. + switch (values->at(i)->type()) { + case T_INT: + args.push_int(values->int_at(i)); + signature = vmSymbols::asPrimitive_int_signature(); + break; + + case T_LONG: + args.push_long(values->long_at(i)); + signature = vmSymbols::asPrimitive_long_signature(); + break; + + case T_FLOAT: + args.push_float(values->float_at(i)); + signature = vmSymbols::asPrimitive_float_signature(); + break; + + case T_DOUBLE: + args.push_double(values->double_at(i)); + signature = vmSymbols::asPrimitive_double_signature(); + break; + + case T_BYTE: + args.push_int(values->int_at(i)); + signature = vmSymbols::asPrimitive_byte_signature(); + break; + + case T_SHORT: + args.push_int(values->int_at(i)); + signature = vmSymbols::asPrimitive_short_signature(); + break; + + case T_CHAR: + args.push_int(values->int_at(i)); + signature = vmSymbols::asPrimitive_char_signature(); + break; + + case T_BOOLEAN: + args.push_int(values->int_at(i)); + signature = vmSymbols::asPrimitive_boolean_signature(); + break; + + case T_OBJECT: + return values->obj_at(i)(); + + case T_CONFLICT: + return NULL; + default: ShouldNotReachHere(); + } + JavaCalls::call_static(&result, + ik, + vmSymbols::asPrimitive_name(), + signature, + &args, + CHECK_NULL); + return (instanceOop) result.get_jobject(); +} + +static objArrayHandle values_to_object_array(StackValueCollection* values, TRAPS) { + int length = values->size(); + objArrayOop array_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(), + length, CHECK_(objArrayHandle())); + objArrayHandle array_h(THREAD, array_oop); + for (int i = 0; i < values->size(); i++) { + StackValue* st = values->at(i); + oop obj = create_primitive_value_instance(values, i, CHECK_(objArrayHandle())); + if (obj != NULL) + array_h->obj_at_put(i, obj); + } + return array_h; +} + +static objArrayHandle monitors_to_object_array(GrowableArray* monitors, TRAPS) { + int length = monitors->length(); + objArrayOop array_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(), + length, CHECK_(objArrayHandle())); + objArrayHandle array_h(THREAD, array_oop); + for (int i = 0; i < length; i++) { + MonitorInfo* monitor = monitors->at(i); + array_h->obj_at_put(i, monitor->owner()); + } + return array_h; +} + +/* + * Initialize MemberName + */ +static void init_MemberName(oop mname, methodHandle method) { + InstanceKlass* ik = method->method_holder(); + CallInfo info(method(), ik); + MethodHandles::init_method_MemberName(mname, info); +} + +/* + * Fill StackFrameInfo with declaringClass and bci and initialize memberName + */ +void StackWalk::fill_frame_buffer(methodHandle method, int bci, Handle stackFrame) { + if (TraceStackWalk) { + tty->print(" member name: "); method->print_short_name(); + } + + java_lang_StackFrameInfo::set_declaringClass(stackFrame(), method->method_holder()->java_mirror()); + if (MemberNameInStackFrame) { + // ## handle redefined Method* in MemberName; does it need version? + init_MemberName(java_lang_StackFrameInfo::member_name(stackFrame()), method); + java_lang_StackFrameInfo::set_bci(stackFrame(), bci); + if (TraceStackWalk) { + tty->print_cr(" bci=%d", bci); + } + } else { + int mid = method->orig_method_idnum(); + int version = method->constants()->version(); + int cpref = method->name_index(); + + java_lang_StackFrameInfo::set_mid(stackFrame(), BackTrace::merge_mid_and_cpref(mid, cpref)); + java_lang_StackFrameInfo::set_bci(stackFrame(), BackTrace::merge_bci_and_version(bci, version)); + if (TraceStackWalk) { + tty->print_cr(" mid=%d, cpref=%d bci=%d, version=%d", + mid, cpref, bci, version); + } + } +} + +/* + * Fill LiveStackFrameInfo with locals, monitors, and expressions + */ + +void StackWalk::fill_live_stackframe(methodHandle method, int bci, Handle stackFrame, javaVFrame* jvf, TRAPS) { + java_lang_StackFrameInfo::set_declaringClass(stackFrame(), method->method_holder()->java_mirror()); + if (MemberNameInStackFrame) { + init_MemberName(java_lang_StackFrameInfo::member_name(stackFrame()), method); + java_lang_StackFrameInfo::set_bci(stackFrame(), bci); + } else { + int mid = method->orig_method_idnum(); + int version = method->constants()->version(); + int cpref = method->name_index(); + + java_lang_StackFrameInfo::set_mid(stackFrame(), BackTrace::merge_mid_and_cpref(mid, cpref)); + java_lang_StackFrameInfo::set_bci(stackFrame(), BackTrace::merge_bci_and_version(bci, version)); + } + + if (jvf != NULL) { + StackValueCollection* locals = jvf->locals(); + StackValueCollection* expressions = jvf->expressions(); + GrowableArray* monitors = jvf->monitors(); + + if (!locals->is_empty()) { + objArrayHandle locals_h = values_to_object_array(locals, CHECK); + java_lang_LiveStackFrameInfo::set_locals(stackFrame(), locals_h()); + } + if (!expressions->is_empty()) { + objArrayHandle expressions_h = values_to_object_array(expressions, CHECK); + java_lang_LiveStackFrameInfo::set_operands(stackFrame(), expressions_h()); + } + if (monitors->length() > 0) { + objArrayHandle monitors_h = monitors_to_object_array(monitors, CHECK); + java_lang_LiveStackFrameInfo::set_monitors(stackFrame(), monitors_h()); + } + } +} + +Klass* StackWalk::AbstractStackWalker_klass(TRAPS) { + if (_abstractStackWalker_klass == NULL) { + _abstractStackWalker_klass = SystemDictionary::resolve_or_null(vmSymbols::java_lang_StackStreamFactory_AbstractStackWalker(), CHECK_NULL); + } + return _abstractStackWalker_klass;; +} + +Klass* StackWalk::StackWalker_klass(TRAPS) { + if (_stackWalker_klass == NULL) { + _stackWalker_klass = SystemDictionary::resolve_or_null(vmSymbols::java_lang_StackWalker(), CHECK_NULL); + } + return _stackWalker_klass; +} + +/* + * Begins stack walking. + * + * @argument stackStream. StackStream object + * @argument mode. Stack walking mode. + * @argument skip_frames. Number of frames to be skipped. + * @argument frame_count. Number of frames to be traversed. + * @argument start_index. Start index to the user-supplied buffers. + * @argument classes_array. Buffer to store classes in, starting at start_index. + * @argument frames_array. Buffer to store StackFrame in, starting at start_index. + * NULL if not used. + * @return Object returned from AbstractStackWalker::doStackWalk call. + */ +Handle StackWalk::walk(Handle stackStream, jlong mode, + int skip_frames, int frame_count, int start_index, + objArrayHandle classes_array, + objArrayHandle frames_array, + TRAPS) +{ + Handle empty; + + JavaThread* jt = (JavaThread*)THREAD; + if (TraceStackWalk) { + tty->print_cr("Start walking: mode " JLONG_FORMAT " skip %d frames batch size %d", mode, skip_frames, frame_count); + } + + if (need_method_info(mode)) { + if (frames_array.is_null()) { + THROW_MSG_(vmSymbols::java_lang_NullPointerException(), "frames_array is NULL", empty); + } + } + + Klass* stackWalker_klass = StackWalker_klass(CHECK_(empty)); + Klass* abstractStackWalker_klass = AbstractStackWalker_klass(CHECK_(empty)); + + methodHandle m_doStackWalk; + { + Method* m = InstanceKlass::cast(abstractStackWalker_klass)->find_method(vmSymbols::doStackWalk_name(), + vmSymbols::doStackWalk_signature()); + if (m == NULL || m->is_static()) { + THROW_MSG_(vmSymbols::java_lang_InternalError(), "no AbstractStackStream::doStackWalk method", empty); + } + m_doStackWalk = methodHandle(THREAD, m); + } + + if (live_frame_info(mode)) { + if (frames_array.is_null()) { + THROW_MSG_(vmSymbols::java_lang_NullPointerException(), "frames_array argument", empty); + } + java_lang_LiveStackFrameInfo::compute_offsets(); + } + + // Open up a traversable stream onto my stack. + // This stream will be made available by *reference* to the inner Java call. + StackWalkAnchor anchor(jt, classes_array); + vframeStream& vfst = anchor.vframe_stream(); + + { + // Skip all methods from AbstractStackWalker and StackWalk (enclosing method) + if (!fill_in_stacktrace(mode)) { + while (!vfst.at_end()) { + InstanceKlass* ik = vfst.method()->method_holder(); + if (ik != stackWalker_klass && ik != abstractStackWalker_klass && ik->super() != abstractStackWalker_klass) { + break; + } + + if (TraceStackWalk) { + tty->print(" skip "); vfst.method()->print_short_name(); tty->print("\n"); + } + vfst.next(); + } + } + + // For exceptions, skip Throwable::fillInStackTrace and methods + // of the exception class and superclasses + if (fill_in_stacktrace(mode)) { + bool skip_to_fillInStackTrace = false; + bool skip_throwableInit_check = false; + while (!vfst.at_end() && !skip_throwableInit_check) { + InstanceKlass* ik = vfst.method()->method_holder(); + Method* method = vfst.method(); + if (!skip_to_fillInStackTrace) { + if (ik == SystemDictionary::Throwable_klass() && + method->name() == vmSymbols::fillInStackTrace_name()) { + // this frame will be skipped + skip_to_fillInStackTrace = true; + } + } else if (!(ik->is_subclass_of(SystemDictionary::Throwable_klass()) && + method->name() == vmSymbols::object_initializer_name())) { + // there are none or we've seen them all - either way stop checking + skip_throwableInit_check = true; + break; + } + + if (TraceStackWalk) { + tty->print("stack walk: skip "); vfst.method()->print_short_name(); tty->print("\n"); + } + vfst.next(); + } + } + + // stack frame has been traversed individually and resume stack walk + // from the stack frame at depth == skip_frames. + for (int n=0; n < skip_frames && !vfst.at_end(); vfst.next(), n++) { + if (TraceStackWalk) { + tty->print(" skip "); vfst.method()->print_short_name(); + tty->print_cr(" frame id: " PTR_FORMAT " pc: " PTR_FORMAT, + p2i(vfst.frame_id()), p2i(vfst.frame_pc())); + } + } + } + + // The Method* pointer in the vfst has a very short shelf life. Grab it now. + int end_index = start_index; + int numFrames = 0; + if (!vfst.at_end()) { + numFrames = anchor.decode_frames(mode, frame_count, start_index, classes_array, + frames_array, end_index, CHECK_(empty)); + if (numFrames < 1) { + THROW_MSG_(vmSymbols::java_lang_InternalError(), "stack walk: decode failed", empty); + } + } + + // call StackStream::doStackWalk to do bulk traversal on the entire stack + JavaValue result(T_OBJECT); + JavaCallArguments args(stackStream); + args.push_long(anchor.address_value()); + args.push_int(skip_frames); + args.push_int(frame_count); + args.push_int(start_index); + args.push_int(end_index); + + // Link the thread and vframe stream into the callee-visible object: + anchor.setup_magic_on_entry(); + + JavaCalls::call(&result, m_doStackWalk, &args, THREAD); + + // Do this before anything else happens, to disable any lingering stream objects: + bool ok = anchor.cleanup_magic_on_exit(); + + // Throw pendiing exception if we must: + (void) (CHECK_(empty)); + + if (!ok) { + THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: corrupted buffers on exit", empty); + } + + Handle obj(THREAD, (oop) result.get_jobject()); + // Return normally: + return obj; + +} + +/* + * Walk the next batch of stack frames + * + * @argument stackStream. StackStream object + * @argument mode. Stack walking mode. + * @argument magic. Must be valid value to continue the stack walk + * @argument frame_count. Number of frames to be decoded. + * @argument start_index. Start index to the user-supplied buffers. + * @argument classes_array. Buffer to store classes in, starting at start_index. + * @argument frames_array. Buffer to store StackFrame in, starting at start_index. + * NULL if not used. + * @return End index + */ +jint StackWalk::moreFrames(Handle stackStream, jlong mode, jlong magic, + int frame_count, int start_index, + objArrayHandle classes_array, + objArrayHandle frames_array, + TRAPS) +{ + JavaThread* jt = (JavaThread*)THREAD; + StackWalkAnchor* existing_anchor = StackWalkAnchor::from_current(jt, magic, classes_array); + if (existing_anchor == NULL) { + THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: corrupted buffers", 0L); + } + + if ((need_method_info(mode) || live_frame_info(mode)) && frames_array.is_null()) { + THROW_MSG_(vmSymbols::java_lang_NullPointerException(), "frames_array is NULL", 0L); + } + + if (TraceStackWalk) { + tty->print_cr("StackWalk::moreFrames frame_count %d existing_anchor " PTR_FORMAT " start %d frames %d", + frame_count, p2i(existing_anchor), start_index, classes_array->length()); + } + int end_index = start_index; + if (frame_count <= 0) { + return end_index; // No operation. + } + + int count = frame_count+start_index; + assert (classes_array->length() >= count, "not enough space in buffers"); + + StackWalkAnchor& anchor = (*existing_anchor); + vframeStream& vfst = anchor.vframe_stream(); + if (!vfst.at_end()) { + vfst.next(); // skip java.lang.StackStream::moreStackWalk + if (!vfst.at_end()) { + int n = anchor.decode_frames(mode, frame_count, start_index, classes_array, + frames_array, end_index, CHECK_0); + if (n < 1) { + THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: later decode failed", 0L); + } + return end_index; + } + } + return end_index; +} --- /dev/null 2015-11-09 17:14:57.000000000 -0800 +++ new/hotspot/src/share/vm/prims/stackwalk.hpp 2015-11-09 17:14:57.000000000 -0800 @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + + +#ifndef SHARE_VM_PRIMS_STACKWALK_HPP +#define SHARE_VM_PRIMS_STACKWALK_HPP + +#include "oops/oop.hpp" +#include "runtime/vframe.hpp" + +class StackWalkAnchor : public StackObj { + JavaThread* _thread; + objArrayHandle _frames; + vframeStream _vfst; + jlong _anchor; + address _last_decoded_frame_pc; +public: + StackWalkAnchor(JavaThread* thread, objArrayHandle frames_array) + : _thread(thread), _frames(frames_array), _vfst(thread), _anchor(0L), _last_decoded_frame_pc(0L) + { + } + + vframeStream& vframe_stream() { return _vfst; } + JavaThread* thread() { return _thread; } + objArrayHandle frames() { return _frames; } + address last_decoded_frame_pc() { return _last_decoded_frame_pc; } + + void setup_magic_on_entry(); + bool check_magic(); + bool cleanup_magic_on_exit(); + + bool is_valid_in(Thread* thread) { + return (_thread == thread && check_magic()); + } + + jlong address_value() { + return (jlong) castable_address(this); + } + + int decode_frames(jlong mode, int decode_limit, int start_index, + objArrayHandle classes_array, + objArrayHandle frames_array, + int& end_index, TRAPS); + static StackWalkAnchor* from_current(JavaThread* thread, jlong anchor, objArrayHandle frames_array); +}; + +class StackWalk : public AllStatic { +public: + enum { + magic_pos = 0, + fill_class_refs_only = 0x2, + fill_method_name = 0x4, + fill_frame_buffer_only = 0x8, + filter_fillInStackTrace = 0x10, + show_hidden_frames = 0x20, + fill_locals_operands = 0x100 + }; +private: + static Klass* _stackWalker_klass; + static Klass* _abstractStackWalker_klass; + + static Klass* StackWalker_klass(TRAPS); + + // After this many redefines, the stack trace is unreliable. +public: + static Handle walk(Handle stackStream, jlong mode, + int skip_frames, int frame_count, int start_index, + objArrayHandle classes_array, + objArrayHandle frames_array, + TRAPS); + + static jint moreFrames(Handle stackStream, jlong mode, jlong magic, + int frame_count, int start_index, + objArrayHandle classes_array, + objArrayHandle frames_array, + TRAPS); + + static void fill_frame_buffer(methodHandle method, int bci, Handle stackFrame); + + static void fill_live_stackframe(methodHandle method, int bci, + Handle stackFrame, javaVFrame* jvf, TRAPS); + + static Klass* AbstractStackWalker_klass(TRAPS); + + static inline bool skip_hidden_frames(int mode) { return (mode & show_hidden_frames) == 0; } + static inline bool need_method_info(int mode) { return (mode & fill_class_refs_only) == 0; } + static inline bool live_frame_info(int mode) { return (mode & fill_locals_operands) != 0; } + static inline bool fill_in_stacktrace(int mode) { return (mode & filter_fillInStackTrace) != 0; } + +}; +#endif // SHARE_VM_PRIMS_STACKWALK_HPP --- /dev/null 2015-11-09 17:14:58.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/LiveStackFrame.java 2015-11-09 17:14:58.000000000 -0800 @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package java.lang; + +import java.lang.StackWalker.StackFrame; + +/** + * UNSUPPORTED This interface is intended to be package-private + * or move to an internal package.

+ * + * {@code LiveStackFrame} represents a frame storing data and partial results. + * Each frame has its own array of local variables (JVMS section 2.6.1), + * its own operand stack (JVMS section 2.6.2) for a method invocation. + * + * @jvms 2.6 Frames + */ +/* package-private */ +interface LiveStackFrame extends StackFrame { + /** + * Return the monitors held by this stack frame. This method returns + * an empty array if no monitor is held by this stack frame. + * + * @return the monitors held by this stack frames + */ + public Object[] getMonitors(); + + /** + * Gets the local variable array of this stack frame. + * + *

A single local variable can hold a value of type boolean, byte, char, + * short, int, float, reference or returnAddress. A pair of local variables + * can hold a value of type long or double. In other words, + * a value of type long or type double occupies two consecutive local + * variables. For a value of primitive type, the element in the + * local variable array is an {@link PrimitiveValue} object; + * otherwise, the element is an {@code Object}. + * + *

A value of type long or double will be represented by + * a {@code PrimitiveValue} object containing the value in the elements + * at index n and n+1 in the local variable array. + * + * @return the local variable array of this stack frame. + */ + public Object[] getLocals(); + + /** + * Gets the operand stack of this stack frame. + * + *

+ * The 0-th element of the returned array represents the top of the operand stack. + * This method returns an empty array if the operand stack is empty. + * + *

Each entry on the operand stack can hold a value of any Java Virtual + * Machine Type. + * For a value of primitive type, the element in the returned array is + * an {@link PrimitiveValue} object; otherwise, the element is the {@code Object} + * on the operand stack. + * + *

A value of type long or double contributes two elements + * of the returned array and a value of any other type contributes one element; + * i.e. a value of type long or double at index + * i, the elements at i and i+1 in the returned + * array are both the same {@code PrimitiveValue} object containing the value. + * + * @return the operand stack of this stack frame. + */ + public Object[] getStack(); + + /** + * UNSUPPORTED This interface is intended to be package-private + * or move to an internal package.

+ * + * Represents a local variable or an entry on the operand whose value is + * of primitive type. + */ + public interface PrimitiveValue { + /** + * Returns the base type of this primitive value, one of + * {@code B, D, C, F, I, J, S, Z}. + * + * @return Name of a base type + * @jvms table 4.3-A + */ + char type(); + + /** + * Returns the boolean value if this primitive value is of type boolean. + * @return the boolean value if this primitive value is of type boolean. + * + * @throws UnsupportedOperationException if this primitive value is not + * of type boolean. + */ + default boolean booleanValue() { + throw new UnsupportedOperationException("this primitive of type " + type()); + } + + /** + * Returns the int value if this primitive value is of type int. + * @return the int value if this primitive value is of type int. + * + * @throws UnsupportedOperationException if this primitive value is not + * of type int. + */ + default int intValue() { + throw new UnsupportedOperationException("this primitive of type " + type()); + } + + /** + * Returns the long value if this primitive value is of type long. + * @return the long value if this primitive value is of type long. + * + * @throws UnsupportedOperationException if this primitive value is not + * of type long. + */ + default long longValue() { + throw new UnsupportedOperationException("this primitive of type " + type()); + } + + /** + * Returns the char value if this primitive value is of type char. + * @return the char value if this primitive value is of type char. + * + * @throws UnsupportedOperationException if this primitive value is not + * of type char. + */ + default char charValue() { + throw new UnsupportedOperationException("this primitive of type " + type()); + } + + /** + * Returns the byte value if this primitive value is of type byte. + * @return the byte value if this primitive value is of type byte. + * + * @throws UnsupportedOperationException if this primitive value is not + * of type byte. + */ + default byte byteValue() { + throw new UnsupportedOperationException("this primitive of type " + type()); + } + + /** + * Returns the short value if this primitive value is of type short. + * @return the short value if this primitive value is of type short. + * + * @throws UnsupportedOperationException if this primitive value is not + * of type short. + */ + default short shortValue() { + throw new UnsupportedOperationException("this primitive of type " + type()); + } + + /** + * Returns the float value if this primitive value is of type float. + * @return the float value if this primitive value is of type float. + * + * @throws UnsupportedOperationException if this primitive value is not + * of type float. + */ + default float floatValue() { + throw new UnsupportedOperationException("this primitive of type " + type()); + } + + /** + * Returns the double value if this primitive value is of type double. + * @return the double value if this primitive value is of type double. + * + * @throws UnsupportedOperationException if this primitive value is not + * of type double. + */ + default double doubleValue() { + throw new UnsupportedOperationException("this primitive of type " + type()); + } + } +} --- /dev/null 2015-11-09 17:14:58.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/LiveStackFrameInfo.java 2015-11-09 17:14:58.000000000 -0800 @@ -0,0 +1,314 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package java.lang; + +import java.lang.StackWalker.Option; +import java.util.EnumSet; +import java.util.Set; + +import static java.lang.StackWalker.ExtendedOption.*; + +final class LiveStackFrameInfo extends StackFrameInfo implements LiveStackFrame { + private static Object[] EMPTY_ARRAY = new Object[0]; + + /** + * Gets {@code StackWalker} that can get locals and operands. + * + * @throws SecurityException if the security manager is present and + * denies access to {@code RuntimePermission(""liveStackFrames")} + */ + public static StackWalker getStackWalker() { + return getStackWalker(EnumSet.noneOf(Option.class)); + } + + + /** + * Gets a {@code StackWalker} instance with the given options specifying + * the stack frame information it can access, and which will traverse at most + * the given {@code maxDepth} number of stack frames. If no option is + * specified, this {@code StackWalker} obtains the method name and + * the class name with all + * {@linkplain StackWalker.Option#SHOW_HIDDEN_FRAMES hidden frames} skipped. + * The returned {@code StackWalker} can get locals and operands. + * + *

+ * If a security manager is present and the given + * {@code options} contains {@link Option#RETAIN_CLASS_REFERENCE}, it will call its + * {@link SecurityManager#checkPermission checkPermission} method for + * {@code StackFramePermission("classReference")}. + * + * @param options stack walk {@link Option options} + * + * @throws IllegalArgumentException if {@code maxDepth <= 0} + * @throws SecurityException if a security manager exists and its + * {@code checkPermission} method denies access. + * @throws SecurityException if the security manager is present and + * denies access to {@code RuntimePermission(""liveStackFrames")} + */ + public static StackWalker getStackWalker(Set

Subclass may override this method to manage the allocated buffers. + * + * @param startIndex the start index for the first frame of the next batch to fill in. + * @param elements the number of elements for the next batch to fill in. + * + */ + void resize(int startIndex, int elements) { + if (!isActive()) + throw new IllegalStateException("inactive frame buffer can't be resized"); + + int size = startIndex+elements; + if (classes.length < size) { + // copy the elements in classes array to the newly allocated one. + // classes[0] is a Thread object + Class[] prev = classes; + classes = new Class[size]; + System.arraycopy(prev, 0, classes, 0, START_POS); + } + currentBatchSize = size; + } + + /* + * Returns the start index for this frame buffer is refilled. + * + * This implementation reuses the allocated buffer for the next batch + * of stack frames. For subclass to retain the fetched stack frames, + * it should override this method to return the index at which the frame + * should be filled in for the next batch. + */ + int startIndex() { + return START_POS; + } + + /** + * Returns next StackFrame object in the current batch of stack frames + */ + StackFrame nextStackFrame() { + throw new InternalError("should not reach here"); + } + } + } + + /* + * This StackFrameTraverser supports {@link Stream} traversal. + * + * This class implements Spliterator::forEachRemaining and Spliterator::tryAdvance. + */ + static class StackFrameTraverser extends AbstractStackWalker + implements Spliterator + { + private static final int CHARACTERISTICS = Spliterator.ORDERED | Spliterator.IMMUTABLE; + + class Buffer extends FrameBuffer { + Buffer(int initialBatchSize) { + super(initialBatchSize); + + this.stackFrames = new StackFrame[initialBatchSize]; + for (int i = START_POS; i < initialBatchSize; i++) { + stackFrames[i] = new StackFrameInfo(walker); + } + } + + @Override + void resize(int startIndex, int elements) { + super.resize(startIndex, elements); + + int size = startIndex+elements; + if (stackFrames.length < size) { + stackFrames = new StackFrame[size]; + } + for (int i = startIndex(); i < size; i++) { + stackFrames[i] = new StackFrameInfo(walker); + } + } + + @Override + StackFrame nextStackFrame() { + if (isEmpty()) { + throw new NoSuchElementException("origin=" + origin + " fence=" + fence); + } + + StackFrame frame = stackFrames[origin]; + origin++; + return frame; + } + } + + final Function, ? extends T> function; // callback + + StackFrameTraverser(StackWalker walker, + Function, ? extends T> function) { + this(walker, function, DEFAULT_MODE); + } + StackFrameTraverser(StackWalker walker, + Function, ? extends T> function, + int mode) { + super(walker, mode); + this.function = function; + } + + /** + * Returns next StackFrame object in the current batch of stack frames; + * or null if no more stack frame. + */ + StackFrame nextStackFrame() { + if (!hasNext()) { + return null; + } + + StackFrame frame = frameBuffer.nextStackFrame(); + depth++; + return frame; + } + + @Override + protected T consumeFrames() { + checkState(OPEN); + Stream stream = StreamSupport.stream(this, false); + if (function != null) { + return function.apply(stream); + } else + throw new UnsupportedOperationException(); + } + + @Override + protected void initFrameBuffer() { + this.frameBuffer = new Buffer(getNextBatchSize()); + } + + @Override + protected int batchSize(int lastBatchFrameCount) { + if (lastBatchFrameCount == 0) { + // First batch, use estimateDepth if not exceed the large batch size + // and not too small + int initialBatchSize = Math.max(walker.estimateDepth(), SMALL_BATCH); + return Math.min(initialBatchSize, LARGE_BATCH_SIZE); + } else { + if (lastBatchFrameCount > BATCH_SIZE) { + return lastBatchFrameCount; + } else { + return Math.min(lastBatchFrameCount*2, BATCH_SIZE); + } + } + } + + // ------- Implementation of Spliterator + + @Override + public Spliterator trySplit() { + return null; // ordered stream and do not allow to split + } + + @Override + public long estimateSize() { + return maxDepth; + } + + @Override + public int characteristics() { + return CHARACTERISTICS; + } + + @Override + public void forEachRemaining(Consumer action) { + checkState(OPEN); + for (int n = 0; n < maxDepth; n++) { + StackFrame frame = nextStackFrame(); + if (frame == null) break; + + action.accept(frame); + } + } + + @Override + public boolean tryAdvance(Consumer action) { + checkState(OPEN); + + int index = frameBuffer.getIndex(); + if (hasNext()) { + StackFrame frame = nextStackFrame(); + action.accept(frame); + if (isDebug) { + System.err.println("tryAdvance: " + index + " " + frame); + } + return true; + } + if (isDebug) { + System.err.println("tryAdvance: " + index + " NO element"); + } + return false; + } + } + + /* + * CallerClassFinder is specialized to return Class for each stack frame. + * StackFrame is not requested. + */ + static class CallerClassFinder extends AbstractStackWalker { + private Class caller; + + CallerClassFinder(StackWalker walker) { + super(walker, FILL_CLASS_REFS_ONLY); + } + + Optional> findCaller() { + walk(); + return caller != null ? Optional.of(caller) : Optional.empty(); + } + + @Override + protected Integer consumeFrames() { + checkState(OPEN); + int n = 0; + // skip the API calling this getCallerClass method + while (n < 2 && (caller = nextFrame()) != null) { + if (isDebug) { + System.err.println("caller: " + n + " " + caller.getName()); + } + n++; + } + return n; + } + + @Override + protected void initFrameBuffer() { + this.frameBuffer = new FrameBuffer(getNextBatchSize()); + } + + @Override + protected int batchSize(int lastBatchFrameCount) { + return MIN_BATCH_SIZE; + } + + @Override + protected int getNextBatchSize() { + return MIN_BATCH_SIZE; + } + } + + /* + * StackTrace caches all frames in the buffer. StackTraceElements are + * created lazily when Throwable::getStackTrace is called. + */ + static class StackTrace extends AbstractStackWalker { + class GrowableBuffer extends FrameBuffer { + GrowableBuffer(int initialBatchSize) { + super(initialBatchSize); + + this.stackFrames = new StackFrame[initialBatchSize]; + for (int i = START_POS; i < initialBatchSize; i++) { + stackFrames[i] = new StackFrameInfo(walker); + } + } + + /* + * Returns the next index to fill + */ + @Override + int startIndex() { + return origin; + } + + /** + * Initialize the buffers for VM to fill in the stack frame information. + * The next batch will start at the given startIndex to + * the length of the buffer. + */ + @Override + void resize(int startIndex, int elements) { + // Expand the frame buffer. + // Do not call super.resize that will reuse the filled elements + // in this frame buffer + int size = startIndex+elements; + if (classes.length < size) { + // resize the frame buffer + classes = Arrays.copyOf(classes, size); + stackFrames = Arrays.copyOf(stackFrames, size); + } + for (int i = startIndex; i < size; i++) { + stackFrames[i] = new StackFrameInfo(walker); + } + currentBatchSize = size; + } + + StackTraceElement get(int index) { + return new StackTraceElement(classes[index].getName(), "unknown", null, -1); + } + + /** + * Returns an array of StackTraceElement for all stack frames cached in + * this StackTrace object. + *

+ * This method is intended for Throwable::getOurStackTrace use only. + */ + StackTraceElement[] toStackTraceElements() { + int startIndex = START_POS; + for (int i = startIndex; i < classes.length; i++) { + if (classes[i] != null && filterStackWalkImpl(classes[i])) { + startIndex++; + } else { + break; + } + } + + // VM fills in the method name, filename, line number info + StackFrameInfo.fillInStackFrames(0, stackFrames, startIndex, startIndex + depth); + + StackTraceElement[] stes = new StackTraceElement[depth]; + for (int i = startIndex, j = 0; i < classes.length && j < depth; i++, j++) { + if (isDebug) { + System.err.println("StackFrame: " + i + " " + stackFrames[i]); + } + stes[j] = stackFrames[i].toStackTraceElement(); + } + return stes; + } + } + + private static final int MAX_STACK_FRAMES = 1024; + private StackTraceElement[] stes; + + StackTrace(StackWalker walker) { + this(walker, DEFAULT_MODE); + } + + /* + * Throwable::fillInStackTrace and of Throwable and subclasses + * are filtered in the VM. + */ + StackTrace(StackWalker walker, Throwable ex) { + this(walker, FILTER_FILL_IN_STACKTRACE); // skip Throwable::init frames + if (isDebug) { + System.err.println("dump stack for " + ex.getClass().getName()); + } + } + + StackTrace(StackWalker walker, int mode) { + super(walker, mode, MAX_STACK_FRAMES); + + // snapshot the stack trace + walk(); + } + + @Override + protected Integer consumeFrames() { + // traverse all frames and perform the action on the stack frames, if specified + int n = 0; + while (n < maxDepth && nextFrame() != null) { + n++; + } + return n; + } + + @Override + protected void initFrameBuffer() { + this.frameBuffer = new GrowableBuffer(getNextBatchSize()); + } + + // TODO: implement better heuristic + @Override + protected int batchSize(int lastBatchFrameCount) { + // chunk size of VM backtrace is 32 + return lastBatchFrameCount == 0 ? 32 : 32; + } + + /** + * Returns an array of StackTraceElement for all stack frames cached in + * this StackTrace object. + *

+ * This method is intended for Throwable::getOurStackTrace use only. + */ + synchronized StackTraceElement[] getStackTraceElements() { + if (stes == null) { + stes = ((GrowableBuffer) frameBuffer).toStackTraceElements(); + // release the frameBuffer memory + frameBuffer = null; + } + return stes; + } + + /* + * Prints stack trace to the given PrintStream. + * + * Further implementation could skip creating StackTraceElement objects + * print directly to the PrintStream. + */ + void printStackTrace(PrintStream s) { + StackTraceElement[] stes = getStackTraceElements(); + synchronized (s) { + s.println("Stack trace"); + for (StackTraceElement traceElement : stes) + s.println("\tat " + traceElement); + } + } + } + + static class LiveStackInfoTraverser extends StackFrameTraverser { + // VM will fill in all method info and live stack info directly in StackFrameInfo + class Buffer extends FrameBuffer { + Buffer(int initialBatchSize) { + super(initialBatchSize); + this.stackFrames = new StackFrame[initialBatchSize]; + for (int i = START_POS; i < initialBatchSize; i++) { + stackFrames[i] = new LiveStackFrameInfo(walker); + } + } + + @Override + void resize(int startIndex, int elements) { + super.resize(startIndex, elements); + int size = startIndex + elements; + + if (stackFrames.length < size) { + this.stackFrames = new StackFrame[size]; + } + + for (int i = startIndex(); i < size; i++) { + stackFrames[i] = new LiveStackFrameInfo(walker); + } + } + + @Override + StackFrame nextStackFrame() { + if (isEmpty()) { + throw new NoSuchElementException("origin=" + origin + " fence=" + fence); + } + + StackFrame frame = stackFrames[origin]; + origin++; + return frame; + } + } + + LiveStackInfoTraverser(StackWalker walker, + Function, ? extends T> function) { + super(walker, function, DEFAULT_MODE); + } + + @Override + protected void initFrameBuffer() { + this.frameBuffer = new Buffer(getNextBatchSize()); + } + } + + // Stack walk implementation classes to be excluded during stack walking + private final static List> stackWalkImplClasses = implClasses(); + + private static List> implClasses() { + Class[] innerClasses = StackStreamFactory.class.getDeclaredClasses(); + List> retVal = new ArrayList<>(innerClasses.length+2); + retVal.add(StackStreamFactory.class); + retVal.add(StackWalker.class); + for (Class clazz : innerClasses) { + retVal.add(clazz); + } + return retVal; + } + + private static boolean filterStackWalkImpl(Class clazz) { + return stackWalkImplClasses.contains(clazz) || + clazz.getName().startsWith("java.util.stream."); + } + + private static boolean isReflectionFrame(Class c) { + if (c.getName().startsWith("sun.reflect") && + !sun.reflect.MethodAccessor.class.isAssignableFrom(c)) { + throw new InternalError("Not sun.reflect.MethodAccessor: " + c.toString()); + } + // ## should filter all @Hidden frames? + return c == Method.class || + sun.reflect.MethodAccessor.class.isAssignableFrom(c) || + c.getName().startsWith("java.lang.invoke.LambdaForm"); + } + + private static boolean getProperty(String key, boolean value) { + String s = AccessController.doPrivileged(new PrivilegedAction<>() { + @Override + public String run() { + return System.getProperty(key); + } + }); + if (s != null) { + return Boolean.valueOf(s); + } + return value; + } +} --- /dev/null 2015-11-09 17:15:00.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/StackWalker.java 2015-11-09 17:15:00.000000000 -0800 @@ -0,0 +1,566 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package java.lang; + +import sun.reflect.CallerSensitive; + +import java.util.*; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Stream; + +/** + * A stack walker. + * + *

The {@link StackWalker#walk walk} method opens a sequential stream + * of {@link StackFrame StackFrame}s for the current thread and then applies + * the given function to walk the {@code StackFrame} stream. + * The stream reports stack frame elements in order, from the top most frame + * that represents the execution point at which the stack was generated to + * the bottom most frame. + * The {@code StackFrame} stream is closed when the {@code walk} method returns. + * If an attempt is made to reuse the closed stream, + * {@code IllegalStateException} will be thrown. + * + *

The {@linkplain Option stack walking options} of a + * {@code StackWalker} determines the information of + * {@link StackFrame StackFrame} objects to be returned. + * By default, stack frames of the reflection API and implementation + * classes are {@linkplain Option#SHOW_HIDDEN_FRAMES hidden} + * and {@code StackFrame}s have the class name and method name + * available but not the {@link StackFrame#getDeclaringClass() Class reference}. + * + *

A {@code StackWalker} object can be used to do multiple stack walks. + * A permission check is performed when a {@code StackWalker} is created, + * according to the options it requests. + * No further permission check is done at stack walking time. + * + * @apiNote + * Examples + * + *

1. To find the first caller filtering a known list of implementation class: + *

{@code
+ *     StackWalker walker = StackWalker.create(Option.RETAIN_CLASS_REFERENCE);
+ *     Optional> callerClass = walker.walk(s ->
+ *         s.map(StackFrame::getDeclaringClass)
+ *          .filter(interestingClasses::contains)
+ *          .findFirst());
+ * }
+ * + *

2. To snapshot the top 10 stack frames of the current thread, + *

{@code
+ *     List stack = StackWalker.create().walk(s ->
+ *         s.limit(10).collect(Collectors.toList()));
+ * }
+ * + * Unless otherwise noted, passing a {@code null} argument to a + * constructor or method in this {@code StackWalker} class + * will cause a {@link NullPointerException NullPointerException} + * to be thrown. + * + * @since 1.9 + */ +public final class StackWalker { + /** + * A {@code StackFrame} object represents a method invocation returned by + * {@link StackWalker}. + * + *

The {@link #getDeclaringClass()} method may be unsupported as determined + * by the {@linkplain Option stack walking options} of a {@linkplain + * StackWalker stack walker}. + * + * @since 1.9 + * @jvms 2.6 + */ + public static interface StackFrame { + /** + * Gets the binary name + * of the declaring class of the method represented by this stack frame. + * + * @return the binary name of the method represented + * by this stack frame + * + * @jls 13.1 The Form of a Binary + */ + public String getClassName(); + + /** + * Gets the name of the method represented by this stack frame. + * @return the name of the method represented by this stack frame + */ + public String getMethodName(); + + /** + * Gets the declaring {@code Class} for the method represented by + * this stack frame. + * + * @return the declaring {@code Class} of the method represented by + * this stack frame + * + * @throws UnsupportedOperationException if this {@code StackWalker} + * is not configured with {@link Option#RETAIN_CLASS_REFERENCE + * Option.RETAIN_CLASS_REFERENCE}. + */ + public Class getDeclaringClass(); + + /** + * Returns the name of the source file containing the execution point + * represented by this stack frame. Generally, this corresponds + * to the {@code SourceFile} attribute of the relevant {@code class} + * file as defined by The Java Virtual Machine Specification. + * In some systems, the name may refer to some source code unit + * other than a file, such as an entry in a source repository. + * + * @return the name of the file containing the execution point + * represented by this stack frame, or empty {@code Optional} + * is unavailable. + * + * @jvms 4.7.10 The {@code SourceFile} Attribute + */ + public Optional getFileName(); + + /** + * Returns the line number of the source line containing the execution + * point represented by this stack frame. Generally, this is + * derived from the {@code LineNumberTable} attribute of the relevant + * {@code class} file as defined by The Java Virtual Machine + * Specification. + * + * @return the line number of the source line containing the execution + * point represented by this stack frame, or empty + * {@code Optional} if this information is unavailable. + * + * @jvms 4.7.12 The {@code LineNumberTable} Attribute + */ + public OptionalInt getLineNumber(); + + /** + * Returns {@code true} if the method containing the execution point + * represented by this stack frame is a native method. + * + * @return {@code true} if the method containing the execution point + * represented by this stack frame is a native method. + */ + public boolean isNativeMethod(); + + /** + * Gets a {@code StackTraceElement} for this stack frame. + * + * @return {@code StackTraceElement} for this stack frame. + * + * */ + public default StackTraceElement toStackTraceElement() { + return new StackTraceElement(getClassName(), getMethodName(), + getFileName().orElse(null), + getLineNumber().orElse(-1)); + } + } + + /** + * Stack walker option to configure the {@linkplain StackFrame stack frame} + * information obtained by a {@code StackWalker}. + * + * @since 1.9 + */ + public enum Option { + /** + * Retains {@code Class} object in {@code StackFrame}s + * walked by this {@code StackWalker}. + * + *

A {@code StackWalker} configured with this option will support + * {@link StackWalker#getCallerClass()} and + * {@link StackFrame#getDeclaringClass() StackFrame.getDeclaringClass()}. + */ + RETAIN_CLASS_REFERENCE, + /** + * Shows all reflection frames. + * + *

By default, reflection frames are hidden. This includes the + * {@link java.lang.reflect.Method#invoke} method + * and the reflection implementation classes. A {@code StackWalker} with + * this {@code SHOW_REFLECT_FRAMES} option will show all reflection frames. + * The {@link #SHOW_HIDDEN_FRAMES} option can also be used to show all + * reflection frames and it will also show other hidden frames that + * are implementation-specific. + */ + SHOW_REFLECT_FRAMES, + /** + * Shows all hidden frames. + * + *

A Java Virtual Machine implementation may hide implementation + * specific frames in addition to {@linkplain #SHOW_REFLECT_FRAMES + * reflection frames}. A {@code StackWalker} with this {@code SHOW_HIDDEN_FRAMES} + * option will show all hidden frames (including reflection frames). + */ + SHOW_HIDDEN_FRAMES; + } + + enum ExtendedOption { + /** + * Obtain locals and operands. + */ + LOCALS_AND_OPERANDS + }; + + static final EnumSet

This {@code StackWalker} is configured to skip all + * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and + * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained. + * + * @return a {@code StackWalker} configured to skip all + * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and + * no {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained. + * + */ + public static StackWalker create() { + // no permission check needed + return DEFAULT_WALKER; + } + + /** + * Creates a {@code StackWalker} instance with the given option specifying + * the stack frame information it can access. + * + *

+ * If a security manager is present and the given {@code option} is + * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE}, + * it calls its {@link SecurityManager#checkPermission checkPermission} + * method for {@code StackFramePermission("retainClassReference")}. + * + * @param option {@link Option stack walking option} + * + * @return a {@code StackWalker} configured with the given option + * + * @throws SecurityException if a security manager exists and its + * {@code checkPermission} method denies access. + */ + public static StackWalker create(Option option) { + return create(EnumSet.of(Objects.requireNonNull(option))); + } + + /** + * Creates a {@code StackWalker} instance with the given {@ocde options} specifying + * the stack frame information it can access. If the given {@ocde options} + * is empty, this {@code StackWalker} is configured to skip all + * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} and no + * {@linkplain Option#RETAIN_CLASS_REFERENCE class reference} is retained. + * + *

+ * If a security manager is present and the given {@code option} is + * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE}, + * it calls its {@link SecurityManager#checkPermission checkPermission} + * method for {@code StackFramePermission("retainClassReference")}. + * + * @param options {@link Option stack walking option} + * + * @return a {@code StackWalker} configured with the given options + * + * @throws SecurityException if a security manager exists and its + * {@code checkPermission} method denies access. + */ + public static StackWalker create(Set

+ * If a security manager is present and the given {@code option} is + * {@link Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE}, + * it calls its {@link SecurityManager#checkPermission checkPermission} + * method for {@code StackFramePermission("retainClassReference")}. + * + *

+ * The {@code estimateDepth} specifies the estimate number of stack frames + * this {@code StackWalker} will traverse that the {@code StackWalker} could + * use as a hint for the buffer size. + * + * @param options {@link Option stack walking options} + * @param estimateDepth Estimate number of stack frames to be traversed. + * + * @return a {@code StackWalker} configured with the given options + * + * @throws IllegalArgumentException if {@code estimateDepth <= 0} + * @throws SecurityException if a security manager exists and its + * {@code checkPermission} method denies access. + */ + public static StackWalker create(Set

The {@code StackFrame} stream will be closed when + * this method returns. When a closed {@code Stream} object + * is reused, {@code IllegalStateException} will be thrown. + * + * @apiNote + * For example, to find the first 10 calling frames, first skipping those frames + * whose declaring class is in package {@code com.foo}: + *

+ *
{@code
+     * List frames = StackWalker.create().walk(s ->
+     *     s.dropWhile(f -> f.getClassName().startsWith("com.foo."))
+     *      .limit(10)
+     *      .collect(Collectors.toList()));
+     * }
+ * + *

This method takes a {@code Function} accepting a {@code Stream}, + * rather than returning a {@code Stream} and allowing the + * caller to directly manipulate the stream. The Java virtual machine is + * free to reorganize a thread's control stack, for example, via + * deoptimization. By taking a {@code Function} parameter, this method + * allows access to stack frames through a stable view of a thread's control + * stack. + * + *

Parallel execution is effectively disabled and stream pipeline + * execution will only occur on the current thread. + * + * @implNote The implementation stabilizes the stack by anchoring a frame + * specific to the stack walking and ensures that the stack walking is + * performed above the anchored frame. When the stream object is closed or + * being reused, {@code IllegalStateException} will be thrown. + * + * @param function a function that takes a stream of + * {@linkplain StackFrame stack frames} and returns a result. + * @param The type of the result of applying the function to the + * stream of {@linkplain StackFrame stack frame}. + * + * @return the result of applying the function to the stream of + * {@linkplain StackFrame stack frame}. + */ + @CallerSensitive + public T walk(Function, ? extends T> function) { + // Returning a Stream would be unsafe, as the stream could + // be used to access the stack frames in an uncontrolled manner. For + // example, a caller might pass a Spliterator of stack frames after one + // or more frames had been traversed. There is no robust way to detect + // whether the execution point when + // Spliterator.tryAdvance(java.util.function.Consumer) is + // invoked is the exact same execution point where the stack frame + // traversal is expected to resume. + + Objects.requireNonNull(function); + return StackStreamFactory.makeStackTraverser(this, function) + .walk(); + } + + /** + * Performs the given action on each element of {@code StackFrame} stream + * of the current thread, traversing from the top frame of the stack, + * which is the method calling this {@code forEach} method. + * + *

This method is equivalent to calling + *

+ * {@code walk(s -> { s.forEach(action); return null; });} + *
+ * + * @param action an action to be performed on each {@code StackFrame} + * of the stack of the current thread + */ + @CallerSensitive + public void forEach(Consumer action) { + Objects.requireNonNull(action); + StackStreamFactory.makeStackTraverser(this, s -> { + s.forEach(action); + return null; + }).walk(); + } + + /** + * + * Gets the {@code Class} object of the caller invoking the method + * that calls this {@code getCallerClass} method, if present; otherwise, + * this method returns an empty {@code Optional}. + * This is equivalent to calling + *
{@code
+     *     walk(s -> s.map(StackFrame::getDeclaringClass)
+     *                .skip(2)
+     *                .findFirst());
+     * }
+ * + * @apiNote + * For example, {@code ResourceBundleUtil::getBundle} loads a resource bundle + * on behalf of the caller. It calls this {@code getCallerClass} method + * to find the method calling {@code Util::getResourceBundle} and use the caller's + * class loader to load the resource bundle. The caller class in this example + * is the {@code MyTool} class. + * + *
{@code
+     *     class ResourceBundleUtil {
+     *         private final StackWalker walker = new StackWalker(EnumSet.of(Option.RETAIN_CLASS_REFERENCE));
+     *         public ResourceBundle getBundle(String bundleName) {
+     *             Class caller = walker.getCallerClass();
+     *             return ResourceBundle.getBundle(bundleName, caller.getClassLoader());
+     *         }
+     *     }
+     *
+     *     class MyTool {
+     *         private void init() {
+     *             ResourceBundle rb = Util.getResourceBundle("mybundle");
+     *         }
+     *     }
+     * }
+ * + *

If this {@code getCallerClass} method is called by the last frame + * on the stack, for example when this {@code getCallerClass} method is + * invoked from the {@code static main} entry point or + * a method called from a JNI attached thread, this method returns + * an empty {@code Optional} since the caller's class is not found. + * + * @return {@code Class} object of the caller's caller invoking this method; + * or an empty {@code Optional} if the caller's caller is not present. + * + * @throws UnsupportedOperationException if this {@code StackWalker} + * is not configured with {@link Option#RETAIN_CLASS_REFERENCE + * Option.RETAIN_CLASS_REFERENCE}. + */ + @CallerSensitive + public Optional> getCallerClass() { + if (!options.contains(Option.RETAIN_CLASS_REFERENCE)) { + throw new UnsupportedOperationException("This stack walker " + + "does not have RETAIN_CLASS_REFERENCE access"); + } + + return StackStreamFactory.makeCallerFinder(this).findCaller(); + } + + // ---- package access ---- + static StackWalker newInstanceNoCheck(EnumSet