--- old/make/jprt.properties 2015-11-24 12:23:33.000000000 -0800 +++ new/make/jprt.properties 2015-11-24 12:23:33.000000000 -0800 @@ -156,13 +156,13 @@ # Test target list (no fastdebug & limited c2 testing) my.test.target.set= \ - solaris_sparcv9_5.11-product-c2-TESTNAME, \ - solaris_x64_5.11-product-c2-TESTNAME, \ - linux_i586_2.6-product-{c1|c2}-TESTNAME, \ - linux_x64_2.6-product-c2-TESTNAME, \ - macosx_x64_10.9-product-c2-TESTNAME, \ - windows_i586_6.2-product-c1-TESTNAME, \ - windows_x64_6.2-product-c2-TESTNAME + solaris_sparcv9_5.11-{product|fastdebug}-c2-TESTNAME, \ + solaris_x64_5.11-{product|fastdebug}-c2-TESTNAME, \ + linux_i586_2.6-{product|fastdebug}-{c1|c2}-TESTNAME, \ + linux_x64_2.6-{product|fastdebug}-c2-TESTNAME, \ + macosx_x64_10.9-{product|fastdebug}-c2-TESTNAME, \ + windows_i586_6.2-{product|fastdebug}-c1-TESTNAME, \ + windows_x64_6.2-{product|fastdebug}-c2-TESTNAME # Default vm test targets (testset=default) my.test.targets.default= \ --- old/hotspot/make/share/makefiles/mapfile-vers 2015-11-24 12:23:34.000000000 -0800 +++ new/hotspot/make/share/makefiles/mapfile-vers 2015-11-24 12:23:34.000000000 -0800 @@ -7,6 +7,7 @@ JVM_ActiveProcessorCount; JVM_ArrayCopy; JVM_AssertionStatusDirectives; + JVM_CallStackWalk; JVM_ClassDepth; JVM_ClassLoaderDepth; JVM_Clone; @@ -36,6 +37,7 @@ JVM_DumpAllStacks; JVM_DumpThreads; JVM_FillInStackTrace; + JVM_FillStackFrames; JVM_FindClassFromCaller; JVM_FindClassFromClass; JVM_FindClassFromBootLoader; @@ -133,6 +135,7 @@ JVM_MonitorNotify; JVM_MonitorNotifyAll; JVM_MonitorWait; + JVM_MoreStackWalk; JVM_NanoTime; JVM_NativePath; JVM_NewArray; @@ -150,6 +153,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-24 12:23:34.000000000 -0800 +++ new/hotspot/src/share/vm/classfile/javaClasses.cpp 2015-11-24 12:23:34.000000000 -0800 @@ -1518,43 +1518,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. @@ -1676,7 +1644,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 @@ -1688,19 +1656,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) { @@ -1718,7 +1673,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); @@ -1733,7 +1688,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 { @@ -1802,8 +1757,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); } @@ -2090,8 +2045,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)); @@ -2114,6 +2069,7 @@ } Handle element = ik->allocate_instance_handle(CHECK_0); + // Fill in class name ResourceMark rm(THREAD); InstanceKlass* holder = InstanceKlass::cast(java_lang_Class::as_Klass(mirror())); @@ -2136,13 +2092,13 @@ 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); 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(); @@ -2155,6 +2111,108 @@ return create(mirror, method_id, method->constants()->version(), bci, cpref, THREAD); } +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 { + short mid = stackFrame->short_field(_mid_offset); + short version = stackFrame->short_field(_version_offset); + 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 { + short version = stackFrame->short_field(_version_offset); + return Backtrace::get_source_file_name(holder, version); + } +} + +void java_lang_StackFrameInfo::set_method_and_bci(Handle stackFrame, const methodHandle& method, int bci) { + // set Method* or mid/cpref + if (MemberNameInStackFrame) { + oop mname = stackFrame->obj_field(_memberName_offset); + InstanceKlass* ik = method->method_holder(); + CallInfo info(method(), ik); + MethodHandles::init_method_MemberName(mname, info); + } else { + int mid = method->orig_method_idnum(); + int cpref = method->name_index(); + assert((jushort)mid == mid, "mid should be short"); + assert((jushort)cpref == cpref, "cpref should be short"); + java_lang_StackFrameInfo::set_mid(stackFrame(), (short)mid); + java_lang_StackFrameInfo::set_cpref(stackFrame(), (short)cpref); + } + // set bci + java_lang_StackFrameInfo::set_bci(stackFrame(), bci); + // method may be redefined; store the version + int version = method->constants()->version(); + assert((jushort)version == version, "version should be short"); + java_lang_StackFrameInfo::set_version(stackFrame(), (short)version); +} + +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 = stackFrame->int_field(_bci_offset); + + // 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 { + // The method can be NULL if the requested class version is gone + if (sym == NULL) { + short cpref = stackFrame->short_field(_cpref_offset); + 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 the method has been redefined, the bci is no longer applicable + short version = stackFrame->short_field(_version_offset); + if (version_matches(method, version)) { + 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(_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()); + STACKFRAMEINFO_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET); +} + +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()); @@ -3471,6 +3529,18 @@ 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::_bci_offset; +int java_lang_StackFrameInfo::_methodName_offset; +int java_lang_StackFrameInfo::_fileName_offset; +int java_lang_StackFrameInfo::_lineNumber_offset; +int java_lang_StackFrameInfo::_mid_offset; +int java_lang_StackFrameInfo::_version_offset; +int java_lang_StackFrameInfo::_cpref_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; @@ -3500,6 +3570,50 @@ 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, short value) { + element->short_field_put(_mid_offset, value); +} + +void java_lang_StackFrameInfo::set_version(oop element, short value) { + element->short_field_put(_version_offset, value); +} + +void java_lang_StackFrameInfo::set_cpref(oop element, short value) { + element->short_field_put(_cpref_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. @@ -3633,6 +3747,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-24 12:23:36.000000000 -0800 +++ new/hotspot/src/share/vm/classfile/javaClasses.hpp 2015-11-24 12:23:35.000000000 -0800 @@ -1359,6 +1359,85 @@ }; +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(const methodHandle& method, int bci); + static Symbol* get_source_file_name(InstanceKlass* holder, int version); + + // Debugging + friend class JavaClasses; +}; + +// Interface to java.lang.StackFrameInfo objects + +#define STACKFRAMEINFO_INJECTED_FIELDS(macro) \ + macro(java_lang_StackFrameInfo, mid, short_signature, false) \ + macro(java_lang_StackFrameInfo, version, short_signature, false) \ + macro(java_lang_StackFrameInfo, cpref, short_signature, false) + +class java_lang_StackFrameInfo: AllStatic { +private: + static int _declaringClass_offset; + static int _memberName_offset; + static int _bci_offset; + static int _methodName_offset; + static int _fileName_offset; + static int _lineNumber_offset; + + static int _mid_offset; + static int _version_offset; + static int _cpref_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_method_and_bci(Handle stackFrame, const methodHandle& method, int bci); + static void set_bci(oop info, int value); + + // set method info in an instance of StackFrameInfo + static void fill_methodInfo(Handle info, TRAPS); + static void set_methodName(oop info, oop value); + static void set_fileName(oop info, oop value); + static void set_lineNumber(oop info, int value); + + // these injected fields are only used if -XX:-MemberNameInStackFrame set + static void set_mid(oop info, short value); + static void set_version(oop info, short value); + static void set_cpref(oop info, short value); + + static void compute_offsets(); + + // 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 class java_lang_AssertionStatusDirectives: AllStatic { @@ -1442,7 +1521,9 @@ CLASS_INJECTED_FIELDS(macro) \ CLASSLOADER_INJECTED_FIELDS(macro) \ MEMBERNAME_INJECTED_FIELDS(macro) \ - CALLSITECONTEXT_INJECTED_FIELDS(macro) + CALLSITECONTEXT_INJECTED_FIELDS(macro) \ + STACKFRAMEINFO_INJECTED_FIELDS(macro) + // Interface to hard-coded offset checking --- old/hotspot/src/share/vm/classfile/javaClasses.inline.hpp 2015-11-24 12:23:37.000000000 -0800 +++ new/hotspot/src/share/vm/classfile/javaClasses.inline.hpp 2015-11-24 12:23:37.000000000 -0800 @@ -73,4 +73,67 @@ 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(const 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); + // 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); +} + #endif // SHARE_VM_CLASSFILE_JAVACLASSES_INLINE_HPP --- old/hotspot/src/share/vm/classfile/systemDictionary.hpp 2015-11-24 12:23:38.000000000 -0800 +++ new/hotspot/src/share/vm/classfile/systemDictionary.hpp 2015-11-24 12:23:37.000000000 -0800 @@ -180,11 +180,17 @@ 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(StackWalker_klass, java_lang_StackWalker, Opt ) \ + do_klass(AbstractStackWalker_klass, java_lang_StackStreamFactory_AbstractStackWalker, Opt ) \ + 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-24 12:23:39.000000000 -0800 +++ new/hotspot/src/share/vm/classfile/vmSymbols.hpp 2015-11-24 12:23:38.000000000 -0800 @@ -311,6 +311,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, "") \ @@ -411,6 +427,18 @@ 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(cpref_name, "cpref") \ + template(version_name, "version") \ + 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") \ @@ -515,6 +543,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/memory/universe.cpp 2015-11-24 12:23:40.000000000 -0800 +++ new/hotspot/src/share/vm/memory/universe.cpp 2015-11-24 12:23:40.000000000 -0800 @@ -115,6 +115,7 @@ LatestMethodCache* Universe::_loader_addClass_cache = NULL; LatestMethodCache* Universe::_pd_implies_cache = NULL; LatestMethodCache* Universe::_throw_illegal_access_error_cache = NULL; +LatestMethodCache* Universe::_do_stack_walk_cache = NULL; oop Universe::_out_of_memory_error_java_heap = NULL; oop Universe::_out_of_memory_error_metaspace = NULL; oop Universe::_out_of_memory_error_class_metaspace = NULL; @@ -240,6 +241,7 @@ _loader_addClass_cache->serialize(f); _pd_implies_cache->serialize(f); _throw_illegal_access_error_cache->serialize(f); + _do_stack_walk_cache->serialize(f); } void Universe::check_alignment(uintx size, uintx alignment, const char* name) { @@ -674,6 +676,7 @@ Universe::_loader_addClass_cache = new LatestMethodCache(); Universe::_pd_implies_cache = new LatestMethodCache(); Universe::_throw_illegal_access_error_cache = new LatestMethodCache(); + Universe::_do_stack_walk_cache = new LatestMethodCache(); if (UseSharedSpaces) { // Read the data structures supporting the shared spaces (shared @@ -1048,6 +1051,17 @@ SystemDictionary::ProtectionDomain_klass(), m); } + // Setup method for stack walking + InstanceKlass::cast(SystemDictionary::AbstractStackWalker_klass())->link_class(CHECK_false); + m = InstanceKlass::cast(SystemDictionary::AbstractStackWalker_klass())-> + find_method(vmSymbols::doStackWalk_name(), + vmSymbols::doStackWalk_signature()); + // Allow NULL which should only happen with bootstrapping. + if (m != NULL) { + Universe::_do_stack_walk_cache->init( + SystemDictionary::AbstractStackWalker_klass(), m); + } + // This needs to be done before the first scavenge/gc, since // it's an input to soft ref clearing policy. { --- old/hotspot/src/share/vm/memory/universe.hpp 2015-11-24 12:23:41.000000000 -0800 +++ new/hotspot/src/share/vm/memory/universe.hpp 2015-11-24 12:23:41.000000000 -0800 @@ -149,6 +149,7 @@ static LatestMethodCache* _loader_addClass_cache; // method for registering loaded classes in class loader vector static LatestMethodCache* _pd_implies_cache; // method for checking protection domain attributes static LatestMethodCache* _throw_illegal_access_error_cache; // Unsafe.throwIllegalAccessError() method + static LatestMethodCache* _do_stack_walk_cache; // method for stack walker callback // preallocated error objects (no backtrace) static oop _out_of_memory_error_java_heap; @@ -314,6 +315,8 @@ static Method* protection_domain_implies_method() { return _pd_implies_cache->get_method(); } static Method* throw_illegal_access_error() { return _throw_illegal_access_error_cache->get_method(); } + static Method* do_stack_walk_method() { return _do_stack_walk_cache->get_method(); } + static oop null_ptr_exception_instance() { return _null_ptr_exception_instance; } static oop arithmetic_exception_instance() { return _arithmetic_exception_instance; } static oop virtual_machine_error_instance() { return _virtual_machine_error_instance; } --- old/hotspot/src/share/vm/prims/jvm.cpp 2015-11-24 12:23:42.000000000 -0800 +++ new/hotspot/src/share/vm/prims/jvm.cpp 2015-11-24 12:23:42.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, THREAD); +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, THREAD); +JVM_END + // java.lang.Object /////////////////////////////////////////////// --- old/hotspot/src/share/vm/prims/jvm.h 2015-11-24 12:23:43.000000000 -0800 +++ new/hotspot/src/share/vm/prims/jvm.h 2015-11-24 12:23:43.000000000 -0800 @@ -201,6 +201,37 @@ JVM_GetStackTraceElement(JNIEnv *env, jobject throwable, jint index); /* + * java.lang.StackWalker + */ +enum { + JVM_STACKWALK_FILL_CLASS_REFS_ONLY = 0x2, + JVM_STACKWALK_FILTER_FILL_IN_STACK_TRACE = 0x10, + JVM_STACKWALK_SHOW_HIDDEN_FRAMES = 0x20, + JVM_STACKWALK_FILL_LIVE_STACK_FRAMES = 0x100 +}; + +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 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-24 12:23:44.000000000 -0800 +++ new/hotspot/src/share/vm/runtime/globals.hpp 2015-11-24 12:23:44.000000000 -0800 @@ -3115,6 +3115,12 @@ "exceptions (0 means all)") \ range(0, max_jint/2) \ \ + develop(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-24 12:23:46.000000000 -0800 +++ new/hotspot/src/share/vm/runtime/vframe.hpp 2015-11-24 12:23:46.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-24 12:23:47.000000000 -0800 +++ new/jdk/make/mapfiles/libjava/mapfile-vers 2015-11-24 12:23:46.000000000 -0800 @@ -138,9 +138,14 @@ 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_checkStackWalkModes; + 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-24 12:23:48.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/System.java 2015-11-24 12:23:47.000000000 -0800 @@ -1896,12 +1896,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-24 12:23:49.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/Thread.java 2015-11-24 12:23:48.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-24 12:23:50.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/Throwable.java 2015-11-24 12:23:50.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-24 12:23:51.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/invoke/MemberName.java 2015-11-24 12:23:50.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/logger/SimpleConsoleLogger.java 2015-11-24 12:23:52.000000000 -0800 +++ new/jdk/src/java.base/share/classes/jdk/internal/logger/SimpleConsoleLogger.java 2015-11-24 12:23:51.000000000 -0800 @@ -31,13 +31,12 @@ import java.security.AccessController; import java.security.PrivilegedAction; import java.time.ZonedDateTime; +import java.util.Optional; import java.util.ResourceBundle; import java.util.function.Function; import java.lang.System.Logger; -import java.lang.System.Logger.Level; +import java.util.function.Predicate; import java.util.function.Supplier; -import jdk.internal.misc.JavaLangAccess; -import jdk.internal.misc.SharedSecrets; import sun.util.logging.PlatformLogger; import sun.util.logging.PlatformLogger.ConfigurableBridge.LoggerConfiguration; @@ -169,42 +168,55 @@ // 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; + Optional frame = new CallerFinder().get(); + if (frame.isPresent()) { + return frame.get().getClassName() + " " + frame.get().getMethodName(); + } else { + return name; + } + } + + /* + * CallerFinder is a stateful predicate. + */ + static final class CallerFinder implements Predicate { + static final StackWalker WALKER = StackWalker.getInstance(); - JavaLangAccess access = SharedSecrets.getJavaLangAccess(); - Throwable throwable = new Throwable(); - int depth = access.getStackTraceDepth(throwable); - - String logClassName = "sun.util.logging.PlatformLogger"; - String simpleLoggerClassName = "jdk.internal.logger.SimpleConsoleLogger"; - 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. - final StackTraceElement frame = - access.getStackTraceElement(throwable, ix); - final String cname = frame.getClassName(); + /** + * Returns StackFrame of the caller's frame. + * @return StackFrame 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) || cname.equals(simpleLoggerClassName)) { - lookingForLogger = false; - } - } else { - if (skipLoggingFrame(cname)) continue; - if (!cname.equals(logClassName) && !cname.equals(simpleLoggerClassName)) { - // We've found the relevant frame. - sourceClassName = cname; - sourceMethodName = frame.getMethodName(); - break; - } + lookingForLogger = !isLoggerImplFrame(cname); + return false; } + // We've found the relevant frame. + return !skipLoggingFrame(cname) && !isLoggerImplFrame(cname); } - if (sourceClassName != null) { - return sourceClassName + " " + sourceMethodName; - } else { - return name; + private boolean isLoggerImplFrame(String cname) { + return (cname.equals("sun.util.logging.PlatformLogger") || + cname.equals("jdk.internal.logger.SimpleConsoleLogger")); } } --- old/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangAccess.java 2015-11-24 12:23:53.000000000 -0800 +++ new/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangAccess.java 2015-11-24 12:23:53.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-24 12:23:54.000000000 -0800 +++ new/jdk/src/java.base/share/classes/jdk/internal/misc/SharedSecrets.java 2015-11-24 12:23:53.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,20 @@ return javaLangAccess; } + public static void setJavaLangInvokeAccess(JavaLangInvokeAccess jlia) { + javaLangInvokeAccess = jlia; + } + + public static JavaLangInvokeAccess getJavaLangInvokeAccess() { + if (javaLangInvokeAccess == null) { + try { + Class c = Class.forName("java.lang.invoke.MemberName"); + unsafe.ensureClassInitialized(c); + } catch (ClassNotFoundException e) {}; + } + return javaLangInvokeAccess; + } + public static void setJavaLangRefAccess(JavaLangRefAccess jlra) { javaLangRefAccess = jlra; } --- old/jdk/src/java.base/share/native/include/jvm.h 2015-11-24 12:23:55.000000000 -0800 +++ new/jdk/src/java.base/share/native/include/jvm.h 2015-11-24 12:23:54.000000000 -0800 @@ -178,6 +178,37 @@ JVM_GetStackTraceElement(JNIEnv *env, jobject throwable, jint index); /* + * java.lang.StackWalker + */ +enum { + JVM_STACKWALK_FILL_CLASS_REFS_ONLY = 0x2, + JVM_STACKWALK_FILTER_FILL_IN_STACK_TRACE = 0x10, + JVM_STACKWALK_SHOW_HIDDEN_FRAMES = 0x20, + JVM_STACKWALK_FILL_LIVE_STACK_FRAMES = 0x100 +}; + +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-24 12:23:56.000000000 -0800 +++ new/jdk/src/java.logging/share/classes/java/util/logging/LogRecord.java 2015-11-24 12:23:55.000000000 -0800 @@ -30,9 +30,8 @@ import java.util.concurrent.atomic.AtomicLong; import java.io.*; import java.time.Clock; +import java.util.function.Predicate; -import jdk.internal.misc.JavaLangAccess; -import jdk.internal.misc.SharedSecrets; import static jdk.internal.logger.SimpleConsoleLogger.skipLoggingFrame; /** @@ -661,42 +660,58 @@ // 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 logging/logger infrastructure and reflection calls - if (!skipLoggingFrame(cname)) { - // 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("sun.util.logging.PlatformLogger")); + /* + * CallerFinder is a stateful predicate. + */ + static final class CallerFinder implements Predicate { + static final StackWalker WALKER = StackWalker.getInstance(); + + /** + * Returns StackFrame of the caller's frame. + * @return StackFrame 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) { + // the log record could be created for a platform logger + lookingForLogger = !isLoggerImplFrame(cname); + return false; + } + // skip logging/logger infrastructure and reflection calls + return !skipLoggingFrame(cname); + } + + private boolean isLoggerImplFrame(String cname) { + return (cname.equals("java.util.logging.Logger") || + cname.startsWith("sun.util.logging.PlatformLogger")); + } } } --- /dev/null 2015-11-24 12:23:57.000000000 -0800 +++ new/hotspot/src/share/vm/prims/stackwalk.cpp 2015-11-24 12:23:56.000000000 -0800 @@ -0,0 +1,470 @@ +/* + * 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" + +// setup and cleanup actions +void StackWalkAnchor::setup_magic_on_entry(objArrayHandle classes_array) { + classes_array->obj_at_put(magic_pos, _thread->threadObj()); + _anchor = address_value(); + assert(check_magic(classes_array), "invalid magic"); +} + +bool StackWalkAnchor::check_magic(objArrayHandle classes_array) { + oop m1 = classes_array->obj_at(magic_pos); + jlong m2 = _anchor; + if (m1 == _thread->threadObj() && m2 == address_value()) return true; + return false; +} + +bool StackWalkAnchor::cleanup_magic_on_exit(objArrayHandle classes_array) { + bool ok = check_magic(classes_array); + classes_array->obj_at_put(magic_pos, NULL); + _anchor = 0L; + return ok; +} + +// Returns StackWalkAnchor for the current stack being traversed. +// +// Parameters: +// thread Current Java thread. +// magic Magic value used for each stack walking +// 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(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, classes_array)) 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. +// +// Parameters: +// mode Restrict which frames to be decoded. +// vfst vFrameStream. +// max_nframes Maximum number of frames to be filled. +// start_index Start index to the user-supplied buffers. +// classes_array Buffer to store classes in, starting at start_index. +// frames_array Buffer to store StackFrame in, starting at start_index. +// NULL if not used. +// end_index End index to the user-supplied buffers with unpacked frames. +// +// Returns the number of frames whose information was transferred into the buffers. +// +int StackWalk::fill_in_frames(jlong mode, vframeStream& vfst, + int max_nframes, int start_index, + objArrayHandle classes_array, + objArrayHandle frames_array, + int& end_index, TRAPS) { + if (TraceStackWalk) { + tty->print_cr("fill_in_frames limit=%d start=%d frames length=%d", + max_nframes, start_index, classes_array->length()); + } + assert(max_nframes > 0, "invalid max_nframes"); + assert(start_index + max_nframes <= 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(); + tty->print("\n"); + } + 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 (live_frame_info(mode)) { + Handle stackFrame(frames_array->obj_at(index)); + fill_live_stackframe(stackFrame, method, bci, vfst.java_frame(), CHECK_0); + } else if (need_method_info(mode)) { + Handle stackFrame(frames_array->obj_at(index)); + fill_stackframe(stackFrame, method, bci); + } + if (++frames_decoded >= max_nframes) 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 = NULL; + + // ## 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: + // put a non-null slot + args.push_int(0); + signature = vmSymbols::asPrimitive_int_signature(); + break; + + 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) { + objArrayHandle empty; + int length = values->size(); + objArrayOop array_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(), + length, CHECK_(empty)); + 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_(empty)); + 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; +} + +// Fill StackFrameInfo with declaringClass and bci and initialize memberName +void StackWalk::fill_stackframe(Handle stackFrame, const methodHandle& method, int bci) { + java_lang_StackFrameInfo::set_declaringClass(stackFrame(), method->method_holder()->java_mirror()); + java_lang_StackFrameInfo::set_method_and_bci(stackFrame(), method, bci); +} + +// Fill LiveStackFrameInfo with locals, monitors, and expressions +void StackWalk::fill_live_stackframe(Handle stackFrame, const methodHandle& method, + int bci, javaVFrame* jvf, TRAPS) { + fill_stackframe(stackFrame, method, bci); + 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()); + } + } +} + +// Begins stack walking. +// +// Parameters: +// stackStream StackStream object +// mode Stack walking mode. +// skip_frames Number of frames to be skipped. +// frame_count Number of frames to be traversed. +// start_index Start index to the user-supplied buffers. +// classes_array Buffer to store classes in, starting at start_index. +// frames_array Buffer to store StackFrame in, starting at start_index. +// NULL if not used. +// +// Returns Object returned from AbstractStackWalker::doStackWalk call. +// +oop StackWalk::walk(Handle stackStream, jlong mode, + int skip_frames, int frame_count, int start_index, + objArrayHandle classes_array, + objArrayHandle frames_array, + TRAPS) { + 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", NULL); + } + } + + Klass* stackWalker_klass = SystemDictionary::StackWalker_klass(); + Klass* abstractStackWalker_klass = SystemDictionary::AbstractStackWalker_klass(); + + methodHandle m_doStackWalk(THREAD, Universe::do_stack_walk_method()); + + // Open up a traversable stream onto my stack. + // This stream will be made available by *reference* to the inner Java call. + StackWalkAnchor anchor(jt); + 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 = fill_in_frames(mode, vfst, frame_count, start_index, classes_array, + frames_array, end_index, CHECK_NULL); + if (numFrames < 1) { + THROW_MSG_(vmSymbols::java_lang_InternalError(), "stack walk: decode failed", NULL); + } + } + + // JVM_CallStackWalk walks the stack and fills in stack frames, then calls to + // Java method java.lang.StackStreamFactory.AbstractStackWalker::doStackWalk + // which calls the implementation to consume the stack frames. + // When JVM_CallStackWalk returns, it invalidates the stack stream. + 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(classes_array); + + 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(classes_array); + + // Throw pending exception if we must + (void) (CHECK_NULL); + + if (!ok) { + THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: corrupted buffers on exit", NULL); + } + + // Return normally + return (oop)result.get_jobject(); + +} + +// Walk the next batch of stack frames +// +// Parameters: +// stackStream StackStream object +// mode Stack walking mode. +// magic Must be valid value to continue the stack walk +// frame_count Number of frames to be decoded. +// start_index Start index to the user-supplied buffers. +// classes_array Buffer to store classes in, starting at start_index. +// frames_array Buffer to store StackFrame in, starting at start_index. +// NULL if not used. +// +// Returns the end index of frame filled in the buffer. +// +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(); // this was the last frame decoded in the previous batch + if (!vfst.at_end()) { + int n = fill_in_frames(mode, vfst, 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-24 12:23:57.000000000 -0800 +++ new/hotspot/src/share/vm/prims/stackwalk.hpp 2015-11-24 12:23:57.000000000 -0800 @@ -0,0 +1,102 @@ +/* + * 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 { +private: + enum { + magic_pos = 0 + }; + + JavaThread* _thread; + vframeStream _vfst; + jlong _anchor; +public: + StackWalkAnchor(JavaThread* thread) + : _thread(thread), _vfst(thread), _anchor(0L) {} + + vframeStream& vframe_stream() { return _vfst; } + JavaThread* thread() { return _thread; } + + void setup_magic_on_entry(objArrayHandle classes_array); + bool check_magic(objArrayHandle classes_array); + bool cleanup_magic_on_exit(objArrayHandle classes_array); + + bool is_valid_in(Thread* thread, objArrayHandle classes_array) { + return (_thread == thread && check_magic(classes_array)); + } + + jlong address_value() { + return (jlong) castable_address(this); + } + + static StackWalkAnchor* from_current(JavaThread* thread, jlong anchor, objArrayHandle frames_array); +}; + +class StackWalk : public AllStatic { +private: + static int fill_in_frames(jlong mode, vframeStream& vfst, + int max_nframes, int start_index, + objArrayHandle classes_array, + objArrayHandle frames_array, + int& end_index, TRAPS); + + static void fill_stackframe(Handle stackFrame, const methodHandle& method, int bci); + + static void fill_live_stackframe(Handle stackFrame, const methodHandle& method, int bci, + javaVFrame* jvf, TRAPS); + + static inline bool skip_hidden_frames(int mode) { + return (mode & JVM_STACKWALK_SHOW_HIDDEN_FRAMES) == 0; + } + static inline bool need_method_info(int mode) { + return (mode & JVM_STACKWALK_FILL_CLASS_REFS_ONLY) == 0; + } + static inline bool live_frame_info(int mode) { + return (mode & JVM_STACKWALK_FILL_LIVE_STACK_FRAMES) != 0; + } + static inline bool fill_in_stacktrace(int mode) { + return (mode & JVM_STACKWALK_FILTER_FILL_IN_STACK_TRACE) != 0; + } + +public: + static oop 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); +}; +#endif // SHARE_VM_PRIMS_STACKWALK_HPP --- /dev/null 2015-11-24 12:23:58.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/LiveStackFrame.java 2015-11-24 12:23:58.000000000 -0800 @@ -0,0 +1,226 @@ +/* + * 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; +import java.util.EnumSet; +import java.util.Set; + +import static java.lang.StackWalker.ExtendedOption.LOCALS_AND_OPERANDS; + +/** + * 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}. + * + * @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. + * + * @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 abstract class 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 + */ + abstract 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. + */ + public 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. + */ + public 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. + */ + public 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. + */ + public 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. + */ + public 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. + */ + public 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. + */ + public 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. + */ + public double doubleValue() { + throw new UnsupportedOperationException("this primitive of type " + type()); + } + } + + + /** + * 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(StackWalker.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. + * + * @param options stack walk {@link StackWalker.Option options} + * + * @throws SecurityException if the security manager is present and + * it denies access to {@code RuntimePermission("liveStackFrames")}; or + * or if the given {@code options} contains + * {@link StackWalker.Option#RETAIN_CLASS_REFERENCE Option.RETAIN_CLASS_REFERENCE} + * and it denies access to {@code StackFramePermission("retainClassReference")}. + */ + public static StackWalker getStackWalker(Set options) { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new RuntimePermission("liveStackFrames")); + } + return StackWalker.newInstance(options, LOCALS_AND_OPERANDS); + } +} --- /dev/null 2015-11-24 12:23:59.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/LiveStackFrameInfo.java 2015-11-24 12:23:59.000000000 -0800 @@ -0,0 +1,271 @@ +/* + * 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]; + + LiveStackFrameInfo(StackWalker walker) { + super(walker); + } + + // These fields are initialized by the VM if ExtendedOption.LOCALS_AND_OPERANDS is set + private Object[] monitors = EMPTY_ARRAY; + private Object[] locals = EMPTY_ARRAY; + private Object[] operands = EMPTY_ARRAY; + + @Override + public Object[] getMonitors() { + return monitors; + } + + @Override + public Object[] getLocals() { + return locals; + } + + @Override + public Object[] getStack() { + return operands; + } + + /* + * Convert primitive value to {@code Primitive} object to represent + * a local variable or an element on the operand stack of primitive type. + */ + static PrimitiveValue asPrimitive(boolean value) { + return new BooleanPrimitive(value); + } + + static PrimitiveValue asPrimitive(int value) { + return new IntPrimitive(value); + } + + static PrimitiveValue asPrimitive(short value) { + return new ShortPrimitive(value); + } + + static PrimitiveValue asPrimitive(char value) { + return new CharPrimitive(value); + } + + static PrimitiveValue asPrimitive(byte value) { + return new BytePrimitive(value); + } + + static PrimitiveValue asPrimitive(long value) { + return new LongPrimitive(value); + } + + static PrimitiveValue asPrimitive(float value) { + return new FloatPrimitive(value); + } + + static PrimitiveValue asPrimitive(double value) { + return new DoublePrimitive(value); + } + + private static class IntPrimitive extends PrimitiveValue { + final int value; + IntPrimitive(int value) { + this.value = value; + } + + @Override + public char type() { + return 'I'; + } + + @Override + public int intValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private static class ShortPrimitive extends PrimitiveValue { + final short value; + ShortPrimitive(short value) { + this.value = value; + } + + @Override + public char type() { + return 'S'; + } + + @Override + public short shortValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private static class BooleanPrimitive extends PrimitiveValue { + final boolean value; + BooleanPrimitive(boolean value) { + this.value = value; + } + + @Override + public char type() { + return 'Z'; + } + + @Override + public boolean booleanValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private static class CharPrimitive extends PrimitiveValue { + final char value; + CharPrimitive(char value) { + this.value = value; + } + + @Override + public char type() { + return 'C'; + } + + @Override + public char charValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private static class BytePrimitive extends PrimitiveValue { + final byte value; + BytePrimitive(byte value) { + this.value = value; + } + + @Override + public char type() { + return 'B'; + } + + @Override + public byte byteValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private static class LongPrimitive extends PrimitiveValue { + final long value; + LongPrimitive(long value) { + this.value = value; + } + + @Override + public char type() { + return 'J'; + } + + @Override + public long longValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private static class FloatPrimitive extends PrimitiveValue { + final float value; + FloatPrimitive(float value) { + this.value = value; + } + + @Override + public char type() { + return 'F'; + } + + @Override + public float floatValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } + + private static class DoublePrimitive extends PrimitiveValue { + final double value; + DoublePrimitive(double value) { + this.value = value; + } + + @Override + public char type() { + return 'D'; + } + + @Override + public double doubleValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + } +} --- /dev/null 2015-11-24 12:24:00.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/StackFrameInfo.java 2015-11-24 12:24:00.000000000 -0800 @@ -0,0 +1,136 @@ +/* + * 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 jdk.internal.misc.JavaLangInvokeAccess; +import jdk.internal.misc.SharedSecrets; + +import static java.lang.StackWalker.Option.*; +import java.lang.StackWalker.StackFrame; +import java.util.Optional; +import java.util.OptionalInt; + +class StackFrameInfo implements StackFrame { + private final static JavaLangInvokeAccess jlInvokeAccess = + SharedSecrets.getJavaLangInvokeAccess(); + + // -XX:+MemberNameInStackFrame will initialize MemberName and all other fields; + // otherwise, VM will set the hidden fields (injected by the VM). + // -XX:+MemberNameInStackFrame is temporary to enable performance measurement + // + // Footprint improvement: MemberName::clazz and MemberName::name + // can replace StackFrameInfo::declaringClass and StackFrameInfo::methodName + // Currently VM sets StackFrameInfo::methodName instead of expanding MemberName::name + + final StackWalker walker; + final Class declaringClass; + final Object memberName; + final int bci; + + // methodName, fileName, and lineNumber will be lazily set by the VM + // when first requested. + private String methodName; + private String fileName = null; // default for unavailable filename + private int lineNumber = -1; // default for unavailable lineNumber + + /* + * Create StackFrameInfo for StackFrameTraverser and LiveStackFrameTraverser + * to use + */ + StackFrameInfo(StackWalker walker) { + this.walker = walker; + this.declaringClass = null; + this.bci = -1; + this.memberName = jlInvokeAccess.newMemberName(); + } + + @Override + public String getClassName() { + return declaringClass.getName(); + } + + @Override + public Class getDeclaringClass() { + walker.ensureAccessEnabled(RETAIN_CLASS_REFERENCE); + return declaringClass; + } + + // Call the VM to set methodName, lineNumber, and fileName + private synchronized void ensureMethodInfoInitialized() { + if (methodName == null) { + setMethodInfo(); + } + } + + @Override + public String getMethodName() { + ensureMethodInfoInitialized(); + return methodName; + } + + @Override + public Optional getFileName() { + ensureMethodInfoInitialized(); + return fileName != null ? Optional.of(fileName) : Optional.empty(); + } + + @Override + public OptionalInt getLineNumber() { + ensureMethodInfoInitialized(); + return lineNumber > 0 ? OptionalInt.of(lineNumber) : OptionalInt.empty(); + } + + @Override + public boolean isNativeMethod() { + ensureMethodInfoInitialized(); + return lineNumber == -2; + } + + @Override + public String toString() { + ensureMethodInfoInitialized(); + // similar format as StackTraceElement::toString + if (isNativeMethod()) { + return getClassName() + "." + getMethodName() + "(Native Method)"; + } else { + // avoid allocating Optional objects + return getClassName() + "." + getMethodName() + + "(" + (fileName != null ? fileName : "Unknown Source") + + (lineNumber > 0 ? ":" + lineNumber : " bci:" + bci) + ")"; + } + } + + /** + * Lazily initialize method name, file name, line number + */ + private native void setMethodInfo(); + + /** + * Fill in source file name and line number of the given StackFrame array. + */ + static native void fillInStackFrames(int startIndex, + Object[] stackframes, + int fromIndex, int toIndex); +} --- /dev/null 2015-11-24 12:24:01.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/StackFramePermission.java 2015-11-24 12:24:01.000000000 -0800 @@ -0,0 +1,50 @@ +/* + * 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; + +/** + * Permission to access {@link StackWalker.StackFrame}. + * + * @see java.lang.StackWalker.Option#RETAIN_CLASS_REFERENCE + * @see StackWalker.StackFrame#getDeclaringClass() + */ +public class StackFramePermission extends java.security.BasicPermission { + private static final long serialVersionUID = 2841894854386706014L; + + /** + * Creates a new {@code StackFramePermission} object. + * + * @param name Permission name. Must be "retainClassReference". + * + * @throws IllegalArgumentException if {@code name} is invalid. + * @throws NullPointerException if {@code name} is {@code null}. + */ + public StackFramePermission(String name) { + super(name); + if (!name.equals("retainClassReference")) { + throw new IllegalArgumentException("name: " + name); + } + } +} --- /dev/null 2015-11-24 12:24:02.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/StackStreamFactory.java 2015-11-24 12:24:01.000000000 -0800 @@ -0,0 +1,1106 @@ +/* + * 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.misc.VM; + +import java.io.PrintStream; +import java.lang.StackWalker.Option; +import java.lang.StackWalker.StackFrame; + +import java.lang.annotation.Native; +import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.Spliterator; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +import static java.lang.StackStreamFactory.WalkerState.*; + +/** + * StackStreamFactory class provides static factory methods + * to get different kinds of stack walker/traverser. + * + * AbstractStackWalker provides the basic stack walking support + * fetching stack frames from VM in batches. + * + * AbstractStackWalker subclass is specialized for a specific kind of stack traversal + * to avoid overhead of Stream/Lambda + * 1. Support traversing Stream + * 2. StackWalker::getCallerClass + * 3. Throwable::init and Throwable::getStackTrace + * 4. AccessControlContext getting ProtectionDomain + */ +final class StackStreamFactory { + private StackStreamFactory() {} + + // Stack walk implementation classes to be excluded during stack walking + // lazily add subclasses when they are loaded. + private final static Set> stackWalkImplClasses = init(); + + private static final int SMALL_BATCH = 8; + private static final int BATCH_SIZE = 32; + private static final int LARGE_BATCH_SIZE = 256; + private static final int MIN_BATCH_SIZE = SMALL_BATCH; + + // These flags must match the values maintained in the VM + @Native private static final int DEFAULT_MODE = 0x0; + @Native private static final int FILL_CLASS_REFS_ONLY = 0x2; + @Native private static final int FILTER_FILL_IN_STACKTRACE = 0x10; + @Native private static final int SHOW_HIDDEN_FRAMES = 0x20; // LambdaForms are hidden by the VM + @Native private static final int FILL_LIVE_STACK_FRAMES = 0x100; + + /* + * For Throwable to use StackWalker, set useNewThrowable to true. + * Performance work and extensive testing is needed to replace the + * VM built-in backtrace filled in Throwable with the StackWalker. + */ + final static boolean useNewThrowable = getProperty("stackwalk.newThrowable", false); + final static boolean isDebug = getProperty("stackwalk.debug", false); + + static StackFrameTraverser + makeStackTraverser(StackWalker walker, Function, ? extends T> function) + { + if (walker.hasLocalsOperandsOption()) + return new LiveStackInfoTraverser(walker, function); + else + return new StackFrameTraverser(walker, function); + } + + /** + * Gets a stack stream to find caller class. + */ + static CallerClassFinder makeCallerFinder(StackWalker walker) { + return new CallerClassFinder(walker); + } + + static boolean useStackTrace(Throwable t) { + if (t instanceof VirtualMachineError) + return false; + + return VM.isBooted() && StackStreamFactory.useNewThrowable; + } + + /* + * This should only be used by Throwable::. + */ + static StackTrace makeStackTrace(Throwable ex) { + return StackTrace.dump(ex); + } + + /* + * This creates StackTrace for Thread::dumpThread to use. + */ + static StackTrace makeStackTrace() { + return StackTrace.dump(); + } + + enum WalkerState { + NEW, // the stream is new and stack walking has not started + OPEN, // the stream is open when it is being traversed. + CLOSED; // the stream is closed when the stack walking is done + } + + static abstract class AbstractStackWalker { + protected final StackWalker walker; + protected final Thread thread; + protected final int maxDepth; + protected final long mode; + protected int depth; // traversed stack depth + protected FrameBuffer frameBuffer; // buffer for VM to fill in + protected long anchor; + + // buffers to fill in stack frame information + protected AbstractStackWalker(StackWalker walker, int mode) { + this(walker, mode, Integer.MAX_VALUE); + } + protected AbstractStackWalker(StackWalker walker, int mode, int maxDepth) { + this.thread = Thread.currentThread(); + this.mode = toStackWalkMode(walker, mode); + this.walker = walker; + this.maxDepth = maxDepth; + this.depth = 0; + } + + private int toStackWalkMode(StackWalker walker, int mode) { + int newMode = mode; + if (walker.hasOption(Option.SHOW_HIDDEN_FRAMES) && + !fillCallerClassOnly(newMode) /* don't show hidden frames for getCallerClass */) + newMode |= SHOW_HIDDEN_FRAMES; + if (walker.hasLocalsOperandsOption()) + newMode |= FILL_LIVE_STACK_FRAMES; + return newMode; + } + + private boolean fillCallerClassOnly(int mode) { + return (mode|FILL_CLASS_REFS_ONLY) != FILL_CLASS_REFS_ONLY; + } + /** + * A callback method to consume the stack frames. This method is invoked + * once stack walking begins (i.e. it is only invoked when walkFrames is called). + * + * Each specialized AbstractStackWalker subclass implements the consumeFrames method + * to control the following: + * 1. fetch the subsequent batches of stack frames + * 2. reuse or expand the allocated buffers + * 3. create specialized StackFrame objects + * + * @return the number of consumed frames + */ + protected abstract T consumeFrames(); + + /** + * Initialize FrameBuffer. Subclass should implement this method to + * create its custom frame buffers. + */ + protected abstract void initFrameBuffer(); + + /** + * Returns the suggested next batch size. + * + * Subclass should override this method to change the batch size + * + * @param lastBatchFrameCount number of frames in the last batch; or zero + * @return suggested batch size + */ + protected abstract int batchSize(int lastBatchFrameCount); + + /* + * Returns the next batch size, always >= minimum batch size (32) + * + * Subclass may override this method if the minimum batch size is different. + */ + protected int getNextBatchSize() { + int lastBatchSize = depth == 0 ? 0 : frameBuffer.curBatchFrameCount(); + int nextBatchSize = batchSize(lastBatchSize); + if (isDebug) { + System.err.println("last batch size = " + lastBatchSize + + " next batch size = " + nextBatchSize); + } + return nextBatchSize >= MIN_BATCH_SIZE ? nextBatchSize : MIN_BATCH_SIZE; + } + + /* + * Checks if this stream is in the given state. Otherwise, throws IllegalStateException. + * + * VM also validates this stream if it's anchored for stack walking + * when stack frames are fetched for each batch. + */ + final void checkState(WalkerState state) { + if (thread != Thread.currentThread()) { + throw new IllegalStateException("Invalid thread walking this stack stream: " + + Thread.currentThread().getName() + " " + thread.getName()); + } + switch (state) { + case NEW: + if (this.anchor != 0) { + throw new IllegalStateException("This stack stream is being reused."); + } + break; + case OPEN: + if (this.anchor == 0 || this.anchor == -1L) { + throw new IllegalStateException("This stack stream is not valid for walking: " + anchor); + } + break; + case CLOSED: + if (this.anchor != -1L) { + throw new IllegalStateException("This stack stream is not closed."); + } + } + } + + /* + * Close this stream. This stream becomes invalid to walk. + */ + private void close() { + this.anchor = -1L; + } + + /* + * Walks stack frames until {@link #consumeFrames} is done consuming + * the frames it is interested in. + */ + final T walk() { + checkState(NEW); + try { + // VM will need to stablize the stack before walking. It will invoke + // the AbstractStackWalker::doStackWalk method once it fetches the first batch. + // the callback will be invoked within the scope of the callStackWalk frame. + return beginStackWalk(); + } finally { + close(); // done traversal; close the stream + } + } + + private boolean skipReflectionFrames() { + return !walker.hasOption(Option.SHOW_REFLECT_FRAMES) && + !walker.hasOption(Option.SHOW_HIDDEN_FRAMES); + } + + /* + * Returns {@code Class} object at the current frame; + * or {@code null} if no more frame. If advanceToNextBatch is true, + * it will only fetch the next batch. + */ + final Class peekFrame() { + while (frameBuffer.isActive() && depth < maxDepth) { + if (frameBuffer.isEmpty()) { + // fetch another batch of stack frames + getNextBatch(); + } else { + Class c = frameBuffer.get(); + if (skipReflectionFrames() && isReflectionFrame(c)) { + if (isDebug) + System.err.println(" skip: frame " + frameBuffer.getIndex() + " " + c); + + frameBuffer.next(); + depth++; + continue; + } else { + return c; + } + } + } + return null; + } + + /* + * This method is only invoked by VM. + * + * It will invoke the consumeFrames method to start the stack walking + * with the first batch of stack frames. Each specialized AbstractStackWalker + * subclass implements the consumeFrames method to control the following: + * 1. fetch the subsequent batches of stack frames + * 2. reuse or expand the allocated buffers + * 3. create specialized StackFrame objects + */ + private Object doStackWalk(long anchor, int skipFrames, int batchSize, + int bufStartIndex, int bufEndIndex) { + checkState(NEW); + + frameBuffer.check(skipFrames); + + if (isDebug) { + System.err.format("doStackWalk: skip %d start %d end %d%n", + skipFrames, bufStartIndex, bufEndIndex); + } + + this.anchor = anchor; // set anchor for this bulk stack frame traversal + frameBuffer.setBatch(bufStartIndex, bufEndIndex); + + // traverse all frames and perform the action on the stack frames, if specified + return consumeFrames(); + } + + /* + * Get next batch of stack frames. + */ + private int getNextBatch() { + int nextBatchSize = Math.min(maxDepth - depth, getNextBatchSize()); + if (!frameBuffer.isActive() || nextBatchSize <= 0) { + if (isDebug) { + System.out.format(" more stack walk done%n"); + } + frameBuffer.freeze(); // stack walk done + return 0; + } + + return fetchStackFrames(nextBatchSize); + } + + /* + * This method traverses the next stack frame and returns the Class + * invoking that stack frame. + * + * This method can only be called during the walk method. This is intended + * to be used to walk the stack frames in one single invocation and + * this stack stream will be invalidated once walk is done. + * + * @see #tryNextFrame + */ + final Class nextFrame() { + if (!hasNext()) { + return null; + } + + Class c = frameBuffer.next(); + depth++; + return c; + } + + /* + * Returns true if there is next frame to be traversed. + * This skips hidden frames unless this StackWalker has + * {@link Option#SHOW_REFLECT_FRAMES} + */ + final boolean hasNext() { + return peekFrame() != null; + } + + /** + * Begin stack walking - pass the allocated arrays to the VM to fill in + * stack frame information. + * + * VM first anchors the frame of the current thread. A traversable stream + * on this thread's stack will be opened. The VM will fetch the first batch + * of stack frames and call AbstractStackWalker::doStackWalk to invoke the + * stack walking function on each stack frame. + * + * If all fetched stack frames are traversed, AbstractStackWalker::fetchStackFrames will + * fetch the next batch of stack frames to continue. + */ + private T beginStackWalk() { + // initialize buffers for VM to fill the stack frame info + initFrameBuffer(); + + return callStackWalk(mode, 0, + frameBuffer.curBatchFrameCount(), + frameBuffer.startIndex(), + frameBuffer.classes, + frameBuffer.stackFrames); + } + + /* + * Fetches stack frames. + * + * @params batchSize number of elements of the frame buffers for this batch + * @returns number of frames fetched in this batch + */ + private int fetchStackFrames(int batchSize) { + int startIndex = frameBuffer.startIndex(); + frameBuffer.resize(startIndex, batchSize); + + int endIndex = fetchStackFrames(mode, anchor, batchSize, + startIndex, + frameBuffer.classes, + frameBuffer.stackFrames); + if (isDebug) { + System.out.format(" more stack walk requesting %d got %d to %d frames%n", + batchSize, frameBuffer.startIndex(), endIndex); + } + int numFrames = endIndex - startIndex; + if (numFrames == 0) { + frameBuffer.freeze(); // done stack walking + } else { + frameBuffer.setBatch(startIndex, endIndex); + } + return numFrames; + } + + /** + * Begins stack walking. This method anchors this frame and invokes + * AbstractStackWalker::doStackWalk after fetching the firt batch of stack frames. + * + * @param mode mode of stack walking + * @param skipframes number of frames to be skipped before filling the frame buffer. + * @param batchSize the batch size, max. number of elements to be filled in the frame buffers. + * @param startIndex start index of the frame buffers to be filled. + * @param classes Classes buffer of the stack frames + * @param frames StackFrame buffer, or null + * @return Result of AbstractStackWalker::doStackWalk + */ + private native T callStackWalk(long mode, int skipframes, + int batchSize, int startIndex, + Class[] classes, + StackFrame[] frames); + + /** + * Fetch the next batch of stack frames. + * + * @param mode mode of stack walking + * @param anchor + * @param batchSize the batch size, max. number of elements to be filled in the frame buffers. + * @param startIndex start index of the frame buffers to be filled. + * @param classes Classes buffer of the stack frames + * @param frames StackFrame buffer, or null + * + * @return the end index to the frame buffers + */ + private native int fetchStackFrames(long mode, long anchor, + int batchSize, int startIndex, + Class[] classes, + StackFrame[] frames); + + + /* + * Frame buffer + * + * Each specialized AbstractStackWalker subclass may subclass the FrameBuffer. + */ + class FrameBuffer { + static final int START_POS = 2; // 0th and 1st elements are reserved + + // buffers for VM to fill stack frame info + int currentBatchSize; // current batch size + Class[] classes; // caller class for fast path + + StackFrame[] stackFrames; + + int origin; // index to the current traversed stack frame + int fence; // index to the last frame in the current batch + + FrameBuffer(int initialBatchSize) { + if (initialBatchSize < MIN_BATCH_SIZE) { + throw new IllegalArgumentException(initialBatchSize + " < minimum batch size: " + MIN_BATCH_SIZE); + } + this.origin = START_POS; + this.fence = 0; + this.currentBatchSize = initialBatchSize; + this.classes = new Class[currentBatchSize]; + } + + int curBatchFrameCount() { + return currentBatchSize-START_POS; + } + + /* + * Tests if this frame buffer is empty. All frames are fetched. + */ + final boolean isEmpty() { + return origin >= fence || (origin == START_POS && fence == 0); + } + + /* + * Freezes this frame buffer. The stack stream source is done fetching. + */ + final void freeze() { + origin = 0; + fence = 0; + } + + /* + * Tests if this frame buffer is active. It is inactive when + * it is done for traversal. All stack frames have been traversed. + */ + final boolean isActive() { + return origin > 0 && (fence == 0 || origin < fence || fence == currentBatchSize); + } + + /** + * Gets the class at the current frame and move to the next frame. + */ + final Class next() { + if (isEmpty()) { + throw new NoSuchElementException("origin=" + origin + " fence=" + fence); + } + Class c = classes[origin++]; + if (isDebug) { + int index = origin-1; + System.out.format(" next frame at %d: %s (origin %d fence %d)%n", index, + Objects.toString(c), index, fence); + } + return c; + } + + /** + * Gets the class at the current frame. + */ + final Class get() { + if (isEmpty()) { + throw new NoSuchElementException("origin=" + origin + " fence=" + fence); + } + return classes[origin]; + } + + /* + * Returns the index of the current frame. + */ + final int getIndex() { + return origin; + } + + /* + * Set the start and end index of a new batch of stack frames that have + * been filled in this frame buffer. + */ + final void setBatch(int startIndex, int endIndex) { + if (startIndex <= 0 || endIndex <= 0) + throw new IllegalArgumentException("startIndex=" + startIndex + " endIndex=" + endIndex); + + this.origin = startIndex; + this.fence = endIndex; + if (depth == 0 && fence > 0) { + // filter the frames due to the stack stream implementation + for (int i = START_POS; i < fence; i++) { + Class c = classes[i]; + if (isDebug) System.err.format(" frame %d: %s%n", i, c); + if (filterStackWalkImpl(c)) { + origin++; + } else { + break; + } + } + } + } + + /* + * Checks if the origin is the expected start index. + */ + final void check(int skipFrames) { + int index = skipFrames + START_POS; + if (origin != index) { + // stack walk must continue with the previous frame depth + throw new IllegalStateException("origin " + origin + " != " + index); + } + } + + // ------ subclass may override the following methods ------- + /** + * Resizes the buffers for VM to fill in the next batch of stack frames. + * The next batch will start at the given startIndex with the maximum number + * of elements. + * + *

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 + { + static { + stackWalkImplClasses.add(StackFrameTraverser.class); + } + 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 { + static { + stackWalkImplClasses.add(CallerClassFinder.class); + } + + private Class caller; + + CallerClassFinder(StackWalker walker) { + super(walker, FILL_CLASS_REFS_ONLY); + } + + Class findCaller() { + walk(); + return caller; + } + + @Override + protected Integer consumeFrames() { + checkState(OPEN); + int n = 0; + Class[] frames = new Class[2]; + // skip the API calling this getCallerClass method + // 0: StackWalker::getCallerClass + // 1: caller-sensitive method + // 2: caller class + while (n < 2 && (caller = nextFrame()) != null) { + if (isMethodHandleFrame(caller)) continue; + frames[n++] = caller; + } + + if (frames[1] == null) + throw new IllegalStateException("no caller frame"); + 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 { + static { + stackWalkImplClasses.add(StackTrace.class); + } + + 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 static final StackWalker STACKTRACE_WALKER = + StackWalker.newInstanceNoCheck(EnumSet.of(Option.SHOW_REFLECT_FRAMES)); + + private StackTraceElement[] stes; + static StackTrace dump() { + return new StackTrace(); + } + + static StackTrace dump(Throwable ex) { + return new StackTrace(ex); + } + + private StackTrace() { + this(STACKTRACE_WALKER, DEFAULT_MODE); + } + + /* + * Throwable::fillInStackTrace and of Throwable and subclasses + * are filtered in the VM. + */ + private StackTrace(Throwable ex) { + this(STACKTRACE_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 { + static { + stackWalkImplClasses.add(LiveStackInfoTraverser.class); + } + // 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()); + } + } + + private static native boolean checkStackWalkModes(); + + // avoid loading other subclasses as they may not be used + private static Set> init() { + if (!checkStackWalkModes()) { + throw new InternalError("StackWalker mode values do not match with JVM"); + } + + Set> classes = new HashSet<>(); + classes.add(StackWalker.class); + classes.add(StackStreamFactory.class); + classes.add(AbstractStackWalker.class); + return classes; + } + + private static boolean filterStackWalkImpl(Class c) { + return stackWalkImplClasses.contains(c) || + c.getName().startsWith("java.util.stream."); + } + + // MethodHandle frames are not hidden and CallerClassFinder has + // to filter them out + private static boolean isMethodHandleFrame(Class c) { + return c.getName().startsWith("java.lang.invoke."); + } + + 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-24 12:24:03.000000000 -0800 +++ new/jdk/src/java.base/share/classes/java/lang/StackWalker.java 2015-11-24 12:24:03.000000000 -0800 @@ -0,0 +1,563 @@ +/* + * 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}. + * + *

{@code StackWalker} is thread-safe. Multiple threads can share + * a single {@code StackWalker} object to traverse its own stack. + * 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.getInstance(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.getInstance().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 declaring class 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() { + int lineNumber = isNativeMethod() ? -2 + : getLineNumber().orElse(-1); + return new StackTraceElement(getClassName(), getMethodName(), + getFileName().orElse(null), + lineNumber); + } + } + + /** + * 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 monitors, 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 getInstance() { + // no permission check needed + return DEFAULT_WALKER; + } + + /** + * Returns 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 getInstance(Option option) { + return getInstance(EnumSet.of(Objects.requireNonNull(option))); + } + + /** + * Returns a {@code StackWalker} instance with the given {@code options} specifying + * the stack frame information it can access. If the given {@code 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 options} contains + * {@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 getInstance(Set

+ * If a security manager is present and the given {@code options} contains + * {@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 getInstance(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.getInstance().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. + * + *

Reflection frames, {@link java.lang.invoke.MethodHandle} and + * hidden frames are filtered regardless of the + * {@link Option#SHOW_REFLECT_FRAMES SHOW_REFLECT_FRAMES} + * and {@link Option#SHOW_HIDDEN_FRAMES SHOW_HIDDEN_FRAMES} options + * this {@code StackWalker} has been configured. + * + *

This method throws {@code UnsupportedOperationException} + * if this {@code StackWalker} is not configured with + * {@link Option#RETAIN_CLASS_REFERENCE RETAIN_CLASS_REFERENCE} option, + * This method should be called when a caller frame is present. If + * it is called from the last frame on the stack; + * {@code IllegalStateException} will be thrown. + * + * @apiNote + * For example, {@code Util::getResourceBundle} 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 Util {
+     *     private final StackWalker walker = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE);
+     *     public ResourceBundle getResourceBundle(String bundleName) {
+     *         Class caller = walker.getCallerClass();
+     *         return ResourceBundle.getBundle(bundleName, Locale.getDefault(), caller.getClassLoader());
+     *     }
+     * }
+     *
+     * class MyTool {
+     *     private final Util util = new Util();
+     *     private void init() {
+     *         ResourceBundle rb = util.getResourceBundle("mybundle");
+     *     }
+     * }
+     * }
+ * + * An equivalent way to find the caller class using the + * {@link StackWalker#walk walk} method is as follows + * (filtering the reflection frames, {@code MethodHandle} and hidden frames + * not shown below): + *
{@code
+     *     Optional> caller = walker.walk(s ->
+     *         s.map(StackFrame::getDeclaringClass)
+     *          .skip(2)
+     *          .findFirst());
+     * }
+ * + * When the {@code getCallerClass} method is called from a method that + * is the last frame on the stack, + * for example, {@code static public void main} method launched by the + * {@code java} launcher or a method invoked from a JNI attached thread. + * {@code IllegalStateException} is thrown. + * + * @return {@code Class} object of the caller's caller invoking this method. + * + * @throws UnsupportedOperationException if this {@code StackWalker} + * is not configured with {@link Option#RETAIN_CLASS_REFERENCE + * Option.RETAIN_CLASS_REFERENCE}. + * @throws IllegalStateException if there is no caller frame, i.e. + * when this {@code getCallerClass} method is called from a method + * which is the last frame on the stack. + */ + @CallerSensitive + public Class 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