OpenJDK / jdk / hs
changeset 44772:1d562a53fd19
Merge
author | prr |
---|---|
date | Thu, 20 Apr 2017 08:27:30 -0700 |
parents | 2ae94a74c972 36aae904cea9 |
children | 7dbf84b343f6 de8620413050 |
files | jdk/make/CopySamples.gmk jdk/src/demo/share/jvmti/agent_util/README.txt jdk/src/demo/share/jvmti/agent_util/agent_util.c jdk/src/demo/share/jvmti/agent_util/agent_util.h jdk/src/demo/share/jvmti/compiledMethodLoad/README.txt jdk/src/demo/share/jvmti/compiledMethodLoad/compiledMethodLoad.c jdk/src/demo/share/jvmti/compiledMethodLoad/sample.makefile.txt jdk/src/demo/share/jvmti/gctest/README.txt jdk/src/demo/share/jvmti/gctest/gctest.c jdk/src/demo/share/jvmti/gctest/sample.makefile.txt jdk/src/demo/share/jvmti/heapTracker/HeapTracker.java jdk/src/demo/share/jvmti/heapTracker/README.txt jdk/src/demo/share/jvmti/heapTracker/heapTracker.c jdk/src/demo/share/jvmti/heapTracker/heapTracker.h jdk/src/demo/share/jvmti/heapTracker/sample.makefile.txt jdk/src/demo/share/jvmti/heapViewer/README.txt jdk/src/demo/share/jvmti/heapViewer/heapViewer.c jdk/src/demo/share/jvmti/heapViewer/sample.makefile.txt jdk/src/demo/share/jvmti/index.html jdk/src/demo/share/jvmti/java_crw_demo/README.txt jdk/src/demo/share/jvmti/java_crw_demo/java_crw_demo.c jdk/src/demo/share/jvmti/java_crw_demo/java_crw_demo.h jdk/src/demo/share/jvmti/java_crw_demo/sample.makefile.txt jdk/src/demo/share/jvmti/minst/Minst.java jdk/src/demo/share/jvmti/minst/README.txt jdk/src/demo/share/jvmti/minst/minst.c jdk/src/demo/share/jvmti/minst/minst.h jdk/src/demo/share/jvmti/minst/sample.makefile.txt jdk/src/demo/share/jvmti/mtrace/Mtrace.java jdk/src/demo/share/jvmti/mtrace/README.txt jdk/src/demo/share/jvmti/mtrace/mtrace.c jdk/src/demo/share/jvmti/mtrace/mtrace.h jdk/src/demo/share/jvmti/mtrace/sample.makefile.txt jdk/src/demo/share/jvmti/versionCheck/README.txt jdk/src/demo/share/jvmti/versionCheck/sample.makefile.txt jdk/src/demo/share/jvmti/versionCheck/versionCheck.c jdk/src/demo/share/jvmti/waiters/Agent.cpp jdk/src/demo/share/jvmti/waiters/Agent.hpp jdk/src/demo/share/jvmti/waiters/Monitor.cpp jdk/src/demo/share/jvmti/waiters/Monitor.hpp jdk/src/demo/share/jvmti/waiters/README.txt jdk/src/demo/share/jvmti/waiters/Thread.cpp jdk/src/demo/share/jvmti/waiters/Thread.hpp jdk/src/demo/share/jvmti/waiters/sample.makefile.txt jdk/src/demo/share/jvmti/waiters/waiters.cpp jdk/src/demo/share/management/FullThreadDump/Deadlock.java jdk/src/demo/share/management/FullThreadDump/FullThreadDump.java jdk/src/demo/share/management/FullThreadDump/README.txt jdk/src/demo/share/management/FullThreadDump/ThreadMonitor.java jdk/src/demo/share/management/JTop/JTop.java jdk/src/demo/share/management/JTop/JTopPlugin.java jdk/src/demo/share/management/JTop/META-INF/services/com.sun.tools.jconsole.JConsolePlugin jdk/src/demo/share/management/JTop/README.txt jdk/src/demo/share/management/MemoryMonitor/MemoryMonitor.java jdk/src/demo/share/management/MemoryMonitor/README.txt jdk/src/demo/share/management/VerboseGC/PrintGCStat.java jdk/src/demo/share/management/VerboseGC/README.txt jdk/src/demo/share/management/VerboseGC/VerboseGC.java jdk/src/demo/share/management/index.html jdk/src/demo/share/scripting/jconsole-plugin/README.txt jdk/src/demo/share/scripting/jconsole-plugin/build.xml jdk/src/demo/share/scripting/jconsole-plugin/src/META-INF/services/com.sun.tools.jconsole.JConsolePlugin jdk/src/demo/share/scripting/jconsole-plugin/src/com/sun/demo/scripting/jconsole/EditableAtEndDocument.java jdk/src/demo/share/scripting/jconsole-plugin/src/com/sun/demo/scripting/jconsole/ScriptJConsolePlugin.java jdk/src/demo/share/scripting/jconsole-plugin/src/com/sun/demo/scripting/jconsole/ScriptShellPanel.java jdk/src/demo/share/scripting/jconsole-plugin/src/resources/jconsole.js jdk/src/demo/share/scripting/jconsole-plugin/src/scripts/heapdump.js jdk/src/demo/share/scripting/jconsole-plugin/src/scripts/hello.js jdk/src/demo/share/scripting/jconsole-plugin/src/scripts/invoke.js jdk/src/demo/share/scripting/jconsole-plugin/src/scripts/jstack.js jdk/src/demo/share/scripting/jconsole-plugin/src/scripts/jtop.js jdk/src/demo/share/scripting/jconsole-plugin/src/scripts/sysprops.js jdk/src/demo/share/scripting/jconsole-plugin/src/scripts/verbose.js jdk/src/demo/solaris/jni/Poller/Client.java jdk/src/demo/solaris/jni/Poller/LinkedQueue.java jdk/src/demo/solaris/jni/Poller/Poller.c jdk/src/demo/solaris/jni/Poller/Poller.java jdk/src/demo/solaris/jni/Poller/PollingServer.java jdk/src/demo/solaris/jni/Poller/README.txt jdk/src/demo/solaris/jni/Poller/SimpleServer.java jdk/src/sample/share/README jdk/src/sample/share/annotations/DependencyChecker/PluginChecker/src/checker/Device.java jdk/src/sample/share/annotations/DependencyChecker/PluginChecker/src/checker/Kettle.xml jdk/src/sample/share/annotations/DependencyChecker/PluginChecker/src/checker/Module.java jdk/src/sample/share/annotations/DependencyChecker/PluginChecker/src/checker/PluginChecker.java jdk/src/sample/share/annotations/DependencyChecker/PluginChecker/src/checker/Require.java jdk/src/sample/share/annotations/DependencyChecker/PluginChecker/src/checker/RequireContainer.java jdk/src/sample/share/annotations/DependencyChecker/Plugins/src/plugins/BoilerPlugin.java jdk/src/sample/share/annotations/DependencyChecker/Plugins/src/plugins/ExtendedBoilerPlugin.java jdk/src/sample/share/annotations/DependencyChecker/Plugins/src/plugins/TimerPlugin.java jdk/src/sample/share/annotations/Validator/src/PositiveIntegerSupplier.java jdk/src/sample/share/annotations/Validator/src/SupplierValidator.java jdk/src/sample/share/annotations/Validator/src/Validate.java jdk/src/sample/share/annotations/Validator/src/Validator.java jdk/src/sample/share/annotations/index.html jdk/src/sample/share/forkjoin/mergesort/MergeDemo.java jdk/src/sample/share/forkjoin/mergesort/MergeSort.java jdk/src/sample/share/jmx/jmx-scandir/build.properties jdk/src/sample/share/jmx/jmx-scandir/build.xml jdk/src/sample/share/jmx/jmx-scandir/index.html jdk/src/sample/share/jmx/jmx-scandir/logging.properties jdk/src/sample/share/jmx/jmx-scandir/manifest.mf jdk/src/sample/share/jmx/jmx-scandir/nbproject/file-targets.xml jdk/src/sample/share/jmx/jmx-scandir/nbproject/jdk.xml jdk/src/sample/share/jmx/jmx-scandir/nbproject/netbeans-targets.xml jdk/src/sample/share/jmx/jmx-scandir/nbproject/project.xml jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/DirectoryScanner.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/DirectoryScannerMXBean.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/ResultLogManager.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/ResultLogManagerMXBean.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/ScanDirAgent.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/ScanDirClient.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/ScanDirConfig.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/ScanDirConfigMXBean.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/ScanManager.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/ScanManagerMXBean.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/config/DirectoryScannerConfig.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/config/FileMatch.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/config/ResultLogConfig.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/config/ResultRecord.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/config/ScanManagerConfig.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/config/XmlConfigUtils.java jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/config/package.html jdk/src/sample/share/jmx/jmx-scandir/src/com/sun/jmx/examples/scandir/package.html jdk/src/sample/share/jmx/jmx-scandir/src/etc/access.properties jdk/src/sample/share/jmx/jmx-scandir/src/etc/management.properties jdk/src/sample/share/jmx/jmx-scandir/src/etc/password.properties jdk/src/sample/share/jmx/jmx-scandir/src/etc/testconfig.xml jdk/src/sample/share/jmx/jmx-scandir/test/com/sun/jmx/examples/scandir/DirectoryScannerTest.java jdk/src/sample/share/jmx/jmx-scandir/test/com/sun/jmx/examples/scandir/ScanDirConfigTest.java jdk/src/sample/share/jmx/jmx-scandir/test/com/sun/jmx/examples/scandir/ScanManagerTest.java jdk/src/sample/share/jmx/jmx-scandir/test/com/sun/jmx/examples/scandir/TestUtils.java jdk/src/sample/share/jmx/jmx-scandir/test/com/sun/jmx/examples/scandir/config/XmlConfigUtilsTest.java jdk/src/sample/share/lambda/BulkDataOperations/index.html jdk/src/sample/share/lambda/BulkDataOperations/src/CSVProcessor.java jdk/src/sample/share/lambda/BulkDataOperations/src/Grep.java jdk/src/sample/share/lambda/BulkDataOperations/src/PasswordGenerator.java jdk/src/sample/share/lambda/BulkDataOperations/src/WC.java jdk/src/sample/share/lambda/DefaultMethods/ArrayIterator.java jdk/src/sample/share/lambda/DefaultMethods/DiamondInheritance.java jdk/src/sample/share/lambda/DefaultMethods/Inheritance.java jdk/src/sample/share/lambda/DefaultMethods/MixIn.java jdk/src/sample/share/lambda/DefaultMethods/Reflection.java jdk/src/sample/share/lambda/DefaultMethods/SimplestUsage.java jdk/src/sample/share/nbproject/project.xml jdk/src/sample/share/nio/chatserver/ChatServer.java jdk/src/sample/share/nio/chatserver/Client.java jdk/src/sample/share/nio/chatserver/ClientReader.java jdk/src/sample/share/nio/chatserver/DataReader.java jdk/src/sample/share/nio/chatserver/MessageReader.java jdk/src/sample/share/nio/chatserver/NameReader.java jdk/src/sample/share/nio/chatserver/README.txt jdk/src/sample/share/nio/file/AclEdit.java jdk/src/sample/share/nio/file/Chmod.java jdk/src/sample/share/nio/file/Copy.java jdk/src/sample/share/nio/file/DiskUsage.java jdk/src/sample/share/nio/file/FileType.java jdk/src/sample/share/nio/file/WatchDir.java jdk/src/sample/share/nio/file/Xdd.java jdk/src/sample/share/nio/multicast/MulticastAddress.java jdk/src/sample/share/nio/multicast/Reader.java jdk/src/sample/share/nio/multicast/Sender.java jdk/src/sample/share/nio/server/AcceptHandler.java jdk/src/sample/share/nio/server/Acceptor.java jdk/src/sample/share/nio/server/B1.java jdk/src/sample/share/nio/server/BN.java jdk/src/sample/share/nio/server/BP.java jdk/src/sample/share/nio/server/ChannelIO.java jdk/src/sample/share/nio/server/ChannelIOSecure.java jdk/src/sample/share/nio/server/Content.java jdk/src/sample/share/nio/server/Dispatcher.java jdk/src/sample/share/nio/server/Dispatcher1.java jdk/src/sample/share/nio/server/DispatcherN.java jdk/src/sample/share/nio/server/FileContent.java jdk/src/sample/share/nio/server/Handler.java jdk/src/sample/share/nio/server/MalformedRequestException.java jdk/src/sample/share/nio/server/N1.java jdk/src/sample/share/nio/server/N2.java jdk/src/sample/share/nio/server/README.txt jdk/src/sample/share/nio/server/Reply.java jdk/src/sample/share/nio/server/Request.java jdk/src/sample/share/nio/server/RequestHandler.java jdk/src/sample/share/nio/server/RequestServicer.java jdk/src/sample/share/nio/server/Sendable.java jdk/src/sample/share/nio/server/Server.java jdk/src/sample/share/nio/server/StringContent.java jdk/src/sample/share/nio/server/URLDumper.java jdk/src/sample/share/scripting/scriptpad/README.txt jdk/src/sample/share/scripting/scriptpad/build.properties jdk/src/sample/share/scripting/scriptpad/build.xml jdk/src/sample/share/scripting/scriptpad/nbproject/file-targets.xml jdk/src/sample/share/scripting/scriptpad/nbproject/jdk.xml jdk/src/sample/share/scripting/scriptpad/nbproject/netbeans-targets.xml jdk/src/sample/share/scripting/scriptpad/nbproject/project.xml jdk/src/sample/share/scripting/scriptpad/src/META-INF/manifest.mf jdk/src/sample/share/scripting/scriptpad/src/com/sun/sample/scriptpad/Main.java jdk/src/sample/share/scripting/scriptpad/src/resources/Main.js jdk/src/sample/share/scripting/scriptpad/src/resources/conc.js jdk/src/sample/share/scripting/scriptpad/src/resources/gui.js jdk/src/sample/share/scripting/scriptpad/src/resources/mm.js jdk/src/sample/share/scripting/scriptpad/src/resources/scriptpad.js jdk/src/sample/share/scripting/scriptpad/src/scripts/README.txt jdk/src/sample/share/scripting/scriptpad/src/scripts/browse.js jdk/src/sample/share/scripting/scriptpad/src/scripts/insertfile.js jdk/src/sample/share/scripting/scriptpad/src/scripts/linewrap.js jdk/src/sample/share/scripting/scriptpad/src/scripts/mail.js jdk/src/sample/share/scripting/scriptpad/src/scripts/memmonitor.js jdk/src/sample/share/scripting/scriptpad/src/scripts/memory.bat jdk/src/sample/share/scripting/scriptpad/src/scripts/memory.js jdk/src/sample/share/scripting/scriptpad/src/scripts/memory.sh jdk/src/sample/share/scripting/scriptpad/src/scripts/textcolor.js jdk/src/sample/share/try-with-resources/index.html jdk/src/sample/share/try-with-resources/src/CustomAutoCloseableSample.java jdk/src/sample/share/try-with-resources/src/Unzip.java jdk/src/sample/share/try-with-resources/src/ZipCat.java jdk/src/sample/share/vm/clr-jvm/Makefile jdk/src/sample/share/vm/clr-jvm/README.txt jdk/src/sample/share/vm/clr-jvm/invoked.java jdk/src/sample/share/vm/clr-jvm/invoker.cs jdk/src/sample/share/vm/clr-jvm/jinvoker.cpp jdk/src/sample/share/vm/clr-jvm/jinvokerExp.h jdk/src/sample/share/vm/jvm-clr/Makefile jdk/src/sample/share/vm/jvm-clr/README.txt jdk/src/sample/share/vm/jvm-clr/invoked.cs jdk/src/sample/share/vm/jvm-clr/invoker.cpp jdk/src/sample/share/vm/jvm-clr/invoker.h jdk/src/sample/share/vm/jvm-clr/invoker.java jdk/src/sample/share/vm/jvm-clr/invokerExp.h jdk/src/sample/solaris/dtrace/README.txt jdk/src/sample/solaris/dtrace/helpers/dtrace_helper.d jdk/src/sample/solaris/dtrace/hotspot/README.txt jdk/src/sample/solaris/dtrace/hotspot/class_loading_stat.d jdk/src/sample/solaris/dtrace/hotspot/gc_time_stat.d jdk/src/sample/solaris/dtrace/hotspot/hotspot_calls_tree.d jdk/src/sample/solaris/dtrace/hotspot/method_compile_stat.d jdk/src/sample/solaris/dtrace/hotspot/method_invocation_stat.d jdk/src/sample/solaris/dtrace/hotspot/method_invocation_stat_filter.d jdk/src/sample/solaris/dtrace/hotspot/method_invocation_tree.d jdk/src/sample/solaris/dtrace/hotspot/monitors.d jdk/src/sample/solaris/dtrace/hotspot/object_allocation_stat.d jdk/src/sample/solaris/dtrace/hotspot_jni/CriticalSection.d jdk/src/sample/solaris/dtrace/hotspot_jni/CriticalSection_slow.d jdk/src/sample/solaris/dtrace/hotspot_jni/README.txt jdk/src/sample/solaris/dtrace/hotspot_jni/hotspot_jni_calls_stat.d jdk/src/sample/solaris/dtrace/hotspot_jni/hotspot_jni_calls_tree.d |
diffstat | 368 files changed, 1530 insertions(+), 43853 deletions(-) [+] |
line wrap: on
line diff
--- a/jdk/make/CompileDemos.gmk Mon Apr 17 09:08:38 2017 -0700 +++ b/jdk/make/CompileDemos.gmk Thu Apr 20 08:27:30 2017 -0700 @@ -263,239 +263,13 @@ MAIN_CLASS := transparentruler.Ruler, \ )) -$(eval $(call SetupBuildDemo, jconsole-plugin, \ - DEMO_SUBDIR := scripting, \ - SRC_SUB_DIR := src, \ - MAIN_CLASS := NONE, \ -)) - -$(eval $(call SetupBuildDemo, FullThreadDump, \ - DEMO_SUBDIR := management, \ -)) - -$(eval $(call SetupBuildDemo, JTop, \ - DEMO_SUBDIR := management, \ -)) - -$(eval $(call SetupBuildDemo, MemoryMonitor, \ - DEMO_SUBDIR := management, \ -)) - -$(eval $(call SetupBuildDemo, VerboseGC, \ - DEMO_SUBDIR := management, \ -)) - -################################################################################ -# Build JVMTI demos. - -# Setup make rules for building a JVMTI demo. -# -# Parameter 1 is the name of the rule. This name is used as variable prefix, -# and the targets generated are listed in a variable by that name. -# -# Remaining parameters are named arguments. These include: -# EXTRA_SRC_SUBDIR Also include these subdirectories -# TOOLCHAIN Optionally specify toolchain to use -SetupBuildJvmtiDemo = $(NamedParamsMacroTemplate) -define SetupBuildJvmtiDemoBody - $1_SRC := \ - $(DEMO_SHARE_SRC)/jvmti/$1 \ - $$(wildcard $$(addprefix $(DEMO_SHARE_SRC)/jvmti/, \ - agent_util $$($1_EXTRA_SRC_SUBDIR))) - - ### Build the native lib - $1_CFLAGS_INCLUDE := $$(addprefix -I, $$($1_SRC)) - - $1_CXXFLAGS := $$($1_CFLAGS_INCLUDE) $(CXXFLAGS_JDKLIB) $(CXXFLAGS_DEBUG_SYMBOLS) - - ifeq ($$($1_TOOLCHAIN), TOOLCHAIN_LINK_CXX) - # For C++, we also need some special treatment. - $1_LDFLAGS := $$(LDFLAGS_CXX_JDK) - $1_LIBS := $(LIBCXX) - - ifeq ($(OPENJDK_TARGET_CPU_ARCH), sparc) - $1_CXXFLAGS := $$(filter-out -xregs=no%appl, $$($1_CXXFLAGS)) - endif - endif - - # Remove the -incremental:no setting to get .ilk-files like in the old build. - $$(eval $$(call SetupNativeCompilation, BUILD_DEMO_JVMTI_NATIVE_$1, \ - SRC := $$($1_SRC), \ - TOOLCHAIN := $$($1_TOOLCHAIN), \ - OPTIMIZATION := LOW, \ - CFLAGS := $$($1_CFLAGS_INCLUDE) $$(CFLAGS_JDKLIB) $$(CFLAGS_DEBUG_SYMBOLS), \ - CXXFLAGS := $$($1_CXXFLAGS), \ - LDFLAGS := $(filter-out -incremental:no -opt:ref, $$(LDFLAGS_JDKLIB)) \ - $$($1_LDFLAGS), \ - LDFLAGS_macosx := $$(call SET_EXECUTABLE_ORIGIN), \ - LIBS := $$($1_LIBS), \ - LIBS_solaris := -lc, \ - VERSIONINFO_RESOURCE := $(GLOBAL_VERSION_INFO_RESOURCE), \ - RC_FLAGS := $$(RC_FLAGS) \ - -D "JDK_FNAME=$1.dll" \ - -D "JDK_INTERNAL_NAME=$1" \ - -D "JDK_FTYPE=0x2L", \ - OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/demos/native/jvmti/$1, \ - OUTPUT_DIR := $(SUPPORT_OUTPUTDIR)/demos/image/jvmti/$1/lib, \ - LIBRARY := $1, \ - STRIP_SYMBOLS := false, \ - )) - - $1 += $$(BUILD_DEMO_JVMTI_NATIVE_$1) - - ### Build the jar, if we have java sources - ifneq ($$(wildcard $(DEMO_SHARE_SRC)/jvmti/$1/*.java), ) - $$(eval $$(call SetupJavaCompilation, BUILD_DEMO_JVMTI_JAVA_$1, \ - SETUP := GENERATE_USINGJDKBYTECODE, \ - SRC := $(DEMO_SHARE_SRC)/jvmti/$1, \ - BIN := $(SUPPORT_OUTPUTDIR)/demos/classes/jvmti/$1, \ - COPY := $(COPY_TO_JAR), \ - JAR := $(SUPPORT_OUTPUTDIR)/demos/image/jvmti/$1/$1.jar, \ - EXTRA_MANIFEST_ATTR := Main-Class: \n, \ - MANIFEST := $(DEMO_MANIFEST), \ - )) - - $1 += $$(BUILD_DEMO_JVMTI_JAVA_$1_JAR) - endif - - ### Build the source zip - $1_EXCLUDE_FILES := \ - $$(wildcard $$(patsubst %, $(DEMO_SHARE_SRC)/jvmti/%/README.txt, \ - agent_util $$($1_EXTRA_SRC_SUBDIR))) \ - $$(wildcard $$(patsubst %, $(DEMO_SHARE_SRC)/jvmti/%/sample.makefile.txt, \ - agent_util $$($1_EXTRA_SRC_SUBDIR))) - - $$(eval $$(call SetupZipArchive, BUILD_DEMO_JVMTI_SRC_$1, \ - SRC := $$($1_SRC), \ - EXCLUDE_FILES := $$($1_EXCLUDE_FILES), \ - ZIP := $(SUPPORT_OUTPUTDIR)/demos/image/jvmti/$1/src.zip, \ - )) - - $1 += $$(BUILD_DEMO_JVMTI_SRC_$1) - - # Copy files to image - $(SUPPORT_OUTPUTDIR)/demos/image/jvmti/$1/README.txt: $(DEMO_SHARE_SRC)/jvmti/$1/README.txt - $$(call install-file) - $(CHMOD) -f ug+w $$@ - - $1 += $(SUPPORT_OUTPUTDIR)/demos/image/jvmti/$1/README.txt - - ifeq ($(OPENJDK_TARGET_OS), windows) - # These lib and exp files normally end up in OBJECT_DIR but for demos they - # are supposed to be included in the distro. Since they are created as - # a side-effect of the library compilation, make does not know about them. - $1_SUPPORT_OUTPUTDIR := $(SUPPORT_OUTPUTDIR)/demos/native/jvmti/$1 - $1_IMAGE_OUTPUTDIR := $(SUPPORT_OUTPUTDIR)/demos/image/jvmti/$1/lib - - $$($1_SUPPORT_OUTPUTDIR)/$1.lib: $$(BUILD_DEMO_JVMTI_NATIVE_$1) - - $$($1_SUPPORT_OUTPUTDIR)/$1.exp: $$(BUILD_DEMO_JVMTI_NATIVE_$1) - - $$($1_IMAGE_OUTPUTDIR)/$1.lib: $$($1_SUPPORT_OUTPUTDIR)/$1.lib - $$(call install-file) - - $$($1_IMAGE_OUTPUTDIR)/$1.exp: $$($1_SUPPORT_OUTPUTDIR)/$1.exp - $$(call install-file) - - $1 += $$($1_IMAGE_OUTPUTDIR)/$1.lib $$($1_IMAGE_OUTPUTDIR)/$1.exp - endif - - TARGETS += $$($1) -endef - -$(eval $(call SetupBuildJvmtiDemo, compiledMethodLoad)) -$(eval $(call SetupBuildJvmtiDemo, gctest)) -$(eval $(call SetupBuildJvmtiDemo, heapViewer)) -$(eval $(call SetupBuildJvmtiDemo, versionCheck)) - -$(eval $(call SetupBuildJvmtiDemo, heapTracker, \ - EXTRA_SRC_SUBDIR := java_crw_demo, \ -)) - -$(eval $(call SetupBuildJvmtiDemo, minst, \ - EXTRA_SRC_SUBDIR := java_crw_demo, \ -)) - -$(eval $(call SetupBuildJvmtiDemo, mtrace, \ - EXTRA_SRC_SUBDIR := java_crw_demo, \ -)) - -$(eval $(call SetupBuildJvmtiDemo, waiters, \ - TOOLCHAIN := TOOLCHAIN_LINK_CXX, \ -)) - -################################################################################ -# Build the Poller demo (on Solaris only). - -ifeq ($(OPENJDK_TARGET_OS), solaris) - DEMO_SOLARIS_SRC := $(JDK_TOPDIR)/src/demo/solaris - - $(eval $(call SetupJavaCompilation, BUILD_DEMO_JAVA_Poller, \ - SETUP := GENERATE_USINGJDKBYTECODE, \ - SRC := $(DEMO_SOLARIS_SRC)/jni/Poller, \ - BIN := $(SUPPORT_OUTPUTDIR)/demos/classes/jni/Poller, \ - HEADERS := $(SUPPORT_OUTPUTDIR)/demos/classes/jni/Poller, \ - JAR := $(SUPPORT_OUTPUTDIR)/demos/image/jni/Poller/Poller.jar, \ - MANIFEST := $(SUPPORT_OUTPUTDIR)/demos/java-main-manifest.mf, \ - SRCZIP := $(SUPPORT_OUTPUTDIR)/demos/image/jni/Poller/src.zip, \ - COPY := README.txt Poller.c, \ - JARMAIN := Client, \ - )) - - TARGETS += $(BUILD_DEMO_JAVA_Poller) - - $(eval $(call SetupNativeCompilation, BUILD_DEMO_NATIVE_Poller, \ - SRC := $(DEMO_SOLARIS_SRC)/jni/Poller, \ - OPTIMIZATION := LOW, \ - CFLAGS := $(CFLAGS_JDKLIB) \ - -I$(SUPPORT_OUTPUTDIR)/demos/classes/jni/Poller, \ - LDFLAGS := $(LDFLAGS_JDKLIB), \ - LIBS_solaris := -lc, \ - OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/demos/native/jni/Poller, \ - OUTPUT_DIR := $(SUPPORT_OUTPUTDIR)/demos/native, \ - LIBRARY := Poller, \ - STRIP_SYMBOLS := false, \ - )) - - TARGETS += $(BUILD_DEMO_NATIVE_Poller) - - # We can only compile native code after java has been compiled (since we - # depend on generated .h files) - $(SUPPORT_OUTPUTDIR)/demos/native/jni/Poller/Poller.o: \ - $(BUILD_DEMO_JAVA_Poller) - - # Copy to image - $(SUPPORT_OUTPUTDIR)/demos/image/jni/Poller/README.txt: \ - $(DEMO_SOLARIS_SRC)/jni/Poller/README.txt - $(call install-file) - $(CHMOD) -f ug+w $@ - - TARGETS += $(SUPPORT_OUTPUTDIR)/demos/image/jni/Poller/README.txt - - $(SUPPORT_OUTPUTDIR)/demos/image/jni/Poller/lib/libPoller.so: \ - $(SUPPORT_OUTPUTDIR)/demos/native/libPoller.so - $(call install-file) - - TARGETS += $(SUPPORT_OUTPUTDIR)/demos/image/jni/Poller/lib/libPoller.so -endif - ################################################################################ # Copy html and README files. -$(SUPPORT_OUTPUTDIR)/demos/image/management/index.html: $(DEMO_SHARE_SRC)/management/index.html - $(call install-file) - $(CHMOD) -f ug+w $@ - -$(SUPPORT_OUTPUTDIR)/demos/image/jvmti/index.html: $(DEMO_SHARE_SRC)/jvmti/index.html - $(call install-file) - $(CHMOD) -f ug+w $@ - $(SUPPORT_OUTPUTDIR)/demos/image/README: $(DEMO_SHARE_SRC)/README $(call install-file) -TARGETS += $(SUPPORT_OUTPUTDIR)/demos/image/management/index.html \ - $(SUPPORT_OUTPUTDIR)/demos/image/jvmti/index.html \ - $(SUPPORT_OUTPUTDIR)/demos/image/README +TARGETS += $(SUPPORT_OUTPUTDIR)/demos/image/README ################################################################################ # Copy netbeans project files.
--- a/jdk/make/CompileTools.gmk Mon Apr 17 09:08:38 2017 -0700 +++ b/jdk/make/CompileTools.gmk Thu Apr 20 08:27:30 2017 -0700 @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2011, 2017, 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 @@ -30,11 +30,19 @@ include JavaCompilation.gmk include SetupJavaCompilers.gmk +$(eval $(call IncludeCustomExtension, jdk, CompileTools.gmk)) + ################################################################################ +# Use += to be able to add to this from a custom extension +BUILD_TOOLS_SRC_DIRS += \ + $(JDK_TOPDIR)/make/src/classes \ + $(BUILDTOOLS_OUTPUTDIR)/interim_cldrconverter_classes \ + # + $(eval $(call SetupJavaCompilation,BUILD_TOOLS_JDK, \ SETUP := GENERATE_OLDBYTECODE, \ - SRC := $(JDK_TOPDIR)/make/src/classes $(BUILDTOOLS_OUTPUTDIR)/interim_cldrconverter_classes, \ + SRC := $(BUILD_TOOLS_SRC_DIRS), \ EXCLUDES := build/tools/deps \ build/tools/jigsaw, \ BIN := $(BUILDTOOLS_OUTPUTDIR)/jdk_tools_classes))
--- a/jdk/make/CopySamples.gmk Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,65 +0,0 @@ -# -# Copyright (c) 2011, 2014, 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. -# - -default: all - -include $(SPEC) -include MakeBase.gmk - -################################################################################ - -SAMPLE_TARGET_DIR := $(SUPPORT_OUTPUTDIR)/sample/image -SAMPLE_SOURCE_DIR := $(JDK_TOPDIR)/src/sample/share -SAMPLE_SOLARIS_SOURCE_DIR := $(JDK_TOPDIR)/src/sample/solaris - -# Exclude the vm directory -$(eval $(call SetupCopyFiles, COPY_SHARE_SAMPLES, \ - SRC := $(SAMPLE_SOURCE_DIR), \ - DEST := $(SAMPLE_TARGET_DIR), \ - FILES := $(filter-out $(SAMPLE_SOURCE_DIR)/vm/%, \ - $(call CacheFind, $(SAMPLE_SOURCE_DIR))), \ -)) - -TARGETS += $(COPY_SHARE_SAMPLES) - -ifneq (, $(filter $(OPENJDK_TARGET_OS), solaris macosx)) - $(eval $(call SetupCopyFiles, COPY_SOLARIS_SAMPLES, \ - SRC := $(SAMPLE_SOLARIS_SOURCE_DIR), \ - DEST := $(SAMPLE_TARGET_DIR), \ - FILES := $(call CacheFind, $(SAMPLE_SOLARIS_SOURCE_DIR)), \ - )) - - TARGETS += $(COPY_SOLARIS_SAMPLES) -endif - -################################################################################ - -$(eval $(call IncludeCustomExtension, jdk, CopySamples.gmk)) - -################################################################################ - -all: $(TARGETS) - -.PHONY: all default
--- a/jdk/make/Tools.gmk Mon Apr 17 09:08:38 2017 -0700 +++ b/jdk/make/Tools.gmk Thu Apr 20 08:27:30 2017 -0700 @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2011, 2017, 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 @@ -28,6 +28,9 @@ include JavaCompilation.gmk +# Hook to include the corresponding custom file, if present. +$(eval $(call IncludeCustomExtension, jdk, Tools.gmk)) + ################################################################################ # To avoid reevaluating the compilation setup for the tools each time this file # is included, the actual compilation is handled by CompileTools.gmk. The
--- a/jdk/make/data/charsetmapping/stdcs-linux Mon Apr 17 09:08:38 2017 -0700 +++ b/jdk/make/data/charsetmapping/stdcs-linux Thu Apr 20 08:27:30 2017 -0700 @@ -24,3 +24,5 @@ JIS_X_0212 JIS_X_0208_Solaris JIS_X_0212_Solaris +MS932 +SJIS # SJIS must go together with MS932 to support sun.nio.cs.map
--- a/jdk/src/demo/share/README Mon Apr 17 09:08:38 2017 -0700 +++ b/jdk/src/demo/share/README Thu Apr 20 08:27:30 2017 -0700 @@ -1,4 +1,4 @@ -The source code provided with samples and demos for the JDK is meant +The source code provided with demos for the JDK is meant to illustrate the usage of a given feature or technique and has been deliberately simplified. Additional steps required for a production-quality application, such as security checks, input
--- a/jdk/src/demo/share/jvmti/agent_util/README.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,35 +0,0 @@ -# -# Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -agent_util sources - -Just some shared generic source used by several of the demos. -
--- a/jdk/src/demo/share/jvmti/agent_util/agent_util.c Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,309 +0,0 @@ -/* - * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - -#include <agent_util.h> - -/* ------------------------------------------------------------------- */ -/* Generic C utility functions */ - -/* Send message to stdout or whatever the data output location is */ -void -stdout_message(const char * format, ...) -{ - va_list ap; - - va_start(ap, format); - (void)vfprintf(stdout, format, ap); - va_end(ap); -} - -/* Send message to stderr or whatever the error output location is and exit */ -void -fatal_error(const char * format, ...) -{ - va_list ap; - - va_start(ap, format); - (void)vfprintf(stderr, format, ap); - (void)fflush(stderr); - va_end(ap); - exit(3); -} - -/* Get a token from a string (strtok is not MT-safe) - * str String to scan - * seps Separation characters - * buf Place to put results - * max Size of buf - * Returns NULL if no token available or can't do the scan. - */ -char * -get_token(char *str, char *seps, char *buf, int max) -{ - int len; - - buf[0] = 0; - if ( str==NULL || str[0]==0 ) { - return NULL; - } - str += strspn(str, seps); - if ( str[0]==0 ) { - return NULL; - } - len = (int)strcspn(str, seps); - if ( len >= max ) { - return NULL; - } - (void)strncpy(buf, str, len); - buf[len] = 0; - return str+len; -} - -/* Determines if a class/method is specified by a list item - * item String that represents a pattern to match - * If it starts with a '*', then any class is allowed - * If it ends with a '*', then any method is allowed - * cname Class name, e.g. "java.lang.Object" - * mname Method name, e.g. "<init>" - * Returns 1(true) or 0(false). - */ -static int -covered_by_list_item(char *item, char *cname, char *mname) -{ - int len; - - len = (int)strlen(item); - if ( item[0]=='*' ) { - if ( strncmp(mname, item+1, len-1)==0 ) { - return 1; - } - } else if ( item[len-1]=='*' ) { - if ( strncmp(cname, item, len-1)==0 ) { - return 1; - } - } else { - int cname_len; - - cname_len = (int)strlen(cname); - if ( strncmp(cname, item, (len>cname_len?cname_len:len))==0 ) { - if ( cname_len >= len ) { - /* No method name supplied in item, we must have matched */ - return 1; - } else { - int mname_len; - - mname_len = (int)strlen(mname); - item += cname_len+1; - len -= cname_len+1; - if ( strncmp(mname, item, (len>mname_len?mname_len:len))==0 ) { - return 1; - } - } - } - } - return 0; -} - -/* Determines if a class/method is specified by this list - * list String of comma separated pattern items - * cname Class name, e.g. "java.lang.Object" - * mname Method name, e.g. "<init>" - * Returns 1(true) or 0(false). - */ -static int -covered_by_list(char *list, char *cname, char *mname) -{ - char token[1024]; - char *next; - - if ( list[0] == 0 ) { - return 0; - } - - next = get_token(list, ",", token, sizeof(token)); - while ( next != NULL ) { - if ( covered_by_list_item(token, cname, mname) ) { - return 1; - } - next = get_token(next, ",", token, sizeof(token)); - } - return 0; -} - -/* Determines which class and methods we are interested in - * cname Class name, e.g. "java.lang.Object" - * mname Method name, e.g. "<init>" - * include_list Empty or an explicit list for inclusion - * exclude_list Empty or an explicit list for exclusion - * Returns 1(true) or 0(false). - */ -int -interested(char *cname, char *mname, char *include_list, char *exclude_list) -{ - if ( exclude_list!=NULL && exclude_list[0]!=0 && - covered_by_list(exclude_list, cname, mname) ) { - return 0; - } - if ( include_list!=NULL && include_list[0]!=0 && - !covered_by_list(include_list, cname, mname) ) { - return 0; - } - return 1; -} - -/* ------------------------------------------------------------------- */ -/* Generic JVMTI utility functions */ - -/* Every JVMTI interface returns an error code, which should be checked - * to avoid any cascading errors down the line. - * The interface GetErrorName() returns the actual enumeration constant - * name, making the error messages much easier to understand. - */ -void -check_jvmti_error(jvmtiEnv *jvmti, jvmtiError errnum, const char *str) -{ - if ( errnum != JVMTI_ERROR_NONE ) { - char *errnum_str; - - errnum_str = NULL; - (void)(*jvmti)->GetErrorName(jvmti, errnum, &errnum_str); - - fatal_error("ERROR: JVMTI: %d(%s): %s\n", errnum, - (errnum_str==NULL?"Unknown":errnum_str), - (str==NULL?"":str)); - } -} - -/* All memory allocated by JVMTI must be freed by the JVMTI Deallocate - * interface. - */ -void -deallocate(jvmtiEnv *jvmti, void *ptr) -{ - jvmtiError error; - - error = (*jvmti)->Deallocate(jvmti, ptr); - check_jvmti_error(jvmti, error, "Cannot deallocate memory"); -} - -/* Allocation of JVMTI managed memory */ -void * -allocate(jvmtiEnv *jvmti, jint len) -{ - jvmtiError error; - void *ptr; - - error = (*jvmti)->Allocate(jvmti, len, (unsigned char **)&ptr); - check_jvmti_error(jvmti, error, "Cannot allocate memory"); - return ptr; -} - -/* Add demo jar file to boot class path (the BCI Tracker class must be - * in the boot classpath) - * - * WARNING: This code assumes that the jar file can be found at one of: - * ${JAVA_HOME}/demo/jvmti/${DEMO_NAME}/${DEMO_NAME}.jar - * ${JAVA_HOME}/../demo/jvmti/${DEMO_NAME}/${DEMO_NAME}.jar - * where JAVA_HOME may refer to the jre directory. - * Both these values are added to the boot classpath. - * These locations are only true for these demos, installed - * in the JDK area. Platform specific code could be used to - * find the location of the DLL or .so library, and construct a - * path name to the jar file, relative to the library location. - */ -void -add_demo_jar_to_bootclasspath(jvmtiEnv *jvmti, char *demo_name) -{ - jvmtiError error; - char *file_sep; - int max_len; - char *java_home; - char jar_path[FILENAME_MAX+1]; - - java_home = NULL; - error = (*jvmti)->GetSystemProperty(jvmti, "java.home", &java_home); - check_jvmti_error(jvmti, error, "Cannot get java.home property value"); - if ( java_home == NULL || java_home[0] == 0 ) { - fatal_error("ERROR: Java home not found\n"); - } - -#ifdef WIN32 - file_sep = "\\"; -#else - file_sep = "/"; -#endif - - max_len = (int)(strlen(java_home) + strlen(demo_name)*2 + - strlen(file_sep)*5 + - 16 /* ".." "demo" "jvmti" ".jar" NULL */ ); - if ( max_len > (int)sizeof(jar_path) ) { - fatal_error("ERROR: Path to jar file too long\n"); - } - (void)strcpy(jar_path, java_home); - (void)strcat(jar_path, file_sep); - (void)strcat(jar_path, "demo"); - (void)strcat(jar_path, file_sep); - (void)strcat(jar_path, "jvmti"); - (void)strcat(jar_path, file_sep); - (void)strcat(jar_path, demo_name); - (void)strcat(jar_path, file_sep); - (void)strcat(jar_path, demo_name); - (void)strcat(jar_path, ".jar"); - error = (*jvmti)->AddToBootstrapClassLoaderSearch(jvmti, (const char*)jar_path); - check_jvmti_error(jvmti, error, "Cannot add to boot classpath"); - - (void)strcpy(jar_path, java_home); - (void)strcat(jar_path, file_sep); - (void)strcat(jar_path, ".."); - (void)strcat(jar_path, file_sep); - (void)strcat(jar_path, "demo"); - (void)strcat(jar_path, file_sep); - (void)strcat(jar_path, "jvmti"); - (void)strcat(jar_path, file_sep); - (void)strcat(jar_path, demo_name); - (void)strcat(jar_path, file_sep); - (void)strcat(jar_path, demo_name); - (void)strcat(jar_path, ".jar"); - - error = (*jvmti)->AddToBootstrapClassLoaderSearch(jvmti, (const char*)jar_path); - check_jvmti_error(jvmti, error, "Cannot add to boot classpath"); -} - -/* ------------------------------------------------------------------- */
--- a/jdk/src/demo/share/jvmti/agent_util/agent_util.h Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - -#ifndef AGENT_UTIL_H -#define AGENT_UTIL_H - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <stddef.h> -#include <stdarg.h> - -#include "jni.h" -#include "jvmti.h" - -#ifdef __cplusplus -extern "C" { -#endif - -void stdout_message(const char * format, ...); -void fatal_error(const char * format, ...); -char *get_token(char *str, char *seps, char *buf, int max); -int interested(char *cname, char *mname, - char *include_list, char *exclude_list); - -void check_jvmti_error(jvmtiEnv *jvmti, jvmtiError errnum, const char *str); -void deallocate(jvmtiEnv *jvmti, void *ptr); -void *allocate(jvmtiEnv *jvmti, jint len); -void add_demo_jar_to_bootclasspath(jvmtiEnv *jvmti, char *demo_name); - -#ifdef STATIC_BUILD -/* Macros for handling declaration of static/dynamic - * Agent library Load/Attach/Unload functions - * - * DEF_Agent_OnLoad, DEF_Agent_OnAttach or DEF_Agent_OnUnload - * generate the appropriate entrypoint names based on static - * versus dynamic builds. - * - * STATIC_BUILD must be defined to build static versions of these libraries. - * LIBRARY_NAME must be set to the name of the library for static builds. - */ -#define ADD_LIB_NAME3(name, lib) name ## lib -#define ADD_LIB_NAME2(name, lib) ADD_LIB_NAME3(name, lib) -#define ADD_LIB_NAME(entry) ADD_LIB_NAME2(entry, LIBRARY_NAME) - -#define DEF_Agent_OnLoad \ -ADD_LIB_NAME(Agent_OnLoad_)(JavaVM *vm, char *options, void *reserved) \ -{ \ - jint JNICALL ADD_LIB_NAME(Agent_OnLoad_dynamic_)(JavaVM *vm, char *options, void *reserved); \ - return ADD_LIB_NAME(Agent_OnLoad_dynamic_)(vm, options, reserved); \ -} \ -jint JNICALL ADD_LIB_NAME(Agent_OnLoad_dynamic_) - -#define DEF_Agent_OnAttach \ -ADD_LIB_NAME(Agent_OnAttach_)(JavaVM *vm, char *options, void *reserved) \ -{ \ - jint JNICALL ADD_LIB_NAME(Agent_OnAttach_dynamic_)(JavaVM *vm, char *options, void *reserved); \ - return ADD_LIB_NAME(Agent_OnAttach_dynamic_)(vm, options, reserved); \ -} \ -jint JNICALL ADD_LIB_NAME(Agent_OnAttach_dynamic_) - -#define DEF_Agent_OnUnload \ -ADD_LIB_NAME(Agent_OnUnload_)(JavaVM *vm) \ -{ \ - void JNICALL ADD_LIB_NAME(Agent_OnUnload_dynamic_)(JavaVM *vm); \ - ADD_LIB_NAME(Agent_OnUnload_dynamic_)(vm); \ -} \ -void JNICALL ADD_LIB_NAME(Agent_OnUnload_dynamic_) - -#else -#define DEF_Agent_OnLoad Agent_OnLoad -#define DEF_Agent_OnAttach Agent_OnAttach -#define DEF_Agent_OnUnload Agent_OnUnload -#endif - -#ifdef __cplusplus -} /* extern "C" */ -#endif /* __cplusplus */ - -#endif
--- a/jdk/src/demo/share/jvmti/compiledMethodLoad/README.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,42 +0,0 @@ -# -# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -compiledMethodLoad - -This agent library traces CompiledMethodLoad events along -with the HotSpot specific compile_info parameter. - -You can use this agent library as follows: - - java -agentlib:compiledMethodLoad ... - -See ${JAVA_HOME}/demo/jvmti/index.html for help running and building agents. -
--- a/jdk/src/demo/share/jvmti/compiledMethodLoad/compiledMethodLoad.c Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,277 +0,0 @@ -/* - * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include "jni.h" -#include "jvmti.h" -#include "jvmticmlr.h" - -#include "agent_util.h" - -/* Global static data */ -static char OUTPUT_FILE[] = "compiledMethodLoad.txt"; -static FILE *fp; -static jvmtiEnv *jvmti; -static jrawMonitorID lock; - -/* print a jvmtiCompiledMethodLoadDummyRecord */ -void -print_dummy_record(jvmtiCompiledMethodLoadDummyRecord* record, - jvmtiEnv* jvmti, FILE* fp) { - - if (record != NULL) { - fprintf(fp, "Dummy record detected containing message: %s\n", - (char *)record->message); - } -} - -/* print the specified stack frames */ -void -print_stack_frames(PCStackInfo* record, jvmtiEnv *jvmti, FILE* fp) { - if (record != NULL && record->methods != NULL) { - int i; - - for (i = 0; i < record->numstackframes; i++) { - jvmtiError err; - char* method_name = NULL; - char* class_name = NULL; - char* method_signature = NULL; - char* class_signature = NULL; - char* generic_ptr_method = NULL; - char* generic_ptr_class = NULL; - jmethodID id; - jclass declaringclassptr; - id = record->methods[i]; - - err = (*jvmti)->GetMethodDeclaringClass(jvmti, id, - &declaringclassptr); - check_jvmti_error(jvmti, err, "get method declaring class"); - - err = (*jvmti)->GetClassSignature(jvmti, declaringclassptr, - &class_signature, &generic_ptr_class); - check_jvmti_error(jvmti, err, "get class signature"); - - err = (*jvmti)->GetMethodName(jvmti, id, &method_name, - &method_signature, &generic_ptr_method); - check_jvmti_error(jvmti, err, "get method name"); - - fprintf(fp, "%s::%s %s %s @%d\n", class_signature, method_name, - method_signature, - generic_ptr_method == NULL ? "" : generic_ptr_method, - record->bcis[i]); - - if (method_name != NULL) { - err = (*jvmti)->Deallocate(jvmti, (unsigned char*)method_name); - check_jvmti_error(jvmti, err, "deallocate method_name"); - } - if (method_signature != NULL) { - err = (*jvmti)->Deallocate(jvmti, - (unsigned char*)method_signature); - check_jvmti_error(jvmti, err, "deallocate method_signature"); - } - if (generic_ptr_method != NULL) { - err = (*jvmti)->Deallocate(jvmti, - (unsigned char*)generic_ptr_method); - check_jvmti_error(jvmti, err, "deallocate generic_ptr_method"); - } - if (class_name != NULL) { - err = (*jvmti)->Deallocate(jvmti, (unsigned char*)class_name); - check_jvmti_error(jvmti, err, "deallocate class_name"); - } - if (class_signature != NULL) { - err = (*jvmti)->Deallocate(jvmti, - (unsigned char*)class_signature); - check_jvmti_error(jvmti, err, "deallocate class_signature"); - } - if (generic_ptr_class != NULL) { - err = (*jvmti)->Deallocate(jvmti, - (unsigned char*)generic_ptr_class); - check_jvmti_error(jvmti, err, "deallocate generic_ptr_class"); - } - } - } -} - -/* print a jvmtiCompiledMethodLoadInlineRecord */ -void -print_inline_info_record(jvmtiCompiledMethodLoadInlineRecord* record, - jvmtiEnv *jvmti, FILE* fp) { - - if (record != NULL && record->pcinfo != NULL) { - int numpcs = record->numpcs; - int i; - - for (i = 0; i < numpcs; i++) { - PCStackInfo pcrecord = (record->pcinfo[i]); - fprintf(fp, "PcDescriptor(pc=%p):\n", pcrecord.pc); - print_stack_frames(&pcrecord, jvmti, fp); - } - } -} - -/* decode kind of CompiledMethodLoadRecord and print */ -void -print_records(jvmtiCompiledMethodLoadRecordHeader* list, jvmtiEnv *jvmti, - FILE* fp) -{ - jvmtiCompiledMethodLoadRecordHeader* curr = list; - fprintf(fp, "\nPrinting PC Descriptors\n\n"); - while (curr != NULL) { - switch (curr->kind) { - case JVMTI_CMLR_DUMMY: - print_dummy_record((jvmtiCompiledMethodLoadDummyRecord *)curr, - jvmti, fp); - break; - - case JVMTI_CMLR_INLINE_INFO: - print_inline_info_record( - (jvmtiCompiledMethodLoadInlineRecord *)curr, jvmti, fp); - break; - - default: - fprintf(fp, "Warning: unrecognized record: kind=%d\n", curr->kind); - break; - } - - curr = (jvmtiCompiledMethodLoadRecordHeader *)curr->next; - } -} - -/* Callback for JVMTI_EVENT_COMPILED_METHOD_LOAD */ -void JNICALL -compiled_method_load(jvmtiEnv *jvmti, jmethodID method, jint code_size, - const void* code_addr, jint map_length, const jvmtiAddrLocationMap* map, - const void* compile_info) -{ - jvmtiError err; - char* name = NULL; - char* signature = NULL; - char* generic_ptr = NULL; - jvmtiCompiledMethodLoadRecordHeader* pcs; - - err = (*jvmti)->RawMonitorEnter(jvmti, lock); - check_jvmti_error(jvmti, err, "raw monitor enter"); - - err = (*jvmti)->GetMethodName(jvmti, method, &name, &signature, - &generic_ptr); - check_jvmti_error(jvmti, err, "get method name"); - - fprintf(fp, "\nCompiled method load event\n"); - fprintf(fp, "Method name %s %s %s\n\n", name, signature, - generic_ptr == NULL ? "" : generic_ptr); - pcs = (jvmtiCompiledMethodLoadRecordHeader *)compile_info; - if (pcs != NULL) { - print_records(pcs, jvmti, fp); - } - - if (name != NULL) { - err = (*jvmti)->Deallocate(jvmti, (unsigned char*)name); - check_jvmti_error(jvmti, err, "deallocate name"); - } - if (signature != NULL) { - err = (*jvmti)->Deallocate(jvmti, (unsigned char*)signature); - check_jvmti_error(jvmti, err, "deallocate signature"); - } - if (generic_ptr != NULL) { - err = (*jvmti)->Deallocate(jvmti, (unsigned char*)generic_ptr); - check_jvmti_error(jvmti, err, "deallocate generic_ptr"); - } - - err = (*jvmti)->RawMonitorExit(jvmti, lock); - check_jvmti_error(jvmti, err, "raw monitor exit"); -} - -/* Agent_OnLoad() is called first, we prepare for a COMPILED_METHOD_LOAD - * event here. - */ -JNIEXPORT jint JNICALL -DEF_Agent_OnLoad(JavaVM *vm, char *options, void *reserved) -{ - jint rc; - jvmtiError err; - jvmtiCapabilities capabilities; - jvmtiEventCallbacks callbacks; - - fp = fopen(OUTPUT_FILE, "w"); - if (fp == NULL) { - fatal_error("ERROR: %s: Unable to create output file\n", OUTPUT_FILE); - return -1; - } - - /* Get JVMTI environment */ - rc = (*vm)->GetEnv(vm, (void **)&jvmti, JVMTI_VERSION); - if (rc != JNI_OK) { - fatal_error( - "ERROR: Unable to create jvmtiEnv, GetEnv failed, error=%d\n", rc); - return -1; - } - - /* add JVMTI capabilities */ - memset(&capabilities,0, sizeof(capabilities)); - capabilities.can_generate_compiled_method_load_events = 1; - err = (*jvmti)->AddCapabilities(jvmti, &capabilities); - check_jvmti_error(jvmti, err, "add capabilities"); - - /* set JVMTI callbacks for events */ - memset(&callbacks, 0, sizeof(callbacks)); - callbacks.CompiledMethodLoad = &compiled_method_load; - err = (*jvmti)->SetEventCallbacks(jvmti, &callbacks, sizeof(callbacks)); - check_jvmti_error(jvmti, err, "set event callbacks"); - - /* enable JVMTI events */ - err = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL); - check_jvmti_error(jvmti, err, "set event notify"); - - /* create coordination monitor */ - err = (*jvmti)->CreateRawMonitor(jvmti, "agent lock", &lock); - check_jvmti_error(jvmti, err, "create raw monitor"); - - return 0; -} - -/* Agent_OnUnload() is called last */ -JNIEXPORT void JNICALL -DEF_Agent_OnUnload(JavaVM *vm) -{ -}
--- a/jdk/src/demo/share/jvmti/compiledMethodLoad/sample.makefile.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,148 +0,0 @@ -# -# Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -######################################################################## -# -# Sample GNU Makefile for building JVMTI Demo compiledMethodLoad -# -# Example uses: -# gnumake JDK=<java_home> OSNAME=solaris [OPT=true] [LIBARCH=sparc] -# gnumake JDK=<java_home> OSNAME=solaris [OPT=true] [LIBARCH=sparcv9] -# gnumake JDK=<java_home> OSNAME=linux [OPT=true] -# gnumake JDK=<java_home> OSNAME=win32 [OPT=true] -# -######################################################################## - -# Source lists -LIBNAME=compiledMethodLoad -SOURCES=compiledMethodLoad.c ../agent_util/agent_util.c - -# Solaris Studio C Compiler Version 12.4 -ifeq ($(OSNAME), solaris) - # Sun Solaris Compiler options needed - COMMON_FLAGS=-mt -KPIC - # Options that help find errors - COMMON_FLAGS+= -Xa -v -xc99=%none - # Check LIBARCH for any special compiler options - LIBARCH=$(shell uname -p) - ifeq ($(LIBARCH), sparc) - COMMON_FLAGS+=-xarch=v8 -xregs=no%appl - endif - ifeq ($(LIBARCH), sparcv9) - COMMON_FLAGS+=-xarch=v9 -xregs=no%appl - endif - ifeq ($(OPT), true) - CFLAGS=-xO2 $(COMMON_FLAGS) - else - CFLAGS=-g $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.o) - # Library name and options needed to build it - LIBRARY=lib$(LIBNAME).so - LDFLAGS=-z defs -ztext - # Libraries we are dependent on - LIBRARIES= -lc - # Building a shared library - LINK_SHARED=$(LINK.c) -G -o $@ -endif - -# Linux GNU C Compiler -ifeq ($(OSNAME), linux) - # GNU Compiler options needed to build it - COMMON_FLAGS=-fno-strict-aliasing -fPIC -fno-omit-frame-pointer - # Options that help find errors - COMMON_FLAGS+= -W -Wall -Wno-unused -Wno-parentheses - ifeq ($(OPT), true) - CFLAGS=-O2 $(COMMON_FLAGS) - else - CFLAGS=-g $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.o) - # Library name and options needed to build it - LIBRARY=lib$(LIBNAME).so - LDFLAGS=-Wl,-soname=$(LIBRARY) -static-libgcc - # Libraries we are dependent on - LIBRARIES=-lc - # Building a shared library - LINK_SHARED=$(LINK.c) -shared -o $@ -endif - -# Windows Microsoft C/C++ Optimizing Compiler Version 12 -ifeq ($(OSNAME), win32) - CC=cl - # Compiler options needed to build it - COMMON_FLAGS=-Gy -DWIN32 - # Options that help find errors - COMMON_FLAGS+=-W0 -WX - ifeq ($(OPT), true) - CFLAGS= -Ox -Op -Zi $(COMMON_FLAGS) - else - CFLAGS= -Od -Zi $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.obj) - # Library name and options needed to build it - LIBRARY=$(LIBNAME).dll - LDFLAGS= - # Libraries we are dependent on - LIBRARIES= - # Building a shared library - LINK_SHARED=link -dll -out:$@ -endif - -# Common -I options -CFLAGS += -I. -CFLAGS += -I../agent_util -CFLAGS += -I$(JDK)/include -I$(JDK)/include/$(OSNAME) - -# Default rule -all: $(LIBRARY) - -# Build native library -$(LIBRARY): $(OBJECTS) - $(LINK_SHARED) $(OBJECTS) $(LIBRARIES) - -# Cleanup the built bits -clean: - rm -f $(LIBRARY) $(OBJECTS) - -# Simple tester -test: all - LD_LIBRARY_PATH=`pwd` $(JDK)/bin/java -agentlib:$(LIBNAME) -version - -# Compilation rule only needed on Windows -ifeq ($(OSNAME), win32) -%.obj: %.c - $(COMPILE.c) $< -endif -
--- a/jdk/src/demo/share/jvmti/gctest/README.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,54 +0,0 @@ -# -# Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -gctest - -This agent library can be used to track garbage collection events. - -You can use this agent library as follows: - - java -agentlib:gctest ... - -To get help on the available options try: - - java -agentlib:gctest=help - -See ${JAVA_HOME}/demo/jvmti/index.html for help running and building agents. - -The Events JVMTI_EVENT_GARBAGE_COLLECTION_START, -JVMTI_EVENT_GARBAGE_COLLECTION_FINISH, and JVMTI_EVENT_OBJECT_FREE -all have limitations as to what can be called directly inside the -agent callback functions (e.g. no JNI calls are allowed, and limited -interface calls can be made). However, by using raw monitors and a separate -watcher thread, this agent demonstrates how these limitations can be -easily avoided, allowing the watcher thread to do just about anything -after the JVMTI_EVENT_GARBAGE_COLLECTION_FINISH event. -
--- a/jdk/src/demo/share/jvmti/gctest/gctest.c Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - -/* Example of using JVMTI_EVENT_GARBAGE_COLLECTION_START and - * JVMTI_EVENT_GARBAGE_COLLECTION_FINISH events. - */ - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include "jni.h" -#include "jvmti.h" - -/* For stdout_message(), fatal_error(), and check_jvmti_error() */ -#include "agent_util.h" - -/* Global static data */ -static jvmtiEnv *jvmti; -static int gc_count; -static jrawMonitorID lock; - -/* Worker thread that waits for garbage collections */ -static void JNICALL -worker(jvmtiEnv* jvmti, JNIEnv* jni, void *p) -{ - jvmtiError err; - - stdout_message("GC worker started...\n"); - - for (;;) { - err = (*jvmti)->RawMonitorEnter(jvmti, lock); - check_jvmti_error(jvmti, err, "raw monitor enter"); - while (gc_count == 0) { - err = (*jvmti)->RawMonitorWait(jvmti, lock, 0); - if (err != JVMTI_ERROR_NONE) { - err = (*jvmti)->RawMonitorExit(jvmti, lock); - check_jvmti_error(jvmti, err, "raw monitor wait"); - return; - } - } - gc_count = 0; - - err = (*jvmti)->RawMonitorExit(jvmti, lock); - check_jvmti_error(jvmti, err, "raw monitor exit"); - - /* Perform arbitrary JVMTI/JNI work here to do post-GC cleanup */ - stdout_message("post-GarbageCollectionFinish actions...\n"); - } -} - -/* Creates a new jthread */ -static jthread -alloc_thread(JNIEnv *env) -{ - jclass thrClass; - jmethodID cid; - jthread res; - - thrClass = (*env)->FindClass(env, "java/lang/Thread"); - if ( thrClass == NULL ) { - fatal_error("Cannot find Thread class\n"); - } - cid = (*env)->GetMethodID(env, thrClass, "<init>", "()V"); - if ( cid == NULL ) { - fatal_error("Cannot find Thread constructor method\n"); - } - res = (*env)->NewObject(env, thrClass, cid); - if ( res == NULL ) { - fatal_error("Cannot create new Thread object\n"); - } - return res; -} - -/* Callback for JVMTI_EVENT_VM_INIT */ -static void JNICALL -vm_init(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) -{ - jvmtiError err; - - stdout_message("VMInit...\n"); - - err = (*jvmti)->RunAgentThread(jvmti, alloc_thread(env), &worker, NULL, - JVMTI_THREAD_MAX_PRIORITY); - check_jvmti_error(jvmti, err, "running agent thread"); -} - -/* Callback for JVMTI_EVENT_GARBAGE_COLLECTION_START */ -static void JNICALL -gc_start(jvmtiEnv* jvmti_env) -{ - stdout_message("GarbageCollectionStart...\n"); -} - -/* Callback for JVMTI_EVENT_GARBAGE_COLLECTION_FINISH */ -static void JNICALL -gc_finish(jvmtiEnv* jvmti_env) -{ - jvmtiError err; - - stdout_message("GarbageCollectionFinish...\n"); - - err = (*jvmti)->RawMonitorEnter(jvmti, lock); - check_jvmti_error(jvmti, err, "raw monitor enter"); - gc_count++; - err = (*jvmti)->RawMonitorNotify(jvmti, lock); - check_jvmti_error(jvmti, err, "raw monitor notify"); - err = (*jvmti)->RawMonitorExit(jvmti, lock); - check_jvmti_error(jvmti, err, "raw monitor exit"); -} - -/* Agent_OnLoad() is called first, we prepare for a VM_INIT event here. */ -JNIEXPORT jint JNICALL -DEF_Agent_OnLoad(JavaVM *vm, char *options, void *reserved) -{ - jint rc; - jvmtiError err; - jvmtiCapabilities capabilities; - jvmtiEventCallbacks callbacks; - - /* Get JVMTI environment */ - rc = (*vm)->GetEnv(vm, (void **)&jvmti, JVMTI_VERSION); - if (rc != JNI_OK) { - fatal_error("ERROR: Unable to create jvmtiEnv, rc=%d\n", rc); - return -1; - } - - /* Get/Add JVMTI capabilities */ - (void)memset(&capabilities, 0, sizeof(capabilities)); - capabilities.can_generate_garbage_collection_events = 1; - err = (*jvmti)->AddCapabilities(jvmti, &capabilities); - check_jvmti_error(jvmti, err, "add capabilities"); - - /* Set callbacks and enable event notifications */ - memset(&callbacks, 0, sizeof(callbacks)); - callbacks.VMInit = &vm_init; - callbacks.GarbageCollectionStart = &gc_start; - callbacks.GarbageCollectionFinish = &gc_finish; - err = (*jvmti)->SetEventCallbacks(jvmti, &callbacks, sizeof(callbacks)); - check_jvmti_error(jvmti, err, "set event callbacks"); - err = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_VM_INIT, NULL); - check_jvmti_error(jvmti, err, "set event notification"); - err = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_GARBAGE_COLLECTION_START, NULL); - check_jvmti_error(jvmti, err, "set event notification"); - err = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_GARBAGE_COLLECTION_FINISH, NULL); - check_jvmti_error(jvmti, err, "set event notification"); - - /* Create the necessary raw monitor */ - err = (*jvmti)->CreateRawMonitor(jvmti, "lock", &lock); - check_jvmti_error(jvmti, err, "create raw monitor"); - return 0; -} - -/* Agent_OnUnload() is called last */ -JNIEXPORT void JNICALL -DEF_Agent_OnUnload(JavaVM *vm) -{ -}
--- a/jdk/src/demo/share/jvmti/gctest/sample.makefile.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,148 +0,0 @@ -# -# Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -######################################################################## -# -# Sample GNU Makefile for building JVMTI Demo gctest -# -# Example uses: -# gnumake JDK=<java_home> OSNAME=solaris [OPT=true] [LIBARCH=sparc] -# gnumake JDK=<java_home> OSNAME=solaris [OPT=true] [LIBARCH=sparcv9] -# gnumake JDK=<java_home> OSNAME=linux [OPT=true] -# gnumake JDK=<java_home> OSNAME=win32 [OPT=true] -# -######################################################################## - -# Source lists -LIBNAME=gctest -SOURCES=gctest.c ../agent_util/agent_util.c - -# Solaris Studio C Compiler Version 12.4 -ifeq ($(OSNAME), solaris) - # Sun Solaris Compiler options needed - COMMON_FLAGS=-mt -KPIC - # Options that help find errors - COMMON_FLAGS+= -Xa -v -xc99=%none - # Check LIBARCH for any special compiler options - LIBARCH=$(shell uname -p) - ifeq ($(LIBARCH), sparc) - COMMON_FLAGS+=-xarch=v8 -xregs=no%appl - endif - ifeq ($(LIBARCH), sparcv9) - COMMON_FLAGS+=-xarch=v9 -xregs=no%appl - endif - ifeq ($(OPT), true) - CFLAGS=-xO2 $(COMMON_FLAGS) - else - CFLAGS=-g $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.o) - # Library name and options needed to build it - LIBRARY=lib$(LIBNAME).so - LDFLAGS=-z defs -ztext - # Libraries we are dependent on - LIBRARIES= -lc - # Building a shared library - LINK_SHARED=$(LINK.c) -G -o $@ -endif - -# Linux GNU C Compiler -ifeq ($(OSNAME), linux) - # GNU Compiler options needed to build it - COMMON_FLAGS=-fno-strict-aliasing -fPIC -fno-omit-frame-pointer - # Options that help find errors - COMMON_FLAGS+= -W -Wall -Wno-unused -Wno-parentheses - ifeq ($(OPT), true) - CFLAGS=-O2 $(COMMON_FLAGS) - else - CFLAGS=-g $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.o) - # Library name and options needed to build it - LIBRARY=lib$(LIBNAME).so - LDFLAGS=-Wl,-soname=$(LIBRARY) -static-libgcc - # Libraries we are dependent on - LIBRARIES=-lc - # Building a shared library - LINK_SHARED=$(LINK.c) -shared -o $@ -endif - -# Windows Microsoft C/C++ Optimizing Compiler Version 12 -ifeq ($(OSNAME), win32) - CC=cl - # Compiler options needed to build it - COMMON_FLAGS=-Gy -DWIN32 - # Options that help find errors - COMMON_FLAGS+=-W0 -WX - ifeq ($(OPT), true) - CFLAGS= -Ox -Op -Zi $(COMMON_FLAGS) - else - CFLAGS= -Od -Zi $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.obj) - # Library name and options needed to build it - LIBRARY=$(LIBNAME).dll - LDFLAGS= - # Libraries we are dependent on - LIBRARIES= - # Building a shared library - LINK_SHARED=link -dll -out:$@ -endif - -# Common -I options -CFLAGS += -I. -CFLAGS += -I../agent_util -CFLAGS += -I$(JDK)/include -I$(JDK)/include/$(OSNAME) - -# Default rule -all: $(LIBRARY) - -# Build native library -$(LIBRARY): $(OBJECTS) - $(LINK_SHARED) $(OBJECTS) $(LIBRARIES) - -# Cleanup the built bits -clean: - rm -f $(LIBRARY) $(OBJECTS) - -# Simple tester -test: all - LD_LIBRARY_PATH=`pwd` $(JDK)/bin/java -agentlib:$(LIBNAME) -version - -# Compilation rule only needed on Windows -ifeq ($(OSNAME), win32) -%.obj: %.c - $(COMPILE.c) $< -endif -
--- a/jdk/src/demo/share/jvmti/heapTracker/HeapTracker.java Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - - -/* Java class to hold static methods which will be called in byte code - * injections of all class files. - */ - -public class HeapTracker { - - private static int engaged = 0; - - private static native void _newobj(Object thread, Object o); - public static void newobj(Object o) - { - if ( engaged != 0 ) { - _newobj(Thread.currentThread(), o); - } - } - - private static native void _newarr(Object thread, Object a); - public static void newarr(Object a) - { - if ( engaged != 0 ) { - _newarr(Thread.currentThread(), a); - } - } - -}
--- a/jdk/src/demo/share/jvmti/heapTracker/README.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,47 +0,0 @@ -# -# Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -heapTracker - -This agent library can be used to track object allocations. -It uses the same java_crw_demo library used by HPROF to do BCI -on all classfiles loaded into the Virtual Machine. - -You can use this agent library as follows: - - java -agentlib:heapTracker ... - -To get help on the available options try: - - java -agentlib:heapTracker=help - -See ${JAVA_HOME}/demo/jvmti/index.html for help running and building agents. -
--- a/jdk/src/demo/share/jvmti/heapTracker/heapTracker.c Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1016 +0,0 @@ -/* - * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - -#include "stdlib.h" - -#include "heapTracker.h" -#include "java_crw_demo.h" - -#include "jni.h" -#include "jvmti.h" - -#include "agent_util.h" - -/* ------------------------------------------------------------------- - * Some constant names that tie to Java class/method names. - * We assume the Java class whose static methods we will be calling - * looks like: - * - * public class HeapTracker { - * private static int engaged; - * private static native void _newobj(Object thr, Object o); - * public static void newobj(Object o) - * { - * if ( engaged != 0 ) { - * _newobj(Thread.currentThread(), o); - * } - * } - * private static native void _newarr(Object thr, Object a); - * public static void newarr(Object a) - * { - * if ( engaged != 0 ) { - * _newarr(Thread.currentThread(), a); - * } - * } - * } - * - * The engaged field allows us to inject all classes (even system classes) - * and delay the actual calls to the native code until the VM has reached - * a safe time to call native methods (Past the JVMTI VM_START event). - * - */ - -#define HEAP_TRACKER_class HeapTracker /* Name of class we are using */ -#define HEAP_TRACKER_newobj newobj /* Name of java init method */ -#define HEAP_TRACKER_newarr newarr /* Name of java newarray method */ -#define HEAP_TRACKER_native_newobj _newobj /* Name of java newobj native */ -#define HEAP_TRACKER_native_newarr _newarr /* Name of java newarray native */ -#define HEAP_TRACKER_engaged engaged /* Name of static field switch */ - -/* C macros to create strings from tokens */ -#define _STRING(s) #s -#define STRING(s) _STRING(s) - -/* ------------------------------------------------------------------- */ - -/* Flavors of traces (to separate out stack traces) */ - -typedef enum { - TRACE_FIRST = 0, - TRACE_USER = 0, - TRACE_BEFORE_VM_START = 1, - TRACE_BEFORE_VM_INIT = 2, - TRACE_VM_OBJECT = 3, - TRACE_MYSTERY = 4, - TRACE_LAST = 4 -} TraceFlavor; - -static char * flavorDesc[] = { - "", - "before VM_START", - "before VM_INIT", - "VM_OBJECT", - "unknown" -}; - -/* Trace (Stack Trace) */ - -#define MAX_FRAMES 6 -typedef struct Trace { - /* Number of frames (includes HEAP_TRACKER methods) */ - jint nframes; - /* Frames from GetStackTrace() (2 extra for HEAP_TRACKER methods) */ - jvmtiFrameInfo frames[MAX_FRAMES+2]; - /* Used to make some traces unique */ - TraceFlavor flavor; -} Trace; - -/* Trace information (more than one object will have this as a tag) */ - -typedef struct TraceInfo { - /* Trace where this object was allocated from */ - Trace trace; - /* 64 bit hash code that attempts to identify this specific trace */ - jlong hashCode; - /* Total space taken up by objects allocated from this trace */ - jlong totalSpace; - /* Total count of objects ever allocated from this trace */ - int totalCount; - /* Total live objects that were allocated from this trace */ - int useCount; - /* The next TraceInfo in the hash bucket chain */ - struct TraceInfo *next; -} TraceInfo; - -/* Global agent data structure */ - -typedef struct { - /* JVMTI Environment */ - jvmtiEnv *jvmti; - /* State of the VM flags */ - jboolean vmStarted; - jboolean vmInitialized; - jboolean vmDead; - /* Options */ - int maxDump; - /* Data access Lock */ - jrawMonitorID lock; - /* Counter on classes where BCI has been applied */ - jint ccount; - /* Hash table to lookup TraceInfo's via Trace's */ - #define HASH_INDEX_BIT_WIDTH 12 /* 4096 */ - #define HASH_BUCKET_COUNT (1<<HASH_INDEX_BIT_WIDTH) - #define HASH_INDEX_MASK (HASH_BUCKET_COUNT-1) - TraceInfo *hashBuckets[HASH_BUCKET_COUNT]; - /* Count of TraceInfo's allocated */ - int traceInfoCount; - /* Pre-defined traces for the system and mystery situations */ - TraceInfo *emptyTrace[TRACE_LAST+1]; -} GlobalAgentData; - -static GlobalAgentData *gdata; - -/* Enter a critical section by doing a JVMTI Raw Monitor Enter */ -static void -enterCriticalSection(jvmtiEnv *jvmti) -{ - jvmtiError error; - - error = (*jvmti)->RawMonitorEnter(jvmti, gdata->lock); - check_jvmti_error(jvmti, error, "Cannot enter with raw monitor"); -} - -/* Exit a critical section by doing a JVMTI Raw Monitor Exit */ -static void -exitCriticalSection(jvmtiEnv *jvmti) -{ - jvmtiError error; - - error = (*jvmti)->RawMonitorExit(jvmti, gdata->lock); - check_jvmti_error(jvmti, error, "Cannot exit with raw monitor"); -} - -/* Update stats on a TraceInfo */ -static TraceInfo * -updateStats(TraceInfo *tinfo) -{ - tinfo->totalCount++; - tinfo->useCount++; - return tinfo; -} - -/* Get TraceInfo for empty stack */ -static TraceInfo * -emptyTrace(TraceFlavor flavor) -{ - return updateStats(gdata->emptyTrace[flavor]); -} - -/* Allocate new TraceInfo */ -static TraceInfo * -newTraceInfo(Trace *trace, jlong hashCode, TraceFlavor flavor) -{ - TraceInfo *tinfo; - - tinfo = (TraceInfo*)calloc(1, sizeof(TraceInfo)); - if ( tinfo == NULL ) { - fatal_error("ERROR: Ran out of malloc() space\n"); - } else { - int hashIndex; - - tinfo->trace = *trace; - tinfo->trace.flavor = flavor; - tinfo->hashCode = hashCode; - gdata->traceInfoCount++; - hashIndex = (int)(hashCode & HASH_INDEX_MASK); - tinfo->next = gdata->hashBuckets[hashIndex]; - gdata->hashBuckets[hashIndex] = tinfo; - } - return tinfo; -} - -/* Create hash code for a Trace */ -static jlong -hashTrace(Trace *trace) -{ - jlong hashCode; - int i; - - hashCode = 0; - for ( i = 0 ; i < trace->nframes ; i++ ) { - hashCode = (hashCode << 3) + - (jlong)(ptrdiff_t)(void*)(trace->frames[i].method); - hashCode = (hashCode << 2) + - (jlong)(trace->frames[i].location); - } - hashCode = (hashCode << 3) + trace->nframes; - hashCode += trace->flavor; - return hashCode; -} - -/* Lookup or create a new TraceInfo */ -static TraceInfo * -lookupOrEnter(jvmtiEnv *jvmti, Trace *trace, TraceFlavor flavor) -{ - TraceInfo *tinfo; - jlong hashCode; - - /* Calculate hash code (outside critical section to lessen contention) */ - hashCode = hashTrace(trace); - - /* Do a lookup in the hash table */ - enterCriticalSection(jvmti); { - TraceInfo *prev; - int hashIndex; - - /* Start with first item in hash buck chain */ - prev = NULL; - hashIndex = (int)(hashCode & HASH_INDEX_MASK); - tinfo = gdata->hashBuckets[hashIndex]; - while ( tinfo != NULL ) { - if ( tinfo->hashCode == hashCode && - memcmp(trace, &(tinfo->trace), sizeof(Trace))==0 ) { - /* We found one that matches, move to head of bucket chain */ - if ( prev != NULL ) { - /* Remove from list and add to head of list */ - prev->next = tinfo->next; - tinfo->next = gdata->hashBuckets[hashIndex]; - gdata->hashBuckets[hashIndex] = tinfo; - } - /* Break out */ - break; - } - prev = tinfo; - tinfo = tinfo->next; - } - - /* If we didn't find anything we need to enter a new entry */ - if ( tinfo == NULL ) { - /* Create new hash table element */ - tinfo = newTraceInfo(trace, hashCode, flavor); - } - - /* Update stats */ - (void)updateStats(tinfo); - - } exitCriticalSection(jvmti); - - return tinfo; -} - -/* Get TraceInfo for this allocation */ -static TraceInfo * -findTraceInfo(jvmtiEnv *jvmti, jthread thread, TraceFlavor flavor) -{ - TraceInfo *tinfo; - jvmtiError error; - - tinfo = NULL; - if ( thread != NULL ) { - static Trace empty; - Trace trace; - - /* Before VM_INIT thread could be NULL, watch out */ - trace = empty; - error = (*jvmti)->GetStackTrace(jvmti, thread, 0, MAX_FRAMES+2, - trace.frames, &(trace.nframes)); - /* If we get a PHASE error, the VM isn't ready, or it died */ - if ( error == JVMTI_ERROR_WRONG_PHASE ) { - /* It is assumed this is before VM_INIT */ - if ( flavor == TRACE_USER ) { - tinfo = emptyTrace(TRACE_BEFORE_VM_INIT); - } else { - tinfo = emptyTrace(flavor); - } - } else { - check_jvmti_error(jvmti, error, "Cannot get stack trace"); - /* Lookup this entry */ - tinfo = lookupOrEnter(jvmti, &trace, flavor); - } - } else { - /* If thread==NULL, it's assumed this is before VM_START */ - if ( flavor == TRACE_USER ) { - tinfo = emptyTrace(TRACE_BEFORE_VM_START); - } else { - tinfo = emptyTrace(flavor); - } - } - return tinfo; -} - -/* Tag an object with a TraceInfo pointer. */ -static void -tagObjectWithTraceInfo(jvmtiEnv *jvmti, jobject object, TraceInfo *tinfo) -{ - jvmtiError error; - jlong tag; - - /* Tag this object with this TraceInfo pointer */ - tag = (jlong)(ptrdiff_t)(void*)tinfo; - error = (*jvmti)->SetTag(jvmti, object, tag); - check_jvmti_error(jvmti, error, "Cannot tag object"); -} - -/* Java Native Method for Object.<init> */ -static void JNICALL -HEAP_TRACKER_native_newobj(JNIEnv *env, jclass klass, jthread thread, jobject o) -{ - TraceInfo *tinfo; - - if ( gdata->vmDead ) { - return; - } - tinfo = findTraceInfo(gdata->jvmti, thread, TRACE_USER); - tagObjectWithTraceInfo(gdata->jvmti, o, tinfo); -} - -/* Java Native Method for newarray */ -static void JNICALL -HEAP_TRACKER_native_newarr(JNIEnv *env, jclass klass, jthread thread, jobject a) -{ - TraceInfo *tinfo; - - if ( gdata->vmDead ) { - return; - } - tinfo = findTraceInfo(gdata->jvmti, thread, TRACE_USER); - tagObjectWithTraceInfo(gdata->jvmti, a, tinfo); -} - -/* Callback for JVMTI_EVENT_VM_START */ -static void JNICALL -cbVMStart(jvmtiEnv *jvmti, JNIEnv *env) -{ - enterCriticalSection(jvmti); { - jclass klass; - jfieldID field; - jint rc; - - /* Java Native Methods for class */ - static JNINativeMethod registry[2] = { - {STRING(HEAP_TRACKER_native_newobj), "(Ljava/lang/Object;Ljava/lang/Object;)V", - (void*)&HEAP_TRACKER_native_newobj}, - {STRING(HEAP_TRACKER_native_newarr), "(Ljava/lang/Object;Ljava/lang/Object;)V", - (void*)&HEAP_TRACKER_native_newarr} - }; - - /* Register Natives for class whose methods we use */ - klass = (*env)->FindClass(env, STRING(HEAP_TRACKER_class)); - if ( klass == NULL ) { - fatal_error("ERROR: JNI: Cannot find %s with FindClass\n", - STRING(HEAP_TRACKER_class)); - } - rc = (*env)->RegisterNatives(env, klass, registry, 2); - if ( rc != 0 ) { - fatal_error("ERROR: JNI: Cannot register natives for class %s\n", - STRING(HEAP_TRACKER_class)); - } - - /* Engage calls. */ - field = (*env)->GetStaticFieldID(env, klass, STRING(HEAP_TRACKER_engaged), "I"); - if ( field == NULL ) { - fatal_error("ERROR: JNI: Cannot get field from %s\n", - STRING(HEAP_TRACKER_class)); - } - (*env)->SetStaticIntField(env, klass, field, 1); - - /* Indicate VM has started */ - gdata->vmStarted = JNI_TRUE; - - } exitCriticalSection(jvmti); -} - -/* Iterate Through Heap callback */ -static jint JNICALL -cbObjectTagger(jlong class_tag, jlong size, jlong* tag_ptr, jint length, - void *user_data) -{ - TraceInfo *tinfo; - - tinfo = emptyTrace(TRACE_BEFORE_VM_INIT); - *tag_ptr = (jlong)(ptrdiff_t)(void*)tinfo; - return JVMTI_VISIT_OBJECTS; -} - -/* Callback for JVMTI_EVENT_VM_INIT */ -static void JNICALL -cbVMInit(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) -{ - jvmtiHeapCallbacks heapCallbacks; - jvmtiError error; - - /* Iterate through heap, find all untagged objects allocated before this */ - (void)memset(&heapCallbacks, 0, sizeof(heapCallbacks)); - heapCallbacks.heap_iteration_callback = &cbObjectTagger; - error = (*jvmti)->IterateThroughHeap(jvmti, JVMTI_HEAP_FILTER_TAGGED, - NULL, &heapCallbacks, NULL); - check_jvmti_error(jvmti, error, "Cannot iterate through heap"); - - enterCriticalSection(jvmti); { - - /* Indicate VM is initialized */ - gdata->vmInitialized = JNI_TRUE; - - } exitCriticalSection(jvmti); -} - -/* Iterate Through Heap callback */ -static jint JNICALL -cbObjectSpaceCounter(jlong class_tag, jlong size, jlong* tag_ptr, jint length, - void *user_data) -{ - TraceInfo *tinfo; - - tinfo = (TraceInfo*)(ptrdiff_t)(*tag_ptr); - if ( tinfo == NULL ) { - tinfo = emptyTrace(TRACE_MYSTERY); - *tag_ptr = (jlong)(ptrdiff_t)(void*)tinfo; - } - tinfo->totalSpace += size; - return JVMTI_VISIT_OBJECTS; -} - -/* Qsort compare function */ -static int -compareInfo(const void *p1, const void *p2) -{ - TraceInfo *tinfo1, *tinfo2; - - tinfo1 = *((TraceInfo**)p1); - tinfo2 = *((TraceInfo**)p2); - return (int)(tinfo2->totalSpace - tinfo1->totalSpace); -} - -/* Frame to text */ -static void -frameToString(jvmtiEnv *jvmti, char *buf, int buflen, jvmtiFrameInfo *finfo) -{ - jvmtiError error; - jclass klass; - char *signature; - char *methodname; - char *methodsig; - jboolean isNative; - char *filename; - int lineCount; - jvmtiLineNumberEntry*lineTable; - int lineNumber; - - /* Initialize defaults */ - buf[0] = 0; - klass = NULL; - signature = NULL; - methodname = NULL; - methodsig = NULL; - isNative = JNI_FALSE; - filename = NULL; - lineCount = 0; - lineTable = NULL; - lineNumber = 0; - - /* Get jclass object for the jmethodID */ - error = (*jvmti)->GetMethodDeclaringClass(jvmti, finfo->method, &klass); - check_jvmti_error(jvmti, error, "Cannot get method's class"); - - /* Get the class signature */ - error = (*jvmti)->GetClassSignature(jvmti, klass, &signature, NULL); - check_jvmti_error(jvmti, error, "Cannot get class signature"); - - /* Skip all this if it's our own Tracker method */ - if ( strcmp(signature, "L" STRING(HEAP_TRACKER_class) ";" ) == 0 ) { - deallocate(jvmti, signature); - return; - } - - /* Get the name and signature for the method */ - error = (*jvmti)->GetMethodName(jvmti, finfo->method, - &methodname, &methodsig, NULL); - check_jvmti_error(jvmti, error, "Cannot method name"); - - /* Check to see if it's a native method, which means no lineNumber */ - error = (*jvmti)->IsMethodNative(jvmti, finfo->method, &isNative); - check_jvmti_error(jvmti, error, "Cannot get method native status"); - - /* Get source file name */ - error = (*jvmti)->GetSourceFileName(jvmti, klass, &filename); - if ( error != JVMTI_ERROR_NONE && error != JVMTI_ERROR_ABSENT_INFORMATION ) { - check_jvmti_error(jvmti, error, "Cannot get source filename"); - } - - /* Get lineNumber if we can */ - if ( !isNative ) { - int i; - - /* Get method line table */ - error = (*jvmti)->GetLineNumberTable(jvmti, finfo->method, &lineCount, &lineTable); - if ( error == JVMTI_ERROR_NONE ) { - /* Search for line */ - lineNumber = lineTable[0].line_number; - for ( i = 1 ; i < lineCount ; i++ ) { - if ( finfo->location < lineTable[i].start_location ) { - break; - } - lineNumber = lineTable[i].line_number; - } - } else if ( error != JVMTI_ERROR_ABSENT_INFORMATION ) { - check_jvmti_error(jvmti, error, "Cannot get method line table"); - } - } - - /* Create string for this frame location. - * NOTE: These char* quantities are mUTF (Modified UTF-8) bytes - * and should actually be converted to the default system - * character encoding. Sending them to things like - * printf() without converting them is actually an I18n - * (Internationalization) error. - */ - (void)sprintf(buf, "%s.%s@%d[%s:%d]", - (signature==NULL?"UnknownClass":signature), - (methodname==NULL?"UnknownMethod":methodname), - (int)finfo->location, - (filename==NULL?"UnknownFile":filename), - lineNumber); - - /* Free up JVMTI space allocated by the above calls */ - deallocate(jvmti, signature); - deallocate(jvmti, methodname); - deallocate(jvmti, methodsig); - deallocate(jvmti, filename); - deallocate(jvmti, lineTable); -} - -/* Print the information */ -static void -printTraceInfo(jvmtiEnv *jvmti, int index, TraceInfo* tinfo) -{ - if ( tinfo == NULL ) { - fatal_error("%d: NULL ENTRY ERROR\n", index); - return; - } - - stdout_message("%2d: %7d bytes %5d objects %5d live %s", - index, (int)tinfo->totalSpace, tinfo->totalCount, - tinfo->useCount, flavorDesc[tinfo->trace.flavor]); - - if ( tinfo->trace.nframes > 0 ) { - int i; - int fcount; - - fcount = 0; - stdout_message(" stack=("); - for ( i = 0 ; i < tinfo->trace.nframes ; i++ ) { - char buf[4096]; - - frameToString(jvmti, buf, (int)sizeof(buf), tinfo->trace.frames+i); - if ( buf[0] == 0 ) { - continue; /* Skip the ones that are from Tracker class */ - } - fcount++; - stdout_message("%s", buf); - if ( i < (tinfo->trace.nframes-1) ) { - stdout_message(","); - } - } - stdout_message(") nframes=%d\n", fcount); - } else { - stdout_message(" stack=<empty>\n"); - } -} - -/* Callback for JVMTI_EVENT_VM_DEATH */ -static void JNICALL -cbVMDeath(jvmtiEnv *jvmti, JNIEnv *env) -{ - jvmtiHeapCallbacks heapCallbacks; - jvmtiError error; - - /* These are purposely done outside the critical section */ - - /* Force garbage collection now so we get our ObjectFree calls */ - error = (*jvmti)->ForceGarbageCollection(jvmti); - check_jvmti_error(jvmti, error, "Cannot force garbage collection"); - - /* Iterate through heap and find all objects */ - (void)memset(&heapCallbacks, 0, sizeof(heapCallbacks)); - heapCallbacks.heap_iteration_callback = &cbObjectSpaceCounter; - error = (*jvmti)->IterateThroughHeap(jvmti, 0, NULL, &heapCallbacks, NULL); - check_jvmti_error(jvmti, error, "Cannot iterate through heap"); - - /* Process VM Death */ - enterCriticalSection(jvmti); { - jclass klass; - jfieldID field; - jvmtiEventCallbacks callbacks; - - /* Disengage calls in HEAP_TRACKER_class. */ - klass = (*env)->FindClass(env, STRING(HEAP_TRACKER_class)); - if ( klass == NULL ) { - fatal_error("ERROR: JNI: Cannot find %s with FindClass\n", - STRING(HEAP_TRACKER_class)); - } - field = (*env)->GetStaticFieldID(env, klass, STRING(HEAP_TRACKER_engaged), "I"); - if ( field == NULL ) { - fatal_error("ERROR: JNI: Cannot get field from %s\n", - STRING(HEAP_TRACKER_class)); - } - (*env)->SetStaticIntField(env, klass, field, 0); - - /* The critical section here is important to hold back the VM death - * until all other callbacks have completed. - */ - - /* Clear out all callbacks. */ - (void)memset(&callbacks,0, sizeof(callbacks)); - error = (*jvmti)->SetEventCallbacks(jvmti, &callbacks, - (jint)sizeof(callbacks)); - check_jvmti_error(jvmti, error, "Cannot set jvmti callbacks"); - - /* Since this critical section could be holding up other threads - * in other event callbacks, we need to indicate that the VM is - * dead so that the other callbacks can short circuit their work. - * We don't expect an further events after VmDeath but we do need - * to be careful that existing threads might be in our own agent - * callback code. - */ - gdata->vmDead = JNI_TRUE; - - /* Dump all objects */ - if ( gdata->traceInfoCount > 0 ) { - TraceInfo **list; - int count; - int i; - - stdout_message("Dumping heap trace information\n"); - - /* Create single array of pointers to TraceInfo's, sort, and - * print top gdata->maxDump top space users. - */ - list = (TraceInfo**)calloc(gdata->traceInfoCount, - sizeof(TraceInfo*)); - if ( list == NULL ) { - fatal_error("ERROR: Ran out of malloc() space\n"); - } - count = 0; - for ( i = 0 ; i < HASH_BUCKET_COUNT ; i++ ) { - TraceInfo *tinfo; - - tinfo = gdata->hashBuckets[i]; - while ( tinfo != NULL ) { - if ( count < gdata->traceInfoCount ) { - list[count++] = tinfo; - } - tinfo = tinfo->next; - } - } - if ( count != gdata->traceInfoCount ) { - fatal_error("ERROR: Count found by iterate doesn't match ours:" - " count=%d != traceInfoCount==%d\n", - count, gdata->traceInfoCount); - } - qsort(list, count, sizeof(TraceInfo*), &compareInfo); - for ( i = 0 ; i < count ; i++ ) { - if ( i >= gdata->maxDump ) { - break; - } - printTraceInfo(jvmti, i+1, list[i]); - } - (void)free(list); - } - - } exitCriticalSection(jvmti); - -} - -/* Callback for JVMTI_EVENT_VM_OBJECT_ALLOC */ -static void JNICALL -cbVMObjectAlloc(jvmtiEnv *jvmti, JNIEnv *env, jthread thread, - jobject object, jclass object_klass, jlong size) -{ - TraceInfo *tinfo; - - if ( gdata->vmDead ) { - return; - } - tinfo = findTraceInfo(jvmti, thread, TRACE_VM_OBJECT); - tagObjectWithTraceInfo(jvmti, object, tinfo); -} - -/* Callback for JVMTI_EVENT_OBJECT_FREE */ -static void JNICALL -cbObjectFree(jvmtiEnv *jvmti, jlong tag) -{ - TraceInfo *tinfo; - - if ( gdata->vmDead ) { - return; - } - - /* The object tag is actually a pointer to a TraceInfo structure */ - tinfo = (TraceInfo*)(void*)(ptrdiff_t)tag; - - /* Decrement the use count */ - tinfo->useCount--; -} - -/* Callback for JVMTI_EVENT_CLASS_FILE_LOAD_HOOK */ -static void JNICALL -cbClassFileLoadHook(jvmtiEnv *jvmti, JNIEnv* env, - jclass class_being_redefined, jobject loader, - const char* name, jobject protection_domain, - jint class_data_len, const unsigned char* class_data, - jint* new_class_data_len, unsigned char** new_class_data) -{ - enterCriticalSection(jvmti); { - /* It's possible we get here right after VmDeath event, be careful */ - if ( !gdata->vmDead ) { - - const char * classname; - - /* Name can be NULL, make sure we avoid SEGV's */ - if ( name == NULL ) { - classname = java_crw_demo_classname(class_data, class_data_len, - NULL); - if ( classname == NULL ) { - fatal_error("ERROR: No classname in classfile\n"); - } - } else { - classname = strdup(name); - if ( classname == NULL ) { - fatal_error("ERROR: Ran out of malloc() space\n"); - } - } - - *new_class_data_len = 0; - *new_class_data = NULL; - - /* The tracker class itself? */ - if ( strcmp(classname, STRING(HEAP_TRACKER_class)) != 0 ) { - jint cnum; - int systemClass; - unsigned char *newImage; - long newLength; - - /* Get number for every class file image loaded */ - cnum = gdata->ccount++; - - /* Is it a system class? If the class load is before VmStart - * then we will consider it a system class that should - * be treated carefully. (See java_crw_demo) - */ - systemClass = 0; - if ( !gdata->vmStarted ) { - systemClass = 1; - } - - newImage = NULL; - newLength = 0; - - /* Call the class file reader/write demo code */ - java_crw_demo(cnum, - classname, - class_data, - class_data_len, - systemClass, - STRING(HEAP_TRACKER_class), - "L" STRING(HEAP_TRACKER_class) ";", - NULL, NULL, - NULL, NULL, - STRING(HEAP_TRACKER_newobj), "(Ljava/lang/Object;)V", - STRING(HEAP_TRACKER_newarr), "(Ljava/lang/Object;)V", - &newImage, - &newLength, - NULL, - NULL); - - /* If we got back a new class image, return it back as "the" - * new class image. This must be JVMTI Allocate space. - */ - if ( newLength > 0 ) { - unsigned char *jvmti_space; - - jvmti_space = (unsigned char *)allocate(jvmti, (jint)newLength); - (void)memcpy((void*)jvmti_space, (void*)newImage, (int)newLength); - *new_class_data_len = (jint)newLength; - *new_class_data = jvmti_space; /* VM will deallocate */ - } - - /* Always free up the space we get from java_crw_demo() */ - if ( newImage != NULL ) { - (void)free((void*)newImage); /* Free malloc() space with free() */ - } - } - - (void)free((void*)classname); - } - } exitCriticalSection(jvmti); -} - -/* Parse the options for this heapTracker agent */ -static void -parse_agent_options(char *options) -{ - #define MAX_TOKEN_LENGTH 16 - char token[MAX_TOKEN_LENGTH]; - char *next; - - /* Defaults */ - gdata->maxDump = 20; - - /* Parse options and set flags in gdata */ - if ( options==NULL ) { - return; - } - - /* Get the first token from the options string. */ - next = get_token(options, ",=", token, (int)sizeof(token)); - - /* While not at the end of the options string, process this option. */ - while ( next != NULL ) { - if ( strcmp(token,"help")==0 ) { - stdout_message("The heapTracker JVMTI demo agent\n"); - stdout_message("\n"); - stdout_message(" java -agent:heapTracker[=options] ...\n"); - stdout_message("\n"); - stdout_message("The options are comma separated:\n"); - stdout_message("\t help\t\t\t Print help information\n"); - stdout_message("\t maxDump=n\t\t\t How many TraceInfo's to dump\n"); - stdout_message("\n"); - exit(0); - } else if ( strcmp(token,"maxDump")==0 ) { - char number[MAX_TOKEN_LENGTH]; - - next = get_token(next, ",=", number, (int)sizeof(number)); - if ( next == NULL ) { - fatal_error("ERROR: Cannot parse maxDump=number: %s\n", options); - } - gdata->maxDump = atoi(number); - } else if ( token[0]!=0 ) { - /* We got a non-empty token and we don't know what it is. */ - fatal_error("ERROR: Unknown option: %s\n", token); - } - /* Get the next token (returns NULL if there are no more) */ - next = get_token(next, ",=", token, (int)sizeof(token)); - } -} - -/* Agent_OnLoad: This is called immediately after the shared library is - * loaded. This is the first code executed. - */ -JNIEXPORT jint JNICALL -DEF_Agent_OnLoad(JavaVM *vm, char *options, void *reserved) -{ - static GlobalAgentData data; - jvmtiEnv *jvmti; - jvmtiError error; - jint res; - TraceFlavor flavor; - jvmtiCapabilities capabilities; - jvmtiEventCallbacks callbacks; - static Trace empty; - - /* Setup initial global agent data area - * Use of static/extern data should be handled carefully here. - * We need to make sure that we are able to cleanup after ourselves - * so anything allocated in this library needs to be freed in - * the Agent_OnUnload() function. - */ - (void)memset((void*)&data, 0, sizeof(data)); - gdata = &data; - - /* First thing we need to do is get the jvmtiEnv* or JVMTI environment */ - res = (*vm)->GetEnv(vm, (void **)&jvmti, JVMTI_VERSION_1); - if (res != JNI_OK) { - /* This means that the VM was unable to obtain this version of the - * JVMTI interface, this is a fatal error. - */ - fatal_error("ERROR: Unable to access JVMTI Version 1 (0x%x)," - " is your JDK a 5.0 or newer version?" - " JNIEnv's GetEnv() returned %d\n", - JVMTI_VERSION_1, res); - } - - /* Here we save the jvmtiEnv* for Agent_OnUnload(). */ - gdata->jvmti = jvmti; - - /* Parse any options supplied on java command line */ - parse_agent_options(options); - - /* Immediately after getting the jvmtiEnv* we need to ask for the - * capabilities this agent will need. - */ - (void)memset(&capabilities,0, sizeof(capabilities)); - capabilities.can_generate_all_class_hook_events = 1; - capabilities.can_tag_objects = 1; - capabilities.can_generate_object_free_events = 1; - capabilities.can_get_source_file_name = 1; - capabilities.can_get_line_numbers = 1; - capabilities.can_generate_vm_object_alloc_events = 1; - error = (*jvmti)->AddCapabilities(jvmti, &capabilities); - check_jvmti_error(jvmti, error, "Unable to get necessary JVMTI capabilities."); - - /* Next we need to provide the pointers to the callback functions to - * to this jvmtiEnv* - */ - (void)memset(&callbacks,0, sizeof(callbacks)); - /* JVMTI_EVENT_VM_START */ - callbacks.VMStart = &cbVMStart; - /* JVMTI_EVENT_VM_INIT */ - callbacks.VMInit = &cbVMInit; - /* JVMTI_EVENT_VM_DEATH */ - callbacks.VMDeath = &cbVMDeath; - /* JVMTI_EVENT_OBJECT_FREE */ - callbacks.ObjectFree = &cbObjectFree; - /* JVMTI_EVENT_VM_OBJECT_ALLOC */ - callbacks.VMObjectAlloc = &cbVMObjectAlloc; - /* JVMTI_EVENT_CLASS_FILE_LOAD_HOOK */ - callbacks.ClassFileLoadHook = &cbClassFileLoadHook; - error = (*jvmti)->SetEventCallbacks(jvmti, &callbacks, (jint)sizeof(callbacks)); - check_jvmti_error(jvmti, error, "Cannot set jvmti callbacks"); - - /* At first the only initial events we are interested in are VM - * initialization, VM death, and Class File Loads. - * Once the VM is initialized we will request more events. - */ - error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_VM_START, (jthread)NULL); - check_jvmti_error(jvmti, error, "Cannot set event notification"); - error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_VM_INIT, (jthread)NULL); - check_jvmti_error(jvmti, error, "Cannot set event notification"); - error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_VM_DEATH, (jthread)NULL); - check_jvmti_error(jvmti, error, "Cannot set event notification"); - error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_OBJECT_FREE, (jthread)NULL); - check_jvmti_error(jvmti, error, "Cannot set event notification"); - error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_VM_OBJECT_ALLOC, (jthread)NULL); - check_jvmti_error(jvmti, error, "Cannot set event notification"); - error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, (jthread)NULL); - check_jvmti_error(jvmti, error, "Cannot set event notification"); - - /* Here we create a raw monitor for our use in this agent to - * protect critical sections of code. - */ - error = (*jvmti)->CreateRawMonitor(jvmti, "agent data", &(gdata->lock)); - check_jvmti_error(jvmti, error, "Cannot create raw monitor"); - - /* Create the TraceInfo for various flavors of empty traces */ - for ( flavor = TRACE_FIRST ; flavor <= TRACE_LAST ; flavor++ ) { - gdata->emptyTrace[flavor] = - newTraceInfo(&empty, hashTrace(&empty), flavor); - } - - /* Add jar file to boot classpath */ - add_demo_jar_to_bootclasspath(jvmti, "heapTracker"); - - /* We return JNI_OK to signify success */ - return JNI_OK; -} - -/* Agent_OnUnload: This is called immediately before the shared library is - * unloaded. This is the last code executed. - */ -JNIEXPORT void JNICALL -DEF_Agent_OnUnload(JavaVM *vm) -{ - /* Skip any cleanup, VM is about to die anyway */ -}
--- a/jdk/src/demo/share/jvmti/heapTracker/heapTracker.h Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - -/* Primary heapTracker #include file, should be included by most if not - * all heapTracker source files. Gives access to the global data structure - * and all global macros. - */ - -#ifndef HEAP_TRACKER_H -#define HEAP_TRACKER_H - -/* Standard C functions used throughout. */ - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <stddef.h> -#include <stdarg.h> - -/* General JVM/Java functions, types and macros. */ - -#include <sys/types.h> -#include "jni.h" -#include "jvmti.h" - -/* Utility functions */ - -#include "agent_util.h" - -#endif
--- a/jdk/src/demo/share/jvmti/heapTracker/sample.makefile.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,163 +0,0 @@ -# -# Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -######################################################################## -# -# Sample GNU Makefile for building JVMTI Demo heapTracker -# -# Example uses: -# gnumake JDK=<java_home> OSNAME=solaris [OPT=true] [LIBARCH=sparc] -# gnumake JDK=<java_home> OSNAME=solaris [OPT=true] [LIBARCH=sparcv9] -# gnumake JDK=<java_home> OSNAME=linux [OPT=true] -# gnumake JDK=<java_home> OSNAME=win32 [OPT=true] -# -######################################################################## - -# Source lists -LIBNAME=heapTracker -SOURCES=heapTracker.c ../agent_util/agent_util.c -JAVA_SOURCES=HeapTracker.java - -# Name of jar file that needs to be created -JARFILE=heapTracker.jar - -# Solaris Studio C Compiler Version 12.4 -ifeq ($(OSNAME), solaris) - # Sun Solaris Compiler options needed - COMMON_FLAGS=-mt -KPIC - # Options that help find errors - COMMON_FLAGS+= -Xa -v -xc99=%none - # Check LIBARCH for any special compiler options - LIBARCH=$(shell uname -p) - ifeq ($(LIBARCH), sparc) - COMMON_FLAGS+=-xarch=v8 -xregs=no%appl - endif - ifeq ($(LIBARCH), sparcv9) - COMMON_FLAGS+=-xarch=v9 -xregs=no%appl - endif - ifeq ($(OPT), true) - CFLAGS=-xO2 $(COMMON_FLAGS) - else - CFLAGS=-g $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.o) - # Library name and options needed to build it - LIBRARY=lib$(LIBNAME).so - LDFLAGS=-z defs -ztext - # Libraries we are dependent on - LIBRARIES=-L $(JDK)/jre/lib/$(LIBARCH) -ljava_crw_demo -lc - # Building a shared library - LINK_SHARED=$(LINK.c) -G -o $@ -endif - -# Linux GNU C Compiler -ifeq ($(OSNAME), linux) - # GNU Compiler options needed to build it - COMMON_FLAGS=-fno-strict-aliasing -fPIC -fno-omit-frame-pointer - # Options that help find errors - COMMON_FLAGS+= -W -Wall -Wno-unused -Wno-parentheses - ifeq ($(OPT), true) - CFLAGS=-O2 $(COMMON_FLAGS) - else - CFLAGS=-g $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.o) - # Library name and options needed to build it - LIBRARY=lib$(LIBNAME).so - LDFLAGS=-Wl,-soname=$(LIBRARY) -static-libgcc - # Libraries we are dependent on - LIBRARIES=-L $(JDK)/jre/lib/$(LIBARCH) -ljava_crw_demo -lc - # Building a shared library - LINK_SHARED=$(LINK.c) -shared -o $@ -endif - -# Windows Microsoft C/C++ Optimizing Compiler Version 12 -ifeq ($(OSNAME), win32) - CC=cl - # Compiler options needed to build it - COMMON_FLAGS=-Gy -DWIN32 - # Options that help find errors - COMMON_FLAGS+=-W0 -WX - ifeq ($(OPT), true) - CFLAGS= -Ox -Op -Zi $(COMMON_FLAGS) - else - CFLAGS= -Od -Zi $(COMMON_FLAGS) - endif - # Sources need java_crw_demo - SOURCES += ../java_crw_demo/java_crw_demo.c - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.obj) - # Library name and options needed to build it - LIBRARY=$(LIBNAME).dll - LDFLAGS= - # Libraries we are dependent on - LIBRARIES=$(JDK)/ - # Building a shared library - LINK_SHARED=link -dll -out:$@ -endif - -# Common -I options -CFLAGS += -I. -CFLAGS += -I../agent_util -CFLAGS += -I../java_crw_demo -CFLAGS += -I$(JDK)/include -I$(JDK)/include/$(OSNAME) - -# Default rule (build both native library and jar file) -all: $(LIBRARY) $(JARFILE) - -# Build native library -$(LIBRARY): $(OBJECTS) - $(LINK_SHARED) $(OBJECTS) $(LIBRARIES) - -# Build jar file -$(JARFILE): $(JAVA_SOURCES) - rm -f -r classes - mkdir -p classes - $(JDK)/bin/javac -d classes $(JAVA_SOURCES) - (cd classes; $(JDK)/bin/jar cf ../$@ *) - -# Cleanup the built bits -clean: - rm -f -r classes - rm -f $(LIBRARY) $(JARFILE) $(OBJECTS) - -# Simple tester -test: all - LD_LIBRARY_PATH=. $(JDK)/bin/java -agentlib:$(LIBNAME) -Xbootclasspath/a:./$(JARFILE) -version - -# Compilation rule only needed on Windows -ifeq ($(OSNAME), win32) -%.obj: %.c - $(COMPILE.c) $< -endif -
--- a/jdk/src/demo/share/jvmti/heapViewer/README.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,56 +0,0 @@ -# -# Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -heapViewer - -This agent library demonstrates how to get an easy view of the -heap in terms of total object count and space used. -It uses GetLoadedClasses(), SetTag(), and IterateThroughHeap() -to count up all the objects of all the current loaded classes. -The heap dump will happen at the event JVMTI_EVENT_VM_DEATH, or the -event JVMTI_EVENT_DATA_DUMP_REQUEST. - -It also demonstrates some more robust agent error handling using -GetErrorName(), - -Using the heap iterate functions, lots of statistics can be generated -without resorting to using Byte Code Instrumentation (BCI). - -You can use this agent library as follows: - - java -agentlib:heapViewer ... - -To get help on the available options try: - - java -agentlib:heapViewer=help - -See ${JAVA_HOME}/demo/jvmti/index.html for help running and building agents. -
--- a/jdk/src/demo/share/jvmti/heapViewer/heapViewer.c Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,288 +0,0 @@ -/* - * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - -#include <stdio.h> -#include <stddef.h> -#include <stdlib.h> -#include <string.h> - -#include "jni.h" -#include "jvmti.h" - -#include "agent_util.h" - -/* Global static data */ -typedef struct { - jboolean vmDeathCalled; - jboolean dumpInProgress; - jrawMonitorID lock; -} GlobalData; -static GlobalData globalData, *gdata = &globalData; - -/* Typedef to hold class details */ -typedef struct { - char *signature; - int count; - int space; -} ClassDetails; - -/* Enter agent monitor protected section */ -static void -enterAgentMonitor(jvmtiEnv *jvmti) -{ - jvmtiError err; - - err = (*jvmti)->RawMonitorEnter(jvmti, gdata->lock); - check_jvmti_error(jvmti, err, "raw monitor enter"); -} - -/* Exit agent monitor protected section */ -static void -exitAgentMonitor(jvmtiEnv *jvmti) -{ - jvmtiError err; - - err = (*jvmti)->RawMonitorExit(jvmti, gdata->lock); - check_jvmti_error(jvmti, err, "raw monitor exit"); -} - -/* Heap object callback */ -static jint JNICALL -cbHeapObject(jlong class_tag, jlong size, jlong* tag_ptr, jint length, - void* user_data) -{ - if ( class_tag != (jlong)0 ) { - ClassDetails *d; - - d = (ClassDetails*)(void*)(ptrdiff_t)class_tag; - (*((jint*)(user_data)))++; - d->count++; - d->space += (int)size; - } - return JVMTI_VISIT_OBJECTS; -} - -/* Compare two ClassDetails */ -static int -compareDetails(const void *p1, const void *p2) -{ - return ((ClassDetails*)p2)->space - ((ClassDetails*)p1)->space; -} - -/* Callback for JVMTI_EVENT_DATA_DUMP_REQUEST (Ctrl-\ or at exit) */ -static void JNICALL -dataDumpRequest(jvmtiEnv *jvmti) -{ - enterAgentMonitor(jvmti); { - if ( !gdata->vmDeathCalled && !gdata->dumpInProgress ) { - jvmtiHeapCallbacks heapCallbacks; - ClassDetails *details; - jvmtiError err; - jclass *classes; - jint totalCount; - jint count; - jint i; - - gdata->dumpInProgress = JNI_TRUE; - - /* Get all the loaded classes */ - err = (*jvmti)->GetLoadedClasses(jvmti, &count, &classes); - check_jvmti_error(jvmti, err, "get loaded classes"); - - /* Setup an area to hold details about these classes */ - details = (ClassDetails*)calloc(sizeof(ClassDetails), count); - if ( details == NULL ) { - fatal_error("ERROR: Ran out of malloc space\n"); - } - for ( i = 0 ; i < count ; i++ ) { - char *sig; - - /* Get and save the class signature */ - err = (*jvmti)->GetClassSignature(jvmti, classes[i], &sig, NULL); - check_jvmti_error(jvmti, err, "get class signature"); - if ( sig == NULL ) { - fatal_error("ERROR: No class signature found\n"); - } - details[i].signature = strdup(sig); - deallocate(jvmti, sig); - - /* Tag this jclass */ - err = (*jvmti)->SetTag(jvmti, classes[i], - (jlong)(ptrdiff_t)(void*)(&details[i])); - check_jvmti_error(jvmti, err, "set object tag"); - } - - /* Iterate through the heap and count up uses of jclass */ - (void)memset(&heapCallbacks, 0, sizeof(heapCallbacks)); - heapCallbacks.heap_iteration_callback = &cbHeapObject; - totalCount = 0; - err = (*jvmti)->IterateThroughHeap(jvmti, - JVMTI_HEAP_FILTER_CLASS_UNTAGGED, NULL, - &heapCallbacks, (const void *)&totalCount); - check_jvmti_error(jvmti, err, "iterate through heap"); - - /* Remove tags */ - for ( i = 0 ; i < count ; i++ ) { - /* Un-Tag this jclass */ - err = (*jvmti)->SetTag(jvmti, classes[i], (jlong)0); - check_jvmti_error(jvmti, err, "set object tag"); - } - - /* Sort details by space used */ - qsort(details, count, sizeof(ClassDetails), &compareDetails); - - /* Print out sorted table */ - stdout_message("Heap View, Total of %d objects found.\n\n", - totalCount); - - stdout_message("Space Count Class Signature\n"); - stdout_message("---------- ---------- ----------------------\n"); - - for ( i = 0 ; i < count ; i++ ) { - if ( details[i].space == 0 || i > 20 ) { - break; - } - stdout_message("%10d %10d %s\n", - details[i].space, details[i].count, details[i].signature); - } - stdout_message("---------- ---------- ----------------------\n\n"); - - /* Free up all allocated space */ - deallocate(jvmti, classes); - for ( i = 0 ; i < count ; i++ ) { - if ( details[i].signature != NULL ) { - free(details[i].signature); - } - } - free(details); - - gdata->dumpInProgress = JNI_FALSE; - } - } exitAgentMonitor(jvmti); -} - -/* Callback for JVMTI_EVENT_VM_INIT */ -static void JNICALL -vmInit(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) -{ - enterAgentMonitor(jvmti); { - jvmtiError err; - - err = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_DATA_DUMP_REQUEST, NULL); - check_jvmti_error(jvmti, err, "set event notification"); - } exitAgentMonitor(jvmti); -} - -/* Callback for JVMTI_EVENT_VM_DEATH */ -static void JNICALL -vmDeath(jvmtiEnv *jvmti, JNIEnv *env) -{ - jvmtiError err; - - /* Make sure everything has been garbage collected */ - err = (*jvmti)->ForceGarbageCollection(jvmti); - check_jvmti_error(jvmti, err, "force garbage collection"); - - /* Disable events and dump the heap information */ - enterAgentMonitor(jvmti); { - err = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_DISABLE, - JVMTI_EVENT_DATA_DUMP_REQUEST, NULL); - check_jvmti_error(jvmti, err, "set event notification"); - - dataDumpRequest(jvmti); - - gdata->vmDeathCalled = JNI_TRUE; - } exitAgentMonitor(jvmti); -} - -/* Agent_OnLoad() is called first, we prepare for a VM_INIT event here. */ -JNIEXPORT jint JNICALL -DEF_Agent_OnLoad(JavaVM *vm, char *options, void *reserved) -{ - jint rc; - jvmtiError err; - jvmtiCapabilities capabilities; - jvmtiEventCallbacks callbacks; - jvmtiEnv *jvmti; - - /* Get JVMTI environment */ - jvmti = NULL; - rc = (*vm)->GetEnv(vm, (void **)&jvmti, JVMTI_VERSION); - if (rc != JNI_OK) { - fatal_error("ERROR: Unable to create jvmtiEnv, error=%d\n", rc); - return -1; - } - if ( jvmti == NULL ) { - fatal_error("ERROR: No jvmtiEnv* returned from GetEnv\n"); - } - - /* Get/Add JVMTI capabilities */ - (void)memset(&capabilities, 0, sizeof(capabilities)); - capabilities.can_tag_objects = 1; - capabilities.can_generate_garbage_collection_events = 1; - err = (*jvmti)->AddCapabilities(jvmti, &capabilities); - check_jvmti_error(jvmti, err, "add capabilities"); - - /* Create the raw monitor */ - err = (*jvmti)->CreateRawMonitor(jvmti, "agent lock", &(gdata->lock)); - check_jvmti_error(jvmti, err, "create raw monitor"); - - /* Set callbacks and enable event notifications */ - memset(&callbacks, 0, sizeof(callbacks)); - callbacks.VMInit = &vmInit; - callbacks.VMDeath = &vmDeath; - callbacks.DataDumpRequest = &dataDumpRequest; - err = (*jvmti)->SetEventCallbacks(jvmti, &callbacks, sizeof(callbacks)); - check_jvmti_error(jvmti, err, "set event callbacks"); - err = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_VM_INIT, NULL); - check_jvmti_error(jvmti, err, "set event notifications"); - err = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_VM_DEATH, NULL); - check_jvmti_error(jvmti, err, "set event notifications"); - return 0; -} - -/* Agent_OnUnload() is called last */ -JNIEXPORT void JNICALL -DEF_Agent_OnUnload(JavaVM *vm) -{ -}
--- a/jdk/src/demo/share/jvmti/heapViewer/sample.makefile.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,147 +0,0 @@ -# -# Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -######################################################################## -# -# Sample GNU Makefile for building JVMTI Demo heapViewer -# -# Example uses: -# gnumake JDK=<java_home> OSNAME=solaris [OPT=true] [LIBARCH=sparc] -# gnumake JDK=<java_home> OSNAME=solaris [OPT=true] [LIBARCH=sparcv9] -# gnumake JDK=<java_home> OSNAME=linux [OPT=true] -# gnumake JDK=<java_home> OSNAME=win32 [OPT=true] -# -######################################################################## - -# Source lists -LIBNAME=heapViewer -SOURCES=heapViewer.c ../agent_util/agent_util.c - -# Solaris Studio C Compiler Version 12.4 -ifeq ($(OSNAME), solaris) - # Sun Solaris Compiler options needed - COMMON_FLAGS=-mt -KPIC - # Options that help find errors - COMMON_FLAGS+= -Xa -v -xc99=%none - # Check LIBARCH for any special compiler options - LIBARCH=$(shell uname -p) - ifeq ($(LIBARCH), sparc) - COMMON_FLAGS+=-xarch=v8 -xregs=no%appl - endif - ifeq ($(LIBARCH), sparcv9) - COMMON_FLAGS+=-xarch=v9 -xregs=no%appl - endif - ifeq ($(OPT), true) - CFLAGS=-xO2 $(COMMON_FLAGS) - else - CFLAGS=-g $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.o) - # Library name and options needed to build it - LIBRARY=lib$(LIBNAME).so - LDFLAGS=-z defs -ztext - # Libraries we are dependent on - LIBRARIES= -lc - # Building a shared library - LINK_SHARED=$(LINK.c) -G -o $@ -endif - -# Linux GNU C Compiler -ifeq ($(OSNAME), linux) - # GNU Compiler options needed to build it - COMMON_FLAGS=-fno-strict-aliasing -fPIC -fno-omit-frame-pointer - # Options that help find errors - COMMON_FLAGS+= -W -Wall -Wno-unused -Wno-parentheses - ifeq ($(OPT), true) - CFLAGS=-O2 $(COMMON_FLAGS) - else - CFLAGS=-g $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.o) - # Library name and options needed to build it - LIBRARY=lib$(LIBNAME).so - LDFLAGS=-Wl,-soname=$(LIBRARY) -static-libgcc - # Libraries we are dependent on - LIBRARIES=-lc - # Building a shared library - LINK_SHARED=$(LINK.c) -shared -o $@ -endif - -# Windows Microsoft C/C++ Optimizing Compiler Version 12 -ifeq ($(OSNAME), win32) - CC=cl - # Compiler options needed to build it - COMMON_FLAGS=-Gy -DWIN32 - # Options that help find errors - COMMON_FLAGS+=-W0 -WX - ifeq ($(OPT), true) - CFLAGS= -Ox -Op -Zi $(COMMON_FLAGS) - else - CFLAGS= -Od -Zi $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.obj) - # Library name and options needed to build it - LIBRARY=$(LIBNAME).dll - LDFLAGS= - # Libraries we are dependent on - LIBRARIES= - # Building a shared library - LINK_SHARED=link -dll -out:$@ -endif - -# Common -I options -CFLAGS += -I. -CFLAGS += -I$(JDK)/include -I$(JDK)/include/$(OSNAME) - -# Default rule -all: $(LIBRARY) - -# Build native library -$(LIBRARY): $(OBJECTS) - $(LINK_SHARED) $(OBJECTS) $(LIBRARIES) - -# Cleanup the built bits -clean: - rm -f $(LIBRARY) $(OBJECTS) - -# Simple tester -test: all - LD_LIBRARY_PATH=`pwd` $(JDK)/bin/java -agentlib:$(LIBNAME) -version - -# Compilation rule only needed on Windows -ifeq ($(OSNAME), win32) -%.obj: %.c - $(COMPILE.c) $< -endif -
--- a/jdk/src/demo/share/jvmti/index.html Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,430 +0,0 @@ -<html> -<head> <title>JVM TI Demonstration Code</title> </head> - -<h1>JVM TI Demonstration Code</h1> - -<p> -The -Java™ Virtual Machine Tools Interface (JVM TI) -is a native tool interface provided in JDK 5.0 and newer. -Native libraries that use JVM TI and are loaded into the -Java Virtual Machine -via the -agentlib, -agentpath, or -Xrun (deprecated) interfaces, are -called Agents. -<p> -<A HREF="http://java.sun.com/j2se/latest/docs/guide/jvmti">JVM TI</A> -was designed to work with the -Java Native Interface -(<A HREF="http://java.sun.com/j2se/latest/docs/guide/jni">JNI</A>), -and eventually displace the -Java Virtual Machine Debugging Interface -(<A HREF="http://java.sun.com/j2se/1.5.0/docs/guide/jpda/jvmdi-spec.html">JVMDI</A>) -and the -Java Virtual Machine Profiling Interface -(<A HREF="http://java.sun.com/j2se/1.5.0/docs/guide/jvmpi/index.html">JVMPI</A>). - -<p> -We have created a set of demonstration agents that should -help show many of the features and abilities of the -interface. This list of demonstration agents will change over time. -They are provided as educational tools and as starting -points for Java tool development. - -<p> -These agents are built with every JDK build and some basic testing is performed -on a regular basis, but no extensive testbases currently -exist for these agents. -Every JDK installation should include all the pre-built binaries and sources for -all these agents, just look in the demo/jvmti directory of your JDK. - - -<h2>Using or Running These Agents</h2> - -<p> -Using these agents will require the VM to locate the shared library file -before any actual Java code is run. -The JDK installation should contain all the agent libraries in -the ${JAVA_HOME}/demo/jvmti/<i>agent-name</i>/lib directories. -The Solaris 64bit version would be contained in the sparcv9 or amd64 -subdirectory. -If 'java' complains that it can't find the library, -you may need to add the directory containing the library into the -LD_LIBRARY_PATH environment variable (Unix), or the PATH environment -variable (Windows). -This is system and platform specific. -If you are using 64bit Solaris (e.g. 'java -d64'), -you should use LD_LIBRARY_PATH64. -Some agents such as the jdwp (debugger backend) -are located inside the primary JDK directories and will always be found -in those locations. - -<p> -The agents that instrument classfiles -(i.e. BCI, usually through the java_crw_demo library) -such as heapTracker, mtrace, and minst, -also need to have the Java classes they use available in the bootclasspath. -The agents will make attempts at automatically adding their jar file -(e.g. heapTracker.jar, mtrace.jar, or minst.jar) to the bootclasspath -with AddToBootstrapClassLoaderSearch from JVM TI at startup -(see the agent_util code). -This is done by locating this jar file at -${JAVA_HOME}/demo/jvmti/<i>agent-name</i> -where JAVA_HOME is obtained by calling GetSystemProperty from JVM TI -with "java.home". -We recognize that this is not ideal, but felt that as just demonstration -code it was acceptable. -Ideally the agent could find out the actual directory it came from and -locate the jar file relative to that location. -Our demonstration agents currently do not do this. - -<p> -If you choose to modify or change these agents, the above information -is important in making everything is found. -It is recommended that you change the name of the agent when you -modify it to avoid conflicts with the existing demo agents. -Or better yet, go to http://jdk.dev.java.net and submit your -changes to the agent as an RFE to the JDK. - - -<h2> Demonstration Agents Available </h2> - -<ul> - -<li> -<A HREF="versionCheck">versionCheck</A> -<br> -This is a extremely small agent that does nothing but check the -version string supplied in the jvmti.h file, with the version -number supplied by the VM at runtime. -</li> - -<li> -<A HREF="compiledMethodLoad">compiledMethodLoad</A> -<br> -This is a small agent that traces CompiledMethodLoad events along -with the HotSpot specific compile_info parameter. -</li> - -<li> -<A HREF="mtrace">mtrace</A> -<br> -This is a small agent that does method tracing. -It uses Bytecode Instrumentation (BCI) via the java_crw_demo library. -</li> - -<li> -<A HREF="minst">minst</A> -<br> -This is an even smaller agent that does just method entry tracing. -It also uses Bytecode Instrumentation (BCI) via the java_crw_demo library, -but the instrumentation code is pure Java (no Java native methods used). -NOTE: Be sure to check out java.lang.instrument for a way to avoid -native code agents completely. -</li> - -<li> -<A HREF="gctest">gctest</A> -<br> -This is a small agent that does garbage collection counting. -</li> - -<li> -<A HREF="heapViewer">heapViewer</A> -<br> -This is a small agent that does some basic heap inspections. -</li> - -<li> -<A HREF="heapTracker">heapTracker</A> -<br> -This is a small agent that does BCI to capture object creation -and track them. -It uses Bytecode Instrumentation (BCI) via the java_crw_demo library. -</li> - -<li> -<A HREF="waiters">waiters</A> -<br> -This is a small agent that gets information about threads -waiting on monitors. -</li> - -</ul> - - - -<h2>Agent Support</h2> - -<ul> - -<li> -<A HREF="java_crw_demo">java_crw_demo</A> -<br> -This is a demo C library that does class file to class file -transformations or BCI (Bytecode Instrumentation). -It is used by several of the above agents. -</li> - - -</ul> - - - -<h2>Native Library Build Hints</h2> - -<p> -All libraries loaded into java are assumed to be MT-safe (Multi-thread safe). -This means that multiple threads could be executing the code at the same -time, and static or global data may need to be placed in critical -sections. See the Raw Monitor interfaces for more information. - -<p> -All native libraries loaded into the -Java Virtual Machine, -including Agent libraries, -need to be compiled and built in a compatible way. -Certain native compilation options or optimizations should be avoided, -and some are required. -More information on this options is available in the man pages for -the various compilers. - -<p> -Some native compiler and linker options can create fatal or -erroneous behavior when native agent libraries are operating -inside the Java Virtual Machine. -It would take too many words to describe all the possible issues with all -the native compiler options, optimizations, and settings. -Here are some recommendations on the basic compiler and linker options -we recommend: - -<ul> - -<h3> Solaris </h3> - -<li> -On Solaris, using the Sun Studio 11 C compiler, -the typical compile and link command lines might look something like: -<br> -For 32bit SPARC: -<br> -<code><ul> -cc -xO2 -mt -xregs=no%appl -xmemalign=4s -xarch=v8 -KPIC -c <i>*.c</i> -<br> -cc -mt -xarch=v8 -z defs -ztext -G -o <i>libXXX.so *.o</i> -lc -</code></ul> -<br> -For 64bit SPARC: -<br> -<code><ul> -cc -xO2 -mt -xregs=no%appl -xarch=v9 -KPIC -c <i>*.c</i> -<br> -cc -mt -xarch=v9 -z defs -ztext -G -o <i>libXXX.so *.o</i> -lc -</code></ul> -<br> -For X86: -<br> -<code><ul> -cc -xO2 -mt -xregs=no%frameptr -KPIC -c <i>*.c</i> -<br> -cc -mt -z defs -ztext -G -o <i>libXXX.so *.o</i> -lc -</code></ul> -<br> -For AMD64: -<br> -<code><ul> -cc -xO2 -mt -xregs=no%frameptr -xarch=amd64 -KPIC -c <i>*.c</i> -<br> -cc -mt -xarch=amd64 -z defs -ztext -G -o <i>libXXX.so *.o</i> -lc -</code></ul> -<br> -</li> - -<li> -Architecture/File Format: -For SPARC 32bit use <code>-xarch=v8</code>, -for SPARC 64bit use <code>-xarch=v9</code>, -for X86 (32-bit) -<i> -leave the option off or use <code>-xarch=generic</code> -</i>, -and for AMD64 (64bit) use <code>-xarch=amd64</code> -with both C and C++. -<br> -This is to be specific as to the architecture and the file format -of the .o files (and ultimately of the .so). -</li> - -<li> -MT-Safe, Position Independent: Use <code>-KPIC -mt</code> -with both C and C++. -</li> - -<li> -Register usage: For SPARC (both 32bit and 64bit) use -<code>-xregs=no%appl</code> and for X86 and AMD64 use <code>-xregs=no%frameptr</code> -with both C and C++. -</li> - -<li> -Alignment: For SPARC 32bit use -xmemalign=4s and for SPARC 64bit do NOT use <code>-xmemalign=4</code> -with both C and C++. -</li> - -<li> -Dependencies: Use <code>ldd -r <i>LibraryName</i></code>. -<br> -After the shared library has been built, the utility -<code>ldd</code> can be used to verify that all dependent libraries -have been satisfied, and all externs can be found. -If <code>ldd</code> says anything is missing, it is very likely that the JVM will also -be unable to load this library. -This usually means that you missed some <code>-l<i>name</i></code> -options when building the library, or perhaps forgot a <code>-R path</code> -option that tells the library where to look for libraries at runtime. -</li> - -<h3> Linux </h3> - -<li> -On Linux, using the gcc version 3.2, -the typical compile and link command lines might look something like: -<br> -For X86: -<br> -<code><ul> -gcc -O2 -fPIC -pthread -DLINUX -c <i>*.c</i> -<br> -gcc -z defs -static-libgcc -shared -o <i>libXXX.so *.o</i> -lc -</code></ul> -<br> -For AMD64: -<br> -<code><ul> -gcc -O2 -fPIC -pthread -DLINUX -D_LP64=1 -c <i>*.c</i> -<br> -gcc -z defs -static-libgcc -shared -o <i>libXXX.so *.o</i> -lc -</code></ul> -<br> -</li> - -<li> -MT-Safe, Position Independent: -Use <code>-fPIC -pthread</code>. -</li> - -<li> -Agent Demo Code: Needs -DLINUX -</li> - -<li> -Register Usage: Use <code>-fno-omit-frame-pointer</code>. -<br> -It is important that these libraries have frame pointer register usage, see the above comments on the Solaris -<code>-xregs=no%frameptr</code> -option. -</li> - -<li> -Library: Use -static-libgcc. -<br> -When building the shared library (-shared option), this option -allows for maximum portability of the library between different -flavors of Linux. -The problem we have seen with Linux is that we cannot depend -on a compatible shared gcc library existing on all the versions of -Linux we can run on. -By doing this static link, the version script becomes more -important, making sure you don't expose any extern symbols -you didn't intend to. -</li> - -<li> -Dependencies: Use <code>ldd -r <i>LibraryName</i></code>. -<br> -Provides the same checking as Solaris (see above). -</li> - -<h3> Windows </h3> - -<li> -On Windows and using the Microsoft C++ Compiler Visual Studio .NET 2003, -the typical compile and link command lines might look something like: -<br> -For X86: -<br> -<code><ul> -cl /O1 /MD /D _STATIC_CPPLIB /c <i>*.c</i> -<br> -link /dll /opt:REF /out:<i>XXX.dll *.obj</i> -</code></ul> -<br> -For AMD64: -<br> -<code><ul> -cl /O1 /MD /D _STATIC_CPPLIB /c <i>*.c</i> -<br> -link /dll /opt:REF /out:<i>XXX.dll *.obj</i> -</code></ul> -<br> -</li> - -<li> -Library: Use <code>/opt:REF </code> when building the dll. -</li> - -<li> -MS DLL Runtime: Use the <code>/MD /D _STATIC_CPPLIB</code> option. -<br> -This causes your dll to become dependent on just MSVCR*.DLL. -The option /D _STATIC_CPPLIB prevents you from becoming dependent on the -C++ library MSVCP*.DLL. -This is what we use in the JDK, but there are probably many combinations -that you could safely use, unfortunately there are many combinations -of runtimes that will not work. -Check the Microsoft site on proper use of runtimes. -</li> - -<li> -Dependencies: Use VC++ <code>dumpbin /exports</code> and the VC++ "Dependency Walker". -<br> -Provides dependency information similar to <code>ldd</code>. -</li> - -</ul> - - -<h2>For More Information</h2> - -<p> -Remember, the complete source to all these agents is contained in the JDK -installations at demo/jvmti. - -<p> -For more detailed information on JVM TI, refer to -<A HREF="http://java.sun.com/j2se/latest/docs/guide/jvmti"> -http://java.sun.com/j2se/latest/docs/guide/jvmti.</A> - -<p> -More information on using JNI and building native libraries refer to: -<A HREF="http://java.sun.com/j2se/latest/docs/guide/jni"> -http://java.sun.com/j2se/latest/docs/guide/jni</A>. - -<p> -Additional information can also be found by doing a search on "jvmti" at -<A HREF="http://java.sun.com/j2se">http://java.sun.com/j2se</A>. -Various technical articles are also available through this website. -And don't forget the -Java Tutorials at -<A HREF="http://docs.oracle.com/javase/tutorial">http://docs.oracle.com/javase/tutorial</A> -for getting a quick start on all the various interfaces. - -<h2>Comments and Feedback</h2> - -<p> -Comments regarding JVM TI or on any of these demonstrations should be -sent through -<A HREF="http://java.sun.com/mail">http://java.sun.com/mail/</A> - - - -</html>
--- a/jdk/src/demo/share/jvmti/java_crw_demo/README.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,77 +0,0 @@ -# -# Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -java_crw_demo Library - -The library java_crw_demo is a small C library that is used by HPROF -and other agent libraries to do some very basic bytecode -insertion (BCI) of class files. This is not an agent -library but a general purpose library that can be used to do some -very limited bytecode insertion. - -In the demo sources, look for the use of java_crw_demo.h and -the C function java_crw_demo(). The java_crw_demo library is provided -as part of the JRE. - -The basic BCI that this library does includes: - - * On entry to the java.lang.Object init method (signature "()V"), - a invokestatic call to tclass.obj_init_method(object); is inserted. - - * On any newarray type opcode, immediately following it, the array - object is duplicated on the stack and an invokestatic call to - tclass.newarray_method(object); is inserted. - - * On entry to all methods, a invokestatic call to - tclass.call_method(cnum,mnum); is inserted. The agent can map the - two integers (cnum,mnum) to a method in a class, the cnum is the - number provided to the java_crw_demo library when the classfile was - modified. - - * On return from any method (any return opcode), a invokestatic call to - tclass.return_method(cnum,mnum); is inserted. - -Some methods are not modified at all, init methods and finalize methods -whose length is 1 will not be modified. Classes that are designated -"system" will not have their clinit methods modified. In addition, the -method java.lang.Thread.currentThread() is not modified. - -No methods or fields will be added to any class, however new constant -pool entries will be added at the end of the original constant pool table. -The exception, line, and local variable tables for each method is adjusted -for the modification. The bytecodes are compressed to use smaller offsets -and the fewest 'wide' opcodes. - -All attempts are made to minimize the number of bytecodes at each insertion -site, however, classes with N return opcodes or N newarray opcodes will get -N insertions. And only the necessary modification dictated by the input -arguments to java_crw_demo are actually made. -
--- a/jdk/src/demo/share/jvmti/java_crw_demo/java_crw_demo.c Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,2535 +0,0 @@ -/* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - -/* Class reader writer (java_crw_demo) for instrumenting bytecodes */ - -/* - * As long as the callbacks allow for it and the class number is unique, - * this code is completely re-entrant and any number of classfile - * injections can happen at the same time. - * - * The current logic requires a unique number for this class instance - * or (jclass,jobject loader) pair, this is done via the ClassIndex - * in hprof, which is passed in as the 'unsigned cnum' to java_crw_demo(). - * It's up to the user of this interface if it wants to use this - * feature. - * - */ - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -/* Get Java and class file and bytecode information. */ - -#include <jni.h> - -#include "classfile_constants.h" - - -/* Include our own interface for cross check */ - -#include "java_crw_demo.h" - -/* Macros over error functions to capture line numbers */ - -/* Fatal error used in all builds. */ - -/* Use THIS_FILE when it is available. */ -#ifndef THIS_FILE - #define THIS_FILE "java_crw.demo.c" /* Never use __FILE__ */ -#endif - -#define CRW_FATAL(ci, message) fatal_error(ci, message, THIS_FILE, __LINE__) - -#if defined(DEBUG) || !defined(NDEBUG) - - /* This assert macro is only used in the debug builds. */ - #define CRW_ASSERT(ci, cond) \ - ((cond)?(void)0:assert_error(ci, #cond, THIS_FILE, __LINE__)) - -#else - - #define CRW_ASSERT(ci, cond) - -#endif - -#define CRW_ASSERT_MI(mi) CRW_ASSERT((mi)?(mi)->ci:NULL,(mi)!=NULL) - -#define CRW_ASSERT_CI(ci) CRW_ASSERT(ci, ( (ci) != NULL && \ - (ci)->input_position <= (ci)->input_len && \ - (ci)->output_position <= (ci)->output_len) ) - -#define BUFSIZE 256 - -#ifdef _WIN32 -#define snprintf(buffer, count, format, ...) _snprintf_s(buffer, count, _TRUNCATE, format, ##__VA_ARGS__) -#endif - -/* Typedefs for various integral numbers, just for code clarity */ - -typedef unsigned ClassOpcode; /* One opcode */ -typedef unsigned char ByteCode; /* One byte from bytecodes */ -typedef int ByteOffset; /* Byte offset */ -typedef int ClassConstant; /* Constant pool kind */ -typedef long CrwPosition; /* Position in class image */ -typedef unsigned short CrwCpoolIndex; /* Index into constant pool */ - -/* Misc support macros */ - -/* Given the position of an opcode, find the next 4byte boundary position */ -#define NEXT_4BYTE_BOUNDARY(opcode_pos) (((opcode_pos)+4) & (~3)) - -#define LARGEST_INJECTION (12*3) /* 3 injections at same site */ -#define MAXIMUM_NEW_CPOOL_ENTRIES 64 /* don't add more than 32 entries */ - -/* Constant Pool Entry (internal table that mirrors pool in file image) */ - -typedef struct { - const char * ptr; /* Pointer to any string */ - unsigned short len; /* Length of string */ - unsigned int index1; /* 1st 16 bit index or 32bit value. */ - unsigned int index2; /* 2nd 16 bit index or 32bit value. */ - ClassConstant tag; /* Tag or kind of entry. */ -} CrwConstantPoolEntry; - -struct MethodImage; - -/* Class file image storage structure */ - -typedef struct CrwClassImage { - - /* Unique class number for this class */ - unsigned number; - - /* Name of class, given or gotten out of class image */ - const char * name; - - /* Input and Output class images tracking */ - const unsigned char * input; - unsigned char * output; - CrwPosition input_len; - CrwPosition output_len; - CrwPosition input_position; - CrwPosition output_position; - - /* Mirrored constant pool */ - CrwConstantPoolEntry * cpool; - CrwCpoolIndex cpool_max_elements; /* Max count */ - CrwCpoolIndex cpool_count_plus_one; - - /* Input flags about class (e.g. is it a system class) */ - int system_class; - - /* Class access flags gotten from file. */ - unsigned access_flags; - - /* Names of classes and methods. */ - char* tclass_name; /* Name of class that has tracker methods. */ - char* tclass_sig; /* Signature of class */ - char* call_name; /* Method name to call at offset 0 */ - char* call_sig; /* Signature of this method */ - char* return_name; /* Method name to call before any return */ - char* return_sig; /* Signature of this method */ - char* obj_init_name; /* Method name to call in Object <init> */ - char* obj_init_sig; /* Signature of this method */ - char* newarray_name; /* Method name to call after newarray opcodes */ - char* newarray_sig; /* Signature of this method */ - - /* Constant pool index values for new entries */ - CrwCpoolIndex tracker_class_index; - CrwCpoolIndex object_init_tracker_index; - CrwCpoolIndex newarray_tracker_index; - CrwCpoolIndex call_tracker_index; - CrwCpoolIndex return_tracker_index; - CrwCpoolIndex class_number_index; /* Class number in pool */ - - /* Count of injections made into this class */ - int injection_count; - - /* This class must be the java.lang.Object class */ - jboolean is_object_class; - - /* This class must be the java.lang.Thread class */ - jboolean is_thread_class; - - /* Callback functions */ - FatalErrorHandler fatal_error_handler; - MethodNumberRegister mnum_callback; - - /* Table of method names and descr's */ - int method_count; - const char ** method_name; - const char ** method_descr; - struct MethodImage * current_mi; - -} CrwClassImage; - -/* Injection bytecodes (holds injected bytecodes for each code position) */ - -typedef struct { - ByteCode * code; - ByteOffset len; -} Injection; - -/* Method transformation data (allocated/freed as each method is processed) */ - -typedef struct MethodImage { - - /* Back reference to Class image data. */ - CrwClassImage * ci; - - /* Unique method number for this class. */ - unsigned number; - - /* Method name and descr */ - const char * name; - const char * descr; - - /* Map of input bytecode offsets to output bytecode offsets */ - ByteOffset * map; - - /* Bytecode injections for each input bytecode offset */ - Injection * injections; - - /* Widening setting for each input bytecode offset */ - signed char * widening; - - /* Length of original input bytecodes, and new bytecodes. */ - ByteOffset code_len; - ByteOffset new_code_len; - - /* Location in input where bytecodes are located. */ - CrwPosition start_of_input_bytecodes; - - /* Original max_stack and new max stack */ - unsigned max_stack; - unsigned new_max_stack; - - jboolean object_init_method; - jboolean skip_call_return_sites; - - /* Method access flags gotten from file. */ - unsigned access_flags; - -} MethodImage; - -/* ----------------------------------------------------------------- */ -/* General support functions (memory and error handling) */ - -static void -fatal_error(CrwClassImage *ci, const char *message, const char *file, int line) -{ - if ( ci != NULL && ci->fatal_error_handler != NULL ) { - (*ci->fatal_error_handler)(message, file, line); - } else { - /* Normal operation should NEVER reach here */ - /* NO CRW FATAL ERROR HANDLER! */ - (void)fprintf(stderr, "CRW: %s [%s:%d]\n", message, file, line); - } - abort(); -} - -#if defined(DEBUG) || !defined(NDEBUG) -static void -assert_error(CrwClassImage *ci, const char *condition, - const char *file, int line) -{ - char buf[512]; - MethodImage *mi; - ByteOffset byte_code_offset; - - mi = ci->current_mi; - if ( mi != NULL ) { - byte_code_offset = (ByteOffset)(mi->ci->input_position - mi->start_of_input_bytecodes); - } else { - byte_code_offset=-1; - } - - (void)sprintf(buf, - "CRW ASSERTION FAILURE: %s (%s:%s:%d)", - condition, - ci->name==NULL?"?":ci->name, - (mi==NULL||mi->name==NULL)?"?":mi->name, - byte_code_offset); - fatal_error(ci, buf, file, line); -} -#endif - -static void * -allocate(CrwClassImage *ci, int nbytes) -{ - void * ptr; - - if ( nbytes <= 0 ) { - CRW_FATAL(ci, "Cannot allocate <= 0 bytes"); - } - ptr = malloc(nbytes); - if ( ptr == NULL ) { - CRW_FATAL(ci, "Ran out of malloc memory"); - } - return ptr; -} - -static void * -reallocate(CrwClassImage *ci, void *optr, int nbytes) -{ - void * ptr; - - if ( optr == NULL ) { - CRW_FATAL(ci, "Cannot deallocate NULL"); - } - if ( nbytes <= 0 ) { - CRW_FATAL(ci, "Cannot reallocate <= 0 bytes"); - } - ptr = realloc(optr, nbytes); - if ( ptr == NULL ) { - CRW_FATAL(ci, "Ran out of malloc memory"); - } - return ptr; -} - -static void * -allocate_clean(CrwClassImage *ci, int nbytes) -{ - void * ptr; - - if ( nbytes <= 0 ) { - CRW_FATAL(ci, "Cannot allocate <= 0 bytes"); - } - ptr = calloc(nbytes, 1); - if ( ptr == NULL ) { - CRW_FATAL(ci, "Ran out of malloc memory"); - } - return ptr; -} - -static const char * -duplicate(CrwClassImage *ci, const char *str, int len) -{ - char *copy; - - copy = (char*)allocate(ci, len+1); - (void)memcpy(copy, str, len); - copy[len] = 0; - return (const char *)copy; -} - -static void -deallocate(CrwClassImage *ci, void *ptr) -{ - if ( ptr == NULL ) { - CRW_FATAL(ci, "Cannot deallocate NULL"); - } - (void)free(ptr); -} - -/* ----------------------------------------------------------------- */ -/* Functions for reading/writing bytes to/from the class images */ - -static unsigned -readU1(CrwClassImage *ci) -{ - CRW_ASSERT_CI(ci); - return ((unsigned)(ci->input[ci->input_position++])) & 0xFF; -} - -static unsigned -readU2(CrwClassImage *ci) -{ - unsigned res; - - res = readU1(ci); - return (res << 8) + readU1(ci); -} - -static signed short -readS2(CrwClassImage *ci) -{ - unsigned res; - - res = readU1(ci); - return ((res << 8) + readU1(ci)) & 0xFFFF; -} - -static unsigned -readU4(CrwClassImage *ci) -{ - unsigned res; - - res = readU2(ci); - return (res << 16) + readU2(ci); -} - -static void -writeU1(CrwClassImage *ci, unsigned val) /* Only writes out lower 8 bits */ -{ - CRW_ASSERT_CI(ci); - if ( ci->output != NULL ) { - ci->output[ci->output_position++] = val & 0xFF; - } -} - -static void -writeU2(CrwClassImage *ci, unsigned val) -{ - writeU1(ci, val >> 8); - writeU1(ci, val); -} - -static void -writeU4(CrwClassImage *ci, unsigned val) -{ - writeU2(ci, val >> 16); - writeU2(ci, val); -} - -static unsigned -copyU1(CrwClassImage *ci) -{ - unsigned value; - - value = readU1(ci); - writeU1(ci, value); - return value; -} - -static unsigned -copyU2(CrwClassImage *ci) -{ - unsigned value; - - value = readU2(ci); - writeU2(ci, value); - return value; -} - -static unsigned -copyU4(CrwClassImage *ci) -{ - unsigned value; - - value = readU4(ci); - writeU4(ci, value); - return value; -} - -static void -copy(CrwClassImage *ci, unsigned count) -{ - CRW_ASSERT_CI(ci); - if ( ci->output != NULL ) { - (void)memcpy(ci->output+ci->output_position, - ci->input+ci->input_position, count); - ci->output_position += count; - } - ci->input_position += count; - CRW_ASSERT_CI(ci); -} - -static void -skip(CrwClassImage *ci, unsigned count) -{ - CRW_ASSERT_CI(ci); - ci->input_position += count; -} - -static void -read_bytes(CrwClassImage *ci, void *bytes, unsigned count) -{ - CRW_ASSERT_CI(ci); - CRW_ASSERT(ci, bytes!=NULL); - (void)memcpy(bytes, ci->input+ci->input_position, count); - ci->input_position += count; -} - -static void -write_bytes(CrwClassImage *ci, void *bytes, unsigned count) -{ - CRW_ASSERT_CI(ci); - CRW_ASSERT(ci, bytes!=NULL); - if ( ci->output != NULL ) { - (void)memcpy(ci->output+ci->output_position, bytes, count); - ci->output_position += count; - } -} - -static void -random_writeU2(CrwClassImage *ci, CrwPosition pos, unsigned val) -{ - CrwPosition save_position; - - CRW_ASSERT_CI(ci); - save_position = ci->output_position; - ci->output_position = pos; - writeU2(ci, val); - ci->output_position = save_position; -} - -static void -random_writeU4(CrwClassImage *ci, CrwPosition pos, unsigned val) -{ - CrwPosition save_position; - - CRW_ASSERT_CI(ci); - save_position = ci->output_position; - ci->output_position = pos; - writeU4(ci, val); - ci->output_position = save_position; -} - -/* ----------------------------------------------------------------- */ -/* Constant Pool handling functions. */ - -static void -fillin_cpool_entry(CrwClassImage *ci, CrwCpoolIndex i, - ClassConstant tag, - unsigned int index1, unsigned int index2, - const char *ptr, int len) -{ - CRW_ASSERT_CI(ci); - CRW_ASSERT(ci, i > 0 && i < ci->cpool_count_plus_one); - ci->cpool[i].tag = tag; - ci->cpool[i].index1 = index1; - ci->cpool[i].index2 = index2; - ci->cpool[i].ptr = ptr; - ci->cpool[i].len = (unsigned short)len; -} - -static CrwCpoolIndex -add_new_cpool_entry(CrwClassImage *ci, ClassConstant tag, - unsigned int index1, unsigned int index2, - const char *str, int len) -{ - CrwCpoolIndex i; - char *utf8 = NULL; - - CRW_ASSERT_CI(ci); - i = ci->cpool_count_plus_one++; - - /* NOTE: This implementation does not automatically expand the - * constant pool table beyond the expected number needed - * to handle this particular CrwTrackerInterface injections. - * See MAXIMUM_NEW_CPOOL_ENTRIES - */ - CRW_ASSERT(ci, ci->cpool_count_plus_one < ci->cpool_max_elements ); - - writeU1(ci, tag); - switch (tag) { - case JVM_CONSTANT_Class: - writeU2(ci, index1); - break; - case JVM_CONSTANT_String: - writeU2(ci, index1); - break; - case JVM_CONSTANT_Fieldref: - case JVM_CONSTANT_Methodref: - case JVM_CONSTANT_InterfaceMethodref: - case JVM_CONSTANT_Integer: - case JVM_CONSTANT_Float: - case JVM_CONSTANT_NameAndType: - writeU2(ci, index1); - writeU2(ci, index2); - break; - case JVM_CONSTANT_Long: - case JVM_CONSTANT_Double: - writeU4(ci, index1); - writeU4(ci, index2); - ci->cpool_count_plus_one++; - CRW_ASSERT(ci, ci->cpool_count_plus_one < ci->cpool_max_elements ); - break; - case JVM_CONSTANT_Utf8: - CRW_ASSERT(ci, len==(len & 0xFFFF)); - writeU2(ci, len); - write_bytes(ci, (void*)str, len); - utf8 = (char*)duplicate(ci, str, len); - break; - default: - CRW_FATAL(ci, "Unknown constant"); - break; - } - fillin_cpool_entry(ci, i, tag, index1, index2, (const char *)utf8, len); - CRW_ASSERT(ci, i > 0 && i < ci->cpool_count_plus_one); - return i; -} - -static CrwCpoolIndex -add_new_class_cpool_entry(CrwClassImage *ci, const char *class_name) -{ - CrwCpoolIndex name_index; - CrwCpoolIndex class_index; - int len; - - CRW_ASSERT_CI(ci); - CRW_ASSERT(ci, class_name!=NULL); - - len = (int)strlen(class_name); - name_index = add_new_cpool_entry(ci, JVM_CONSTANT_Utf8, len, 0, - class_name, len); - class_index = add_new_cpool_entry(ci, JVM_CONSTANT_Class, name_index, 0, - NULL, 0); - return class_index; -} - -static CrwCpoolIndex -add_new_method_cpool_entry(CrwClassImage *ci, CrwCpoolIndex class_index, - const char *name, const char *descr) -{ - CrwCpoolIndex name_index; - CrwCpoolIndex descr_index; - CrwCpoolIndex name_type_index; - int len; - - CRW_ASSERT_CI(ci); - CRW_ASSERT(ci, name!=NULL); - CRW_ASSERT(ci, descr!=NULL); - len = (int)strlen(name); - name_index = - add_new_cpool_entry(ci, JVM_CONSTANT_Utf8, len, 0, name, len); - len = (int)strlen(descr); - descr_index = - add_new_cpool_entry(ci, JVM_CONSTANT_Utf8, len, 0, descr, len); - name_type_index = - add_new_cpool_entry(ci, JVM_CONSTANT_NameAndType, - name_index, descr_index, NULL, 0); - return add_new_cpool_entry(ci, JVM_CONSTANT_Methodref, - class_index, name_type_index, NULL, 0); -} - -static CrwConstantPoolEntry -cpool_entry(CrwClassImage *ci, CrwCpoolIndex c_index) -{ - CRW_ASSERT_CI(ci); - CRW_ASSERT(ci, c_index > 0 && c_index < ci->cpool_count_plus_one); - return ci->cpool[c_index]; -} - -static void -cpool_setup(CrwClassImage *ci) -{ - CrwCpoolIndex i; - CrwPosition cpool_output_position; - int count_plus_one; - - CRW_ASSERT_CI(ci); - cpool_output_position = ci->output_position; - count_plus_one = copyU2(ci); - CRW_ASSERT(ci, count_plus_one>1); - ci->cpool_max_elements = count_plus_one+MAXIMUM_NEW_CPOOL_ENTRIES; - ci->cpool = (CrwConstantPoolEntry*)allocate_clean(ci, - (int)((ci->cpool_max_elements)*sizeof(CrwConstantPoolEntry))); - ci->cpool_count_plus_one = (CrwCpoolIndex)count_plus_one; - - /* Index zero not in class file */ - for (i = 1; i < count_plus_one; ++i) { - CrwCpoolIndex ipos; - ClassConstant tag; - unsigned int index1; - unsigned int index2; - unsigned len; - char * utf8; - char message[BUFSIZE]; - - ipos = i; - index1 = 0; - index2 = 0; - len = 0; - utf8 = NULL; - - tag = copyU1(ci); - switch (tag) { - case JVM_CONSTANT_Class: - index1 = copyU2(ci); - break; - case JVM_CONSTANT_String: - index1 = copyU2(ci); - break; - case JVM_CONSTANT_Fieldref: - case JVM_CONSTANT_Methodref: - case JVM_CONSTANT_InterfaceMethodref: - case JVM_CONSTANT_Integer: - case JVM_CONSTANT_Float: - case JVM_CONSTANT_NameAndType: - index1 = copyU2(ci); - index2 = copyU2(ci); - break; - case JVM_CONSTANT_Long: - case JVM_CONSTANT_Double: - index1 = copyU4(ci); - index2 = copyU4(ci); - ++i; /* // these take two CP entries - duh! */ - break; - case JVM_CONSTANT_Utf8: - len = copyU2(ci); - index1 = (unsigned short)len; - utf8 = (char*)allocate(ci, len+1); - read_bytes(ci, (void*)utf8, len); - utf8[len] = 0; - write_bytes(ci, (void*)utf8, len); - break; - case JVM_CONSTANT_MethodType: - index1 = copyU2(ci); - break; - case JVM_CONSTANT_MethodHandle: - index1 = copyU1(ci); - index2 = copyU2(ci); - break; - case JVM_CONSTANT_InvokeDynamic: - index1 = copyU2(ci); - index2 = copyU2(ci); - break; - default: - snprintf(message, BUFSIZE, "Unknown tag: %d, at ipos %hu", tag, ipos); - CRW_FATAL(ci, message); - break; - } - fillin_cpool_entry(ci, ipos, tag, index1, index2, (const char *)utf8, len); - } - - if (ci->call_name != NULL || ci->return_name != NULL) { - if ( ci->number != (ci->number & 0x7FFF) ) { - ci->class_number_index = - add_new_cpool_entry(ci, JVM_CONSTANT_Integer, - (ci->number>>16) & 0xFFFF, ci->number & 0xFFFF, NULL, 0); - } - } - - if ( ci->tclass_name != NULL ) { - ci->tracker_class_index = - add_new_class_cpool_entry(ci, ci->tclass_name); - } - if (ci->obj_init_name != NULL) { - ci->object_init_tracker_index = add_new_method_cpool_entry(ci, - ci->tracker_class_index, - ci->obj_init_name, - ci->obj_init_sig); - } - if (ci->newarray_name != NULL) { - ci->newarray_tracker_index = add_new_method_cpool_entry(ci, - ci->tracker_class_index, - ci->newarray_name, - ci->newarray_sig); - } - if (ci->call_name != NULL) { - ci->call_tracker_index = add_new_method_cpool_entry(ci, - ci->tracker_class_index, - ci->call_name, - ci->call_sig); - } - if (ci->return_name != NULL) { - ci->return_tracker_index = add_new_method_cpool_entry(ci, - ci->tracker_class_index, - ci->return_name, - ci->return_sig); - } - - random_writeU2(ci, cpool_output_position, ci->cpool_count_plus_one); -} - -/* ----------------------------------------------------------------- */ -/* Functions that create the bytecodes to inject */ - -static ByteOffset -push_pool_constant_bytecodes(ByteCode *bytecodes, CrwCpoolIndex index) -{ - ByteOffset nbytes = 0; - - if ( index == (index&0x7F) ) { - bytecodes[nbytes++] = (ByteCode)JVM_OPC_ldc; - } else { - bytecodes[nbytes++] = (ByteCode)JVM_OPC_ldc_w; - bytecodes[nbytes++] = (ByteCode)((index >> 8) & 0xFF); - } - bytecodes[nbytes++] = (ByteCode)(index & 0xFF); - return nbytes; -} - -static ByteOffset -push_short_constant_bytecodes(ByteCode *bytecodes, unsigned number) -{ - ByteOffset nbytes = 0; - - if ( number <= 5 ) { - bytecodes[nbytes++] = (ByteCode)(JVM_OPC_iconst_0+number); - } else if ( number == (number&0x7F) ) { - bytecodes[nbytes++] = (ByteCode)JVM_OPC_bipush; - bytecodes[nbytes++] = (ByteCode)(number & 0xFF); - } else { - bytecodes[nbytes++] = (ByteCode)JVM_OPC_sipush; - bytecodes[nbytes++] = (ByteCode)((number >> 8) & 0xFF); - bytecodes[nbytes++] = (ByteCode)(number & 0xFF); - } - return nbytes; -} - -static ByteOffset -injection_template(MethodImage *mi, ByteCode *bytecodes, ByteOffset max_nbytes, - CrwCpoolIndex method_index) -{ - CrwClassImage * ci; - ByteOffset nbytes = 0; - unsigned max_stack; - int add_dup; - int add_aload; - int push_cnum; - int push_mnum; - - ci = mi->ci; - - CRW_ASSERT(ci, bytecodes!=NULL); - - if ( method_index == 0 ) { - return 0; - } - - if ( method_index == ci->newarray_tracker_index) { - max_stack = mi->max_stack + 1; - add_dup = JNI_TRUE; - add_aload = JNI_FALSE; - push_cnum = JNI_FALSE; - push_mnum = JNI_FALSE; - } else if ( method_index == ci->object_init_tracker_index) { - max_stack = mi->max_stack + 1; - add_dup = JNI_FALSE; - add_aload = JNI_TRUE; - push_cnum = JNI_FALSE; - push_mnum = JNI_FALSE; - } else { - max_stack = mi->max_stack + 2; - add_dup = JNI_FALSE; - add_aload = JNI_FALSE; - push_cnum = JNI_TRUE; - push_mnum = JNI_TRUE; - } - - if ( add_dup ) { - bytecodes[nbytes++] = (ByteCode)JVM_OPC_dup; - } - if ( add_aload ) { - bytecodes[nbytes++] = (ByteCode)JVM_OPC_aload_0; - } - if ( push_cnum ) { - if ( ci->number == (ci->number & 0x7FFF) ) { - nbytes += push_short_constant_bytecodes(bytecodes+nbytes, - ci->number); - } else { - CRW_ASSERT(ci, ci->class_number_index!=0); - nbytes += push_pool_constant_bytecodes(bytecodes+nbytes, - ci->class_number_index); - } - } - if ( push_mnum ) { - nbytes += push_short_constant_bytecodes(bytecodes+nbytes, - mi->number); - } - bytecodes[nbytes++] = (ByteCode)JVM_OPC_invokestatic; - bytecodes[nbytes++] = (ByteCode)(method_index >> 8); - bytecodes[nbytes++] = (ByteCode)method_index; - bytecodes[nbytes] = 0; - CRW_ASSERT(ci, nbytes<max_nbytes); - - /* Make sure the new max_stack is appropriate */ - if ( max_stack > mi->new_max_stack ) { - mi->new_max_stack = max_stack; - } - return nbytes; -} - -/* Called to create injection code at entry to a method */ -static ByteOffset -entry_injection_code(MethodImage *mi, ByteCode *bytecodes, ByteOffset len) -{ - CrwClassImage * ci; - ByteOffset nbytes = 0; - - CRW_ASSERT_MI(mi); - - ci = mi->ci; - - if ( mi->object_init_method ) { - nbytes = injection_template(mi, - bytecodes, len, ci->object_init_tracker_index); - } - if ( !mi->skip_call_return_sites ) { - nbytes += injection_template(mi, - bytecodes+nbytes, len-nbytes, ci->call_tracker_index); - } - return nbytes; -} - -/* Called to create injection code before an opcode */ -static ByteOffset -before_injection_code(MethodImage *mi, ClassOpcode opcode, - ByteCode *bytecodes, ByteOffset len) -{ - ByteOffset nbytes = 0; - - - CRW_ASSERT_MI(mi); - switch ( opcode ) { - case JVM_OPC_return: - case JVM_OPC_ireturn: - case JVM_OPC_lreturn: - case JVM_OPC_freturn: - case JVM_OPC_dreturn: - case JVM_OPC_areturn: - if ( !mi->skip_call_return_sites ) { - nbytes = injection_template(mi, - bytecodes, len, mi->ci->return_tracker_index); - } - break; - default: - break; - } - return nbytes; -} - -/* Called to create injection code after an opcode */ -static ByteOffset -after_injection_code(MethodImage *mi, ClassOpcode opcode, - ByteCode *bytecodes, ByteOffset len) -{ - CrwClassImage* ci; - ByteOffset nbytes; - - ci = mi->ci; - nbytes = 0; - - CRW_ASSERT_MI(mi); - switch ( opcode ) { - case JVM_OPC_new: - /* Can't inject here cannot pass around uninitialized object */ - break; - case JVM_OPC_newarray: - case JVM_OPC_anewarray: - case JVM_OPC_multianewarray: - nbytes = injection_template(mi, - bytecodes, len, ci->newarray_tracker_index); - break; - default: - break; - } - return nbytes; -} - -/* Actually inject the bytecodes */ -static void -inject_bytecodes(MethodImage *mi, ByteOffset at, - ByteCode *bytecodes, ByteOffset len) -{ - Injection injection; - CrwClassImage *ci; - - ci = mi->ci; - CRW_ASSERT_MI(mi); - CRW_ASSERT(ci, at <= mi->code_len); - - injection = mi->injections[at]; - - CRW_ASSERT(ci, len <= LARGEST_INJECTION/2); - CRW_ASSERT(ci, injection.len+len <= LARGEST_INJECTION); - - /* Either start an injection area or concatenate to what is there */ - if ( injection.code == NULL ) { - CRW_ASSERT(ci, injection.len==0); - injection.code = (ByteCode *)allocate_clean(ci, LARGEST_INJECTION+1); - } - - (void)memcpy(injection.code+injection.len, bytecodes, len); - injection.len += len; - injection.code[injection.len] = 0; - mi->injections[at] = injection; - ci->injection_count++; -} - -/* ----------------------------------------------------------------- */ -/* Method handling functions */ - -static MethodImage * -method_init(CrwClassImage *ci, unsigned mnum, ByteOffset code_len) -{ - MethodImage * mi; - ByteOffset i; - - mi = (MethodImage*)allocate_clean(ci, (int)sizeof(MethodImage)); - mi->ci = ci; - mi->name = ci->method_name[mnum]; - mi->descr = ci->method_descr[mnum]; - mi->code_len = code_len; - mi->map = (ByteOffset*)allocate_clean(ci, - (int)((code_len+1)*sizeof(ByteOffset))); - for(i=0; i<=code_len; i++) { - mi->map[i] = i; - } - mi->widening = (signed char*)allocate_clean(ci, code_len+1); - mi->injections = (Injection *)allocate_clean(ci, - (int)((code_len+1)*sizeof(Injection))); - mi->number = mnum; - ci->current_mi = mi; - return mi; -} - -static void -method_term(MethodImage *mi) -{ - CrwClassImage *ci; - - ci = mi->ci; - CRW_ASSERT_MI(mi); - if ( mi->map != NULL ) { - deallocate(ci, (void*)mi->map); - mi->map = NULL; - } - if ( mi->widening != NULL ) { - deallocate(ci, (void*)mi->widening); - mi->widening = NULL; - } - if ( mi->injections != NULL ) { - ByteOffset i; - for(i=0; i<= mi->code_len; i++) { - if ( mi->injections[i].code != NULL ) { - deallocate(ci, (void*)mi->injections[i].code); - mi->injections[i].code = NULL; - } - } - deallocate(ci, (void*)mi->injections); - mi->injections = NULL; - } - ci->current_mi = NULL; - deallocate(ci, (void*)mi); -} - -static ByteOffset -input_code_offset(MethodImage *mi) -{ - CRW_ASSERT_MI(mi); - return (ByteOffset)(mi->ci->input_position - mi->start_of_input_bytecodes); -} - -static void -rewind_to_beginning_of_input_bytecodes(MethodImage *mi) -{ - CRW_ASSERT_MI(mi); - mi->ci->input_position = mi->start_of_input_bytecodes; -} - -/* Starting at original byte position 'at', add 'offset' to it's new - * location. This may be a negative value. - * NOTE: That this map is not the new bytecode location of the opcode - * but the new bytecode location that should be used when - * a goto or jump instruction was targeting the old bytecode - * location. - */ -static void -adjust_map(MethodImage *mi, ByteOffset at, ByteOffset offset) -{ - ByteOffset i; - - CRW_ASSERT_MI(mi); - for (i = at; i <= mi->code_len; ++i) { - mi->map[i] += offset; - } -} - -static void -widen(MethodImage *mi, ByteOffset at, ByteOffset len) -{ - int delta; - - CRW_ASSERT(mi->ci, at <= mi->code_len); - delta = len - mi->widening[at]; - /* Adjust everything from the current input location by delta */ - adjust_map(mi, input_code_offset(mi), delta); - /* Mark at beginning of instruction */ - mi->widening[at] = (signed char)len; -} - -static void -verify_opc_wide(CrwClassImage *ci, ClassOpcode wopcode) -{ - switch (wopcode) { - case JVM_OPC_aload: case JVM_OPC_astore: - case JVM_OPC_fload: case JVM_OPC_fstore: - case JVM_OPC_iload: case JVM_OPC_istore: - case JVM_OPC_lload: case JVM_OPC_lstore: - case JVM_OPC_dload: case JVM_OPC_dstore: - case JVM_OPC_ret: case JVM_OPC_iinc: - break; - default: - CRW_FATAL(ci, "Invalid opcode supplied to wide opcode"); - break; - } -} - -static unsigned -opcode_length(CrwClassImage *ci, ClassOpcode opcode) -{ - /* Define array that holds length of an opcode */ - static unsigned char _opcode_length[JVM_OPC_MAX+1] = - JVM_OPCODE_LENGTH_INITIALIZER; - - if ( opcode > JVM_OPC_MAX ) { - CRW_FATAL(ci, "Invalid opcode supplied to opcode_length()"); - } - return _opcode_length[opcode]; -} - -/* Walk one instruction and inject instrumentation */ -static void -inject_for_opcode(MethodImage *mi) -{ - CrwClassImage * ci; - ClassOpcode opcode; - int pos; - - CRW_ASSERT_MI(mi); - ci = mi->ci; - pos = input_code_offset(mi); - opcode = readU1(ci); - - if (opcode == JVM_OPC_wide) { - ClassOpcode wopcode; - - wopcode = readU1(ci); - /* lvIndex not used */ - (void)readU2(ci); - verify_opc_wide(ci, wopcode); - if ( wopcode==JVM_OPC_iinc ) { - (void)readU1(ci); - (void)readU1(ci); - } - } else { - - ByteCode bytecodes[LARGEST_INJECTION+1]; - int header; - int instr_len; - int low; - int high; - int npairs; - ByteOffset len; - - /* Get bytecodes to inject before this opcode */ - len = before_injection_code(mi, opcode, bytecodes, (int)sizeof(bytecodes)); - if ( len > 0 ) { - inject_bytecodes(mi, pos, bytecodes, len); - /* Adjust map after processing this opcode */ - } - - /* Process this opcode */ - switch (opcode) { - case JVM_OPC_tableswitch: - header = NEXT_4BYTE_BOUNDARY(pos); - skip(ci, header - (pos+1)); - (void)readU4(ci); - low = readU4(ci); - high = readU4(ci); - skip(ci, (high+1-low) * 4); - break; - case JVM_OPC_lookupswitch: - header = NEXT_4BYTE_BOUNDARY(pos); - skip(ci, header - (pos+1)); - (void)readU4(ci); - npairs = readU4(ci); - skip(ci, npairs * 8); - break; - default: - instr_len = opcode_length(ci, opcode); - skip(ci, instr_len-1); - break; - } - - /* Get position after this opcode is processed */ - pos = input_code_offset(mi); - - /* Adjust for any before_injection_code() */ - if ( len > 0 ) { - /* Adjust everything past this opcode. - * Why past it? Because we want any jumps to this bytecode loc - * to go to the injected code, not where the opcode - * was moved too. - * Consider a 'return' opcode that is jumped too. - * NOTE: This may not be correct in all cases, but will - * when we are only dealing with non-variable opcodes - * like the return opcodes. Be careful if the - * before_injection_code() changes to include other - * opcodes that have variable length. - */ - adjust_map(mi, pos, len); - } - - /* Get bytecodes to inject after this opcode */ - len = after_injection_code(mi, opcode, bytecodes, (int)sizeof(bytecodes)); - if ( len > 0 ) { - inject_bytecodes(mi, pos, bytecodes, len); - - /* Adjust for any after_injection_code() */ - adjust_map(mi, pos, len); - } - - } -} - -/* Map original bytecode location to it's new location. (See adjust_map()). */ -static ByteOffset -method_code_map(MethodImage *mi, ByteOffset pos) -{ - CRW_ASSERT_MI(mi); - CRW_ASSERT(mi->ci, pos <= mi->code_len); - return mi->map[pos]; -} - -static int -adjust_instruction(MethodImage *mi) -{ - CrwClassImage * ci; - ClassOpcode opcode; - int pos; - int new_pos; - - CRW_ASSERT_MI(mi); - ci = mi->ci; - pos = input_code_offset(mi); - new_pos = method_code_map(mi,pos); - - opcode = readU1(ci); - - if (opcode == JVM_OPC_wide) { - ClassOpcode wopcode; - - wopcode = readU1(ci); - /* lvIndex not used */ - (void)readU2(ci); - verify_opc_wide(ci, wopcode); - if ( wopcode==JVM_OPC_iinc ) { - (void)readU1(ci); - (void)readU1(ci); - } - } else { - - int widened; - int header; - int newHeader; - int low; - int high; - int new_pad; - int old_pad; - int delta; - int new_delta; - int delta_pad; - int npairs; - int instr_len; - - switch (opcode) { - - case JVM_OPC_tableswitch: - widened = mi->widening[pos]; - header = NEXT_4BYTE_BOUNDARY(pos); - newHeader = NEXT_4BYTE_BOUNDARY(new_pos); - - skip(ci, header - (pos+1)); - - delta = readU4(ci); - low = readU4(ci); - high = readU4(ci); - skip(ci, (high+1-low) * 4); - new_pad = newHeader - new_pos; - old_pad = header - pos; - delta_pad = new_pad - old_pad; - if (widened != delta_pad) { - widen(mi, pos, delta_pad); - return 0; - } - break; - - case JVM_OPC_lookupswitch: - widened = mi->widening[pos]; - header = NEXT_4BYTE_BOUNDARY(pos); - newHeader = NEXT_4BYTE_BOUNDARY(new_pos); - - skip(ci, header - (pos+1)); - - delta = readU4(ci); - npairs = readU4(ci); - skip(ci, npairs * 8); - new_pad = newHeader - new_pos; - old_pad = header - pos; - delta_pad = new_pad - old_pad; - if (widened != delta_pad) { - widen(mi, pos, delta_pad); - return 0; - } - break; - - case JVM_OPC_jsr: case JVM_OPC_goto: - case JVM_OPC_ifeq: case JVM_OPC_ifge: case JVM_OPC_ifgt: - case JVM_OPC_ifle: case JVM_OPC_iflt: case JVM_OPC_ifne: - case JVM_OPC_if_icmpeq: case JVM_OPC_if_icmpne: case JVM_OPC_if_icmpge: - case JVM_OPC_if_icmpgt: case JVM_OPC_if_icmple: case JVM_OPC_if_icmplt: - case JVM_OPC_if_acmpeq: case JVM_OPC_if_acmpne: - case JVM_OPC_ifnull: case JVM_OPC_ifnonnull: - widened = mi->widening[pos]; - delta = readS2(ci); - if (widened == 0) { - new_delta = method_code_map(mi,pos+delta) - new_pos; - if ((new_delta < -32768) || (new_delta > 32767)) { - switch (opcode) { - case JVM_OPC_jsr: case JVM_OPC_goto: - widen(mi, pos, 2); - break; - default: - widen(mi, pos, 5); - break; - } - return 0; - } - } - break; - - case JVM_OPC_jsr_w: - case JVM_OPC_goto_w: - (void)readU4(ci); - break; - - default: - instr_len = opcode_length(ci, opcode); - skip(ci, instr_len-1); - break; - } - } - return 1; -} - -static void -write_instruction(MethodImage *mi) -{ - CrwClassImage * ci; - ClassOpcode opcode; - ByteOffset new_code_len; - int pos; - int new_pos; - - CRW_ASSERT_MI(mi); - ci = mi->ci; - pos = input_code_offset(mi); - new_pos = method_code_map(mi,pos); - new_code_len = mi->injections[pos].len; - if (new_code_len > 0) { - write_bytes(ci, (void*)mi->injections[pos].code, new_code_len); - } - - opcode = readU1(ci); - if (opcode == JVM_OPC_wide) { - ClassOpcode wopcode; - - writeU1(ci, opcode); - - wopcode = copyU1(ci); - /* lvIndex not used */ - (void)copyU2(ci); - verify_opc_wide(ci, wopcode); - if ( wopcode==JVM_OPC_iinc ) { - (void)copyU1(ci); - (void)copyU1(ci); - } - } else { - - ClassOpcode new_opcode; - int header; - int newHeader; - int low; - int high; - int i; - int npairs; - int widened; - int instr_len; - int delta; - int new_delta; - - switch (opcode) { - - case JVM_OPC_tableswitch: - header = NEXT_4BYTE_BOUNDARY(pos); - newHeader = NEXT_4BYTE_BOUNDARY(new_pos); - - skip(ci, header - (pos+1)); - - delta = readU4(ci); - new_delta = method_code_map(mi,pos+delta) - new_pos; - low = readU4(ci); - high = readU4(ci); - - writeU1(ci, opcode); - for (i = new_pos+1; i < newHeader; ++i) { - writeU1(ci, 0); - } - writeU4(ci, new_delta); - writeU4(ci, low); - writeU4(ci, high); - - for (i = low; i <= high; ++i) { - delta = readU4(ci); - new_delta = method_code_map(mi,pos+delta) - new_pos; - writeU4(ci, new_delta); - } - break; - - case JVM_OPC_lookupswitch: - header = NEXT_4BYTE_BOUNDARY(pos); - newHeader = NEXT_4BYTE_BOUNDARY(new_pos); - - skip(ci, header - (pos+1)); - - delta = readU4(ci); - new_delta = method_code_map(mi,pos+delta) - new_pos; - npairs = readU4(ci); - writeU1(ci, opcode); - for (i = new_pos+1; i < newHeader; ++i) { - writeU1(ci, 0); - } - writeU4(ci, new_delta); - writeU4(ci, npairs); - for (i = 0; i< npairs; ++i) { - unsigned match = readU4(ci); - delta = readU4(ci); - new_delta = method_code_map(mi,pos+delta) - new_pos; - writeU4(ci, match); - writeU4(ci, new_delta); - } - break; - - case JVM_OPC_jsr: case JVM_OPC_goto: - case JVM_OPC_ifeq: case JVM_OPC_ifge: case JVM_OPC_ifgt: - case JVM_OPC_ifle: case JVM_OPC_iflt: case JVM_OPC_ifne: - case JVM_OPC_if_icmpeq: case JVM_OPC_if_icmpne: case JVM_OPC_if_icmpge: - case JVM_OPC_if_icmpgt: case JVM_OPC_if_icmple: case JVM_OPC_if_icmplt: - case JVM_OPC_if_acmpeq: case JVM_OPC_if_acmpne: - case JVM_OPC_ifnull: case JVM_OPC_ifnonnull: - widened = mi->widening[pos]; - delta = readS2(ci); - new_delta = method_code_map(mi,pos+delta) - new_pos; - new_opcode = opcode; - if (widened == 0) { - writeU1(ci, opcode); - writeU2(ci, new_delta); - } else if (widened == 2) { - switch (opcode) { - case JVM_OPC_jsr: - new_opcode = JVM_OPC_jsr_w; - break; - case JVM_OPC_goto: - new_opcode = JVM_OPC_goto_w; - break; - default: - CRW_FATAL(ci, "unexpected opcode"); - break; - } - writeU1(ci, new_opcode); - writeU4(ci, new_delta); - } else if (widened == 5) { - switch (opcode) { - case JVM_OPC_ifeq: - new_opcode = JVM_OPC_ifne; - break; - case JVM_OPC_ifge: - new_opcode = JVM_OPC_iflt; - break; - case JVM_OPC_ifgt: - new_opcode = JVM_OPC_ifle; - break; - case JVM_OPC_ifle: - new_opcode = JVM_OPC_ifgt; - break; - case JVM_OPC_iflt: - new_opcode = JVM_OPC_ifge; - break; - case JVM_OPC_ifne: - new_opcode = JVM_OPC_ifeq; - break; - case JVM_OPC_if_icmpeq: - new_opcode = JVM_OPC_if_icmpne; - break; - case JVM_OPC_if_icmpne: - new_opcode = JVM_OPC_if_icmpeq; - break; - case JVM_OPC_if_icmpge: - new_opcode = JVM_OPC_if_icmplt; - break; - case JVM_OPC_if_icmpgt: - new_opcode = JVM_OPC_if_icmple; - break; - case JVM_OPC_if_icmple: - new_opcode = JVM_OPC_if_icmpgt; - break; - case JVM_OPC_if_icmplt: - new_opcode = JVM_OPC_if_icmpge; - break; - case JVM_OPC_if_acmpeq: - new_opcode = JVM_OPC_if_acmpne; - break; - case JVM_OPC_if_acmpne: - new_opcode = JVM_OPC_if_acmpeq; - break; - case JVM_OPC_ifnull: - new_opcode = JVM_OPC_ifnonnull; - break; - case JVM_OPC_ifnonnull: - new_opcode = JVM_OPC_ifnull; - break; - default: - CRW_FATAL(ci, "Unexpected opcode"); - break; - } - writeU1(ci, new_opcode); /* write inverse branch */ - writeU2(ci, 3 + 5); /* beyond if and goto_w */ - writeU1(ci, JVM_OPC_goto_w); /* add a goto_w */ - writeU4(ci, new_delta-3); /* write new and wide delta */ - } else { - CRW_FATAL(ci, "Unexpected widening"); - } - break; - - case JVM_OPC_jsr_w: - case JVM_OPC_goto_w: - delta = readU4(ci); - new_delta = method_code_map(mi,pos+delta) - new_pos; - writeU1(ci, opcode); - writeU4(ci, new_delta); - break; - - default: - instr_len = opcode_length(ci, opcode); - writeU1(ci, opcode); - copy(ci, instr_len-1); - break; - } - } -} - -static void -method_inject_and_write_code(MethodImage *mi) -{ - ByteCode bytecodes[LARGEST_INJECTION+1]; - ByteOffset len; - - CRW_ASSERT_MI(mi); - - /* Do injections */ - rewind_to_beginning_of_input_bytecodes(mi); - len = entry_injection_code(mi, bytecodes, (int)sizeof(bytecodes)); - if ( len > 0 ) { - int pos; - - pos = 0; - inject_bytecodes(mi, pos, bytecodes, len); - /* Adjust pos 0 to map to new pos 0, you never want to - * jump into this entry code injection. So the new pos 0 - * will be past this entry_injection_code(). - */ - adjust_map(mi, pos, len); /* Inject before behavior */ - } - while (input_code_offset(mi) < mi->code_len) { - inject_for_opcode(mi); - } - - /* Adjust instructions */ - rewind_to_beginning_of_input_bytecodes(mi); - while (input_code_offset(mi) < mi->code_len) { - if (!adjust_instruction(mi)) { - rewind_to_beginning_of_input_bytecodes(mi); - } - } - - /* Write new instructions */ - rewind_to_beginning_of_input_bytecodes(mi); - while (input_code_offset(mi) < mi->code_len) { - write_instruction(mi); - } -} - -static void -copy_attribute(CrwClassImage *ci) -{ - int len; - - (void)copyU2(ci); - len = copyU4(ci); - copy(ci, len); -} - -static void -copy_attributes(CrwClassImage *ci) -{ - unsigned i; - unsigned count; - - count = copyU2(ci); - for (i = 0; i < count; ++i) { - copy_attribute(ci); - } -} - -static void -copy_all_fields(CrwClassImage *ci) -{ - unsigned i; - unsigned count; - - count = copyU2(ci); - for (i = 0; i < count; ++i) { - /* access, name, descriptor */ - copy(ci, 6); - copy_attributes(ci); - } -} - -static void -write_line_table(MethodImage *mi) -{ - unsigned i; - unsigned count; - CrwClassImage * ci; - - CRW_ASSERT_MI(mi); - ci = mi->ci; - (void)copyU4(ci); - count = copyU2(ci); - for(i=0; i<count; i++) { - ByteOffset start_pc; - ByteOffset new_start_pc; - - start_pc = readU2(ci); - - if ( start_pc == 0 ) { - new_start_pc = 0; /* Don't skip entry injection code. */ - } else { - new_start_pc = method_code_map(mi, start_pc); - } - - writeU2(ci, new_start_pc); - (void)copyU2(ci); - } -} - -/* Used for LocalVariableTable and LocalVariableTypeTable attributes */ -static void -write_var_table(MethodImage *mi) -{ - unsigned i; - unsigned count; - CrwClassImage * ci; - - CRW_ASSERT_MI(mi); - ci = mi->ci; - (void)copyU4(ci); - count = copyU2(ci); - for(i=0; i<count; i++) { - ByteOffset start_pc; - ByteOffset new_start_pc; - ByteOffset length; - ByteOffset new_length; - ByteOffset end_pc; - ByteOffset new_end_pc; - - start_pc = readU2(ci); - length = readU2(ci); - - if ( start_pc == 0 ) { - new_start_pc = 0; /* Don't skip entry injection code. */ - } else { - new_start_pc = method_code_map(mi, start_pc); - } - end_pc = start_pc + length; - new_end_pc = method_code_map(mi, end_pc); - new_length = new_end_pc - new_start_pc; - - writeU2(ci, new_start_pc); - writeU2(ci, new_length); - (void)copyU2(ci); - (void)copyU2(ci); - (void)copyU2(ci); - } -} - -/* The uoffset field is u2 or u4 depending on the code_len. - * Note that the code_len is likely changing, so be careful here. - */ -static unsigned -readUoffset(MethodImage *mi) -{ - if ( mi->code_len > 65535 ) { - return readU4(mi->ci); - } - return readU2(mi->ci); -} - -static void -writeUoffset(MethodImage *mi, unsigned val) -{ - if ( mi->new_code_len > 65535 ) { - writeU4(mi->ci, val); - } - writeU2(mi->ci, val); -} - -static unsigned -copyUoffset(MethodImage *mi) -{ - unsigned uoffset; - - uoffset = readUoffset(mi); - writeUoffset(mi, uoffset); - return uoffset; -} - -/* Copy over verification_type_info structure */ -static void -copy_verification_types(MethodImage *mi, int ntypes) -{ - /* If there were ntypes, we just copy that over, no changes */ - if ( ntypes > 0 ) { - int j; - - for ( j = 0 ; j < ntypes ; j++ ) { - unsigned tag; - - tag = copyU1(mi->ci); - switch ( tag ) { - case JVM_ITEM_Object: - (void)copyU2(mi->ci); /* Constant pool entry */ - break; - case JVM_ITEM_Uninitialized: - /* Code offset for 'new' opcode is for this object */ - writeUoffset(mi, method_code_map(mi, readUoffset(mi))); - break; - } - } - } -} - -/* Process the StackMapTable attribute. We didn't add any basic blocks - * so the frame count remains the same but we may need to process the - * frame types due to offset changes putting things out of range. - */ -static void -write_stackmap_table(MethodImage *mi) -{ - CrwClassImage *ci; - CrwPosition save_position; - ByteOffset last_pc; - ByteOffset last_new_pc; - unsigned i; - unsigned attr_len; - unsigned new_attr_len; - unsigned count; - unsigned delta_adj; - - CRW_ASSERT_MI(mi); - ci = mi->ci; - - /* Save the position of the attribute length so we can fix it later */ - save_position = ci->output_position; - attr_len = copyU4(ci); - count = copyUoffset(mi); /* uoffset: number_of_entries */ - if ( count == 0 ) { - CRW_ASSERT(ci, attr_len==2); - return; - } - - /* Process entire stackmap */ - last_pc = 0; - last_new_pc = 0; - delta_adj = 0; - for ( i = 0 ; i < count ; i++ ) { - ByteOffset new_pc=0; /* new pc in instrumented code */ - unsigned ft; /* frame_type */ - int delta=0; /* pc delta */ - int new_delta=0; /* new pc delta */ - - ft = readU1(ci); - if ( ft <= 63 ) { - /* Frame Type: same_frame ([0,63]) */ - unsigned new_ft; /* new frame_type */ - - delta = (delta_adj + ft); - new_pc = method_code_map(mi, last_pc + delta); - new_delta = new_pc - last_new_pc; - new_ft = (new_delta - delta_adj); - if ( new_ft > 63 ) { - /* Change to same_frame_extended (251) */ - new_ft = 251; - writeU1(ci, new_ft); - writeUoffset(mi, (new_delta - delta_adj)); - } else { - writeU1(ci, new_ft); - } - } else if ( ft >= 64 && ft <= 127 ) { - /* Frame Type: same_locals_1_stack_item_frame ([64,127]) */ - unsigned new_ft; /* new frame_type */ - - delta = (delta_adj + ft - 64); - new_pc = method_code_map(mi, last_pc + delta); - new_delta = new_pc - last_new_pc; - if ( (new_delta - delta_adj) > 63 ) { - /* Change to same_locals_1_stack_item_frame_extended (247) */ - new_ft = 247; - writeU1(ci, new_ft); - writeUoffset(mi, (new_delta - delta_adj)); - } else { - new_ft = (new_delta - delta_adj) + 64; - writeU1(ci, new_ft); - } - copy_verification_types(mi, 1); - } else if ( ft >= 128 && ft <= 246 ) { - /* Frame Type: reserved_for_future_use ([128,246]) */ - CRW_FATAL(ci, "Unknown frame type in StackMapTable attribute"); - } else if ( ft == 247 ) { - /* Frame Type: same_locals_1_stack_item_frame_extended (247) */ - delta = (delta_adj + readUoffset(mi)); - new_pc = method_code_map(mi, last_pc + delta); - new_delta = new_pc - last_new_pc; - writeU1(ci, ft); - writeUoffset(mi, (new_delta - delta_adj)); - copy_verification_types(mi, 1); - } else if ( ft >= 248 && ft <= 250 ) { - /* Frame Type: chop_frame ([248,250]) */ - delta = (delta_adj + readUoffset(mi)); - new_pc = method_code_map(mi, last_pc + delta); - new_delta = new_pc - last_new_pc; - writeU1(ci, ft); - writeUoffset(mi, (new_delta - delta_adj)); - } else if ( ft == 251 ) { - /* Frame Type: same_frame_extended (251) */ - delta = (delta_adj + readUoffset(mi)); - new_pc = method_code_map(mi, last_pc + delta); - new_delta = new_pc - last_new_pc; - writeU1(ci, ft); - writeUoffset(mi, (new_delta - delta_adj)); - } else if ( ft >= 252 && ft <= 254 ) { - /* Frame Type: append_frame ([252,254]) */ - delta = (delta_adj + readUoffset(mi)); - new_pc = method_code_map(mi, last_pc + delta); - new_delta = new_pc - last_new_pc; - writeU1(ci, ft); - writeUoffset(mi, (new_delta - delta_adj)); - copy_verification_types(mi, (ft - 251)); - } else if ( ft == 255 ) { - unsigned ntypes; - - /* Frame Type: full_frame (255) */ - delta = (delta_adj + readUoffset(mi)); - new_pc = method_code_map(mi, last_pc + delta); - new_delta = new_pc - last_new_pc; - writeU1(ci, ft); - writeUoffset(mi, (new_delta - delta_adj)); - ntypes = copyU2(ci); /* ulocalvar */ - copy_verification_types(mi, ntypes); - ntypes = copyU2(ci); /* ustack */ - copy_verification_types(mi, ntypes); - } - - /* Update last_pc and last_new_pc (save on calls to method_code_map) */ - CRW_ASSERT(ci, delta >= 0); - CRW_ASSERT(ci, new_delta >= 0); - last_pc += delta; - last_new_pc = new_pc; - CRW_ASSERT(ci, last_pc <= mi->code_len); - CRW_ASSERT(ci, last_new_pc <= mi->new_code_len); - - /* Delta adjustment, all deltas are -1 now in attribute */ - delta_adj = 1; - } - - /* Update the attribute length */ - new_attr_len = ci->output_position - (save_position + 4); - CRW_ASSERT(ci, new_attr_len >= attr_len); - random_writeU4(ci, save_position, new_attr_len); -} - -/* Process the CLDC StackMap attribute. We didn't add any basic blocks - * so the frame count remains the same but we may need to process the - * frame types due to offset changes putting things out of range. - */ -static void -write_cldc_stackmap_table(MethodImage *mi) -{ - CrwClassImage *ci; - CrwPosition save_position; - unsigned i; - unsigned attr_len; - unsigned new_attr_len; - unsigned count; - - CRW_ASSERT_MI(mi); - ci = mi->ci; - - /* Save the position of the attribute length so we can fix it later */ - save_position = ci->output_position; - attr_len = copyU4(ci); - count = copyUoffset(mi); /* uoffset: number_of_entries */ - if ( count == 0 ) { - CRW_ASSERT(ci, attr_len==2); - return; - } - - /* Process entire stackmap */ - for ( i = 0 ; i < count ; i++ ) { - unsigned ntypes; - - writeUoffset(mi, method_code_map(mi, readUoffset(mi))); - ntypes = copyU2(ci); /* ulocalvar */ - copy_verification_types(mi, ntypes); - ntypes = copyU2(ci); /* ustack */ - copy_verification_types(mi, ntypes); - } - - /* Update the attribute length */ - new_attr_len = ci->output_position - (save_position + 4); - CRW_ASSERT(ci, new_attr_len >= attr_len); - random_writeU4(ci, save_position, new_attr_len); -} - -static void -method_write_exception_table(MethodImage *mi) -{ - unsigned i; - unsigned count; - CrwClassImage * ci; - - CRW_ASSERT_MI(mi); - ci = mi->ci; - count = copyU2(ci); - for(i=0; i<count; i++) { - ByteOffset start_pc; - ByteOffset new_start_pc; - ByteOffset end_pc; - ByteOffset new_end_pc; - ByteOffset handler_pc; - ByteOffset new_handler_pc; - - start_pc = readU2(ci); - end_pc = readU2(ci); - handler_pc = readU2(ci); - - new_start_pc = method_code_map(mi, start_pc); - new_end_pc = method_code_map(mi, end_pc); - new_handler_pc = method_code_map(mi, handler_pc); - - writeU2(ci, new_start_pc); - writeU2(ci, new_end_pc); - writeU2(ci, new_handler_pc); - (void)copyU2(ci); - } -} - -static int -attribute_match(CrwClassImage *ci, CrwCpoolIndex name_index, const char *name) -{ - CrwConstantPoolEntry cs; - int len; - - CRW_ASSERT_CI(ci); - CRW_ASSERT(ci, name!=NULL); - len = (int)strlen(name); - cs = cpool_entry(ci, name_index); - if ( cs.len==len && strncmp(cs.ptr, name, len)==0) { - return 1; - } - return 0; -} - -static void -method_write_code_attribute(MethodImage *mi) -{ - CrwClassImage * ci; - CrwCpoolIndex name_index; - - CRW_ASSERT_MI(mi); - ci = mi->ci; - name_index = copyU2(ci); - if ( attribute_match(ci, name_index, "LineNumberTable") ) { - write_line_table(mi); - } else if ( attribute_match(ci, name_index, "LocalVariableTable") ) { - write_var_table(mi); - } else if ( attribute_match(ci, name_index, "LocalVariableTypeTable") ) { - write_var_table(mi); /* Exact same format as the LocalVariableTable */ - } else if ( attribute_match(ci, name_index, "StackMapTable") ) { - write_stackmap_table(mi); - } else if ( attribute_match(ci, name_index, "StackMap") ) { - write_cldc_stackmap_table(mi); - } else { - unsigned len; - len = copyU4(ci); - copy(ci, len); - } -} - -static int -is_init_method(const char *name) -{ - if ( name!=NULL && strcmp(name,"<init>")==0 ) { - return JNI_TRUE; - } - return JNI_FALSE; -} - -static int -is_clinit_method(const char *name) -{ - if ( name!=NULL && strcmp(name,"<clinit>")==0 ) { - return JNI_TRUE; - } - return JNI_FALSE; -} - -static int -is_finalize_method(const char *name) -{ - if ( name!=NULL && strcmp(name,"finalize")==0 ) { - return JNI_TRUE; - } - return JNI_FALSE; -} - -static int -skip_method(CrwClassImage *ci, const char *name, - unsigned access_flags, ByteOffset code_len, - int system_class, jboolean *pskip_call_return_sites) -{ - *pskip_call_return_sites = JNI_FALSE; - if ( system_class ) { - if ( code_len == 1 && is_init_method(name) ) { - return JNI_TRUE; - } else if ( code_len == 1 && is_finalize_method(name) ) { - return JNI_TRUE; - } else if ( is_clinit_method(name) ) { - return JNI_TRUE; - } else if ( ci->is_thread_class && strcmp(name,"currentThread")==0 ) { - return JNI_TRUE; - } - /* - if ( access_flags & JVM_ACC_PRIVATE ) { - *pskip_call_return_sites = JNI_TRUE; - } - */ - } - return JNI_FALSE; -} - -/* Process all code attributes */ -static void -method_write_bytecodes(CrwClassImage *ci, unsigned mnum, unsigned access_flags) -{ - CrwPosition output_attr_len_position; - CrwPosition output_max_stack_position; - CrwPosition output_code_len_position; - CrwPosition start_of_output_bytecodes; - unsigned i; - unsigned attr_len; - unsigned max_stack; - ByteOffset code_len; - unsigned attr_count; - unsigned new_attr_len; - MethodImage * mi; - jboolean object_init_method; - jboolean skip_call_return_sites; - - CRW_ASSERT_CI(ci); - - /* Attribute Length */ - output_attr_len_position = ci->output_position; - attr_len = copyU4(ci); - - /* Max Stack */ - output_max_stack_position = ci->output_position; - max_stack = copyU2(ci); - - /* Max Locals */ - (void)copyU2(ci); - - /* Code Length */ - output_code_len_position = ci->output_position; - code_len = copyU4(ci); - start_of_output_bytecodes = ci->output_position; - - /* Some methods should not be instrumented */ - object_init_method = JNI_FALSE; - skip_call_return_sites = JNI_FALSE; - if ( ci->is_object_class && - is_init_method(ci->method_name[mnum]) && - strcmp(ci->method_descr[mnum],"()V")==0 ) { - object_init_method = JNI_TRUE; - skip_call_return_sites = JNI_TRUE; - } else if ( skip_method(ci, ci->method_name[mnum], access_flags, - code_len, ci->system_class, &skip_call_return_sites) ) { - /* Copy remainder minus already copied, the U2 max_stack, - * U2 max_locals, and U4 code_length fields have already - * been processed. - */ - copy(ci, attr_len - (2+2+4)); - return; - } - - /* Start Injection */ - mi = method_init(ci, mnum, code_len); - mi->object_init_method = object_init_method; - mi->access_flags = access_flags; - mi->skip_call_return_sites = skip_call_return_sites; - - /* Save the current position as the start of the input bytecodes */ - mi->start_of_input_bytecodes = ci->input_position; - - /* The max stack may increase */ - mi->max_stack = max_stack; - mi->new_max_stack = max_stack; - - /* Adjust all code offsets */ - method_inject_and_write_code(mi); - - /* Fix up code length (save new_code_len for later attribute processing) */ - mi->new_code_len = (int)(ci->output_position - start_of_output_bytecodes); - random_writeU4(ci, output_code_len_position, mi->new_code_len); - - /* Fixup max stack */ - CRW_ASSERT(ci, mi->new_max_stack <= 0xFFFF); - random_writeU2(ci, output_max_stack_position, mi->new_max_stack); - - /* Copy exception table */ - method_write_exception_table(mi); - - /* Copy code attributes (needs mi->new_code_len) */ - attr_count = copyU2(ci); - for (i = 0; i < attr_count; ++i) { - method_write_code_attribute(mi); - } - - /* Fix up attribute length */ - new_attr_len = (int)(ci->output_position - (output_attr_len_position + 4)); - random_writeU4(ci, output_attr_len_position, new_attr_len); - - /* Free method data */ - method_term(mi); - mi = NULL; - -} - -static void -method_write(CrwClassImage *ci, unsigned mnum) -{ - unsigned i; - unsigned access_flags; - CrwCpoolIndex name_index; - CrwCpoolIndex descr_index; - unsigned attr_count; - - access_flags = copyU2(ci); - name_index = copyU2(ci); - ci->method_name[mnum] = cpool_entry(ci, name_index).ptr; - descr_index = copyU2(ci); - ci->method_descr[mnum] = cpool_entry(ci, descr_index).ptr; - attr_count = copyU2(ci); - - for (i = 0; i < attr_count; ++i) { - CrwCpoolIndex name_index; - - name_index = copyU2(ci); - if ( attribute_match(ci, name_index, "Code") ) { - method_write_bytecodes(ci, mnum, access_flags); - } else { - unsigned len; - len = copyU4(ci); - copy(ci, len); - } - } -} - -static void -method_write_all(CrwClassImage *ci) -{ - unsigned i; - unsigned count; - - count = copyU2(ci); - ci->method_count = count; - if ( count > 0 ) { - ci->method_name = (const char **)allocate_clean(ci, count*(int)sizeof(const char*)); - ci->method_descr = (const char **)allocate_clean(ci, count*(int)sizeof(const char*)); - } - - for (i = 0; i < count; ++i) { - method_write(ci, i); - } - - if ( ci->mnum_callback != NULL ) { - (*(ci->mnum_callback))(ci->number, ci->method_name, ci->method_descr, - count); - } -} - -/* ------------------------------------------------------------------- */ -/* Cleanup function. */ - -static void -cleanup(CrwClassImage *ci) -{ - CRW_ASSERT_CI(ci); - if ( ci->name != NULL ) { - deallocate(ci, (void*)ci->name); - ci->name = NULL; - } - if ( ci->method_name != NULL ) { - deallocate(ci, (void*)ci->method_name); - ci->method_name = NULL; - } - if ( ci->method_descr != NULL ) { - deallocate(ci, (void*)ci->method_descr); - ci->method_descr = NULL; - } - if ( ci->cpool != NULL ) { - CrwCpoolIndex i; - for(i=0; i<ci->cpool_count_plus_one; i++) { - if ( ci->cpool[i].ptr != NULL ) { - deallocate(ci, (void*)(ci->cpool[i].ptr)); - ci->cpool[i].ptr = NULL; - } - } - deallocate(ci, (void*)ci->cpool); - ci->cpool = NULL; - } -} - -static jboolean -skip_class(unsigned access_flags) -{ - if ( access_flags & JVM_ACC_INTERFACE ) { - return JNI_TRUE; - } - return JNI_FALSE; -} - -static long -inject_class(struct CrwClassImage *ci, - int system_class, - char* tclass_name, - char* tclass_sig, - char* call_name, - char* call_sig, - char* return_name, - char* return_sig, - char* obj_init_name, - char* obj_init_sig, - char* newarray_name, - char* newarray_sig, - unsigned char *buf, - long buf_len) -{ - CrwConstantPoolEntry cs; - CrwCpoolIndex this_class; - CrwCpoolIndex super_class; - unsigned magic; - unsigned classfileMajorVersion; - unsigned classfileMinorVersion; - unsigned interface_count; - - CRW_ASSERT_CI(ci); - CRW_ASSERT(ci, buf!=NULL); - CRW_ASSERT(ci, buf_len!=0); - - CRW_ASSERT(ci, strchr(tclass_name,'.')==NULL); /* internal qualified name */ - - ci->injection_count = 0; - ci->system_class = system_class; - ci->tclass_name = tclass_name; - ci->tclass_sig = tclass_sig; - ci->call_name = call_name; - ci->call_sig = call_sig; - ci->return_name = return_name; - ci->return_sig = return_sig; - ci->obj_init_name = obj_init_name; - ci->obj_init_sig = obj_init_sig; - ci->newarray_name = newarray_name; - ci->newarray_sig = newarray_sig; - ci->output = buf; - ci->output_len = buf_len; - - magic = copyU4(ci); - CRW_ASSERT(ci, magic==0xCAFEBABE); - if ( magic != 0xCAFEBABE ) { - return (long)0; - } - - /* minor version number not used */ - classfileMinorVersion = copyU2(ci); - /* major version number not used */ - classfileMajorVersion = copyU2(ci); - CRW_ASSERT(ci, (classfileMajorVersion <= JVM_CLASSFILE_MAJOR_VERSION) || - ((classfileMajorVersion == JVM_CLASSFILE_MAJOR_VERSION) && - (classfileMinorVersion <= JVM_CLASSFILE_MINOR_VERSION))); - - cpool_setup(ci); - - ci->access_flags = copyU2(ci); - if ( skip_class(ci->access_flags) ) { - return (long)0; - } - - this_class = copyU2(ci); - - cs = cpool_entry(ci, (CrwCpoolIndex)(cpool_entry(ci, this_class).index1)); - if ( ci->name == NULL ) { - ci->name = duplicate(ci, cs.ptr, cs.len); - CRW_ASSERT(ci, strchr(ci->name,'.')==NULL); /* internal qualified name */ - } - CRW_ASSERT(ci, (int)strlen(ci->name)==cs.len && strncmp(ci->name, cs.ptr, cs.len)==0); - - super_class = copyU2(ci); - if ( super_class == 0 ) { - ci->is_object_class = JNI_TRUE; - CRW_ASSERT(ci, strcmp(ci->name,"java/lang/Object")==0); - } - - interface_count = copyU2(ci); - copy(ci, interface_count * 2); - - copy_all_fields(ci); - - method_write_all(ci); - - if ( ci->injection_count == 0 ) { - return (long)0; - } - - copy_attributes(ci); - - return (long)ci->output_position; -} - -/* ------------------------------------------------------------------- */ -/* Exported interfaces */ - -JNIEXPORT void JNICALL -java_crw_demo(unsigned class_number, - const char *name, - const unsigned char *file_image, - long file_len, - int system_class, - char* tclass_name, /* Name of class that has tracker methods. */ - char* tclass_sig, /* Signature of tclass */ - char* call_name, /* Method name to call at offset 0 */ - char* call_sig, /* Signature of this method */ - char* return_name, /* Method name to call before any return */ - char* return_sig, /* Signature of this method */ - char* obj_init_name, /* Method name to call in Object <init> */ - char* obj_init_sig, /* Signature of this method */ - char* newarray_name, /* Method name to call after newarray opcodes */ - char* newarray_sig, /* Signature of this method */ - unsigned char **pnew_file_image, - long *pnew_file_len, - FatalErrorHandler fatal_error_handler, - MethodNumberRegister mnum_callback) -{ - CrwClassImage ci; - long max_length; - long new_length; - void *new_image; - int len; - - /* Initial setup of the CrwClassImage structure */ - (void)memset(&ci, 0, (int)sizeof(CrwClassImage)); - ci.fatal_error_handler = fatal_error_handler; - ci.mnum_callback = mnum_callback; - - /* Do some interface error checks */ - if ( pnew_file_image==NULL ) { - CRW_FATAL(&ci, "pnew_file_image==NULL"); - } - if ( pnew_file_len==NULL ) { - CRW_FATAL(&ci, "pnew_file_len==NULL"); - } - - /* No file length means do nothing */ - *pnew_file_image = NULL; - *pnew_file_len = 0; - if ( file_len==0 ) { - return; - } - - /* Do some more interface error checks */ - if ( file_image == NULL ) { - CRW_FATAL(&ci, "file_image == NULL"); - } - if ( file_len < 0 ) { - CRW_FATAL(&ci, "file_len < 0"); - } - if ( system_class != 0 && system_class != 1 ) { - CRW_FATAL(&ci, "system_class is not 0 or 1"); - } - if ( tclass_name == NULL ) { - CRW_FATAL(&ci, "tclass_name == NULL"); - } - if ( tclass_sig == NULL || tclass_sig[0]!='L' ) { - CRW_FATAL(&ci, "tclass_sig is not a valid class signature"); - } - len = (int)strlen(tclass_sig); - if ( tclass_sig[len-1]!=';' ) { - CRW_FATAL(&ci, "tclass_sig is not a valid class signature"); - } - if ( call_name != NULL ) { - if ( call_sig == NULL || strcmp(call_sig, "(II)V") != 0 ) { - CRW_FATAL(&ci, "call_sig is not (II)V"); - } - } - if ( return_name != NULL ) { - if ( return_sig == NULL || strcmp(return_sig, "(II)V") != 0 ) { - CRW_FATAL(&ci, "return_sig is not (II)V"); - } - } - if ( obj_init_name != NULL ) { - if ( obj_init_sig == NULL || strcmp(obj_init_sig, "(Ljava/lang/Object;)V") != 0 ) { - CRW_FATAL(&ci, "obj_init_sig is not (Ljava/lang/Object;)V"); - } - } - if ( newarray_name != NULL ) { - if ( newarray_sig == NULL || strcmp(newarray_sig, "(Ljava/lang/Object;)V") != 0 ) { - CRW_FATAL(&ci, "newarray_sig is not (Ljava/lang/Object;)V"); - } - } - - /* Finish setup the CrwClassImage structure */ - ci.is_thread_class = JNI_FALSE; - if ( name != NULL ) { - CRW_ASSERT(&ci, strchr(name,'.')==NULL); /* internal qualified name */ - - ci.name = duplicate(&ci, name, (int)strlen(name)); - if ( strcmp(name, "java/lang/Thread")==0 ) { - ci.is_thread_class = JNI_TRUE; - } - } - ci.number = class_number; - ci.input = file_image; - ci.input_len = file_len; - - /* Do the injection */ - max_length = file_len*2 + 512; /* Twice as big + 512 */ - new_image = allocate(&ci, (int)max_length); - new_length = inject_class(&ci, - system_class, - tclass_name, - tclass_sig, - call_name, - call_sig, - return_name, - return_sig, - obj_init_name, - obj_init_sig, - newarray_name, - newarray_sig, - new_image, - max_length); - - /* Dispose or shrink the space to be returned. */ - if ( new_length == 0 ) { - deallocate(&ci, (void*)new_image); - new_image = NULL; - } else { - new_image = (void*)reallocate(&ci, (void*)new_image, (int)new_length); - } - - /* Return the new class image */ - *pnew_file_image = (unsigned char *)new_image; - *pnew_file_len = (long)new_length; - - /* Cleanup before we leave. */ - cleanup(&ci); -} - -/* Return the classname for this class which is inside the classfile image. */ -JNIEXPORT char * JNICALL -java_crw_demo_classname(const unsigned char *file_image, long file_len, - FatalErrorHandler fatal_error_handler) -{ - CrwClassImage ci; - CrwConstantPoolEntry cs; - CrwCpoolIndex this_class; - unsigned magic; - char * name; - - name = NULL; - - if ( file_len==0 || file_image==NULL ) { - return name; - } - - /* The only fields we need filled in are the image pointer and the error - * handler. - * By not adding an output buffer pointer, no output is created. - */ - (void)memset(&ci, 0, (int)sizeof(CrwClassImage)); - ci.input = file_image; - ci.input_len = file_len; - ci.fatal_error_handler = fatal_error_handler; - - /* Read out the bytes from the classfile image */ - - magic = readU4(&ci); /* magic number */ - CRW_ASSERT(&ci, magic==0xCAFEBABE); - if ( magic != 0xCAFEBABE ) { - return name; - } - (void)readU2(&ci); /* minor version number */ - (void)readU2(&ci); /* major version number */ - - /* Read in constant pool. Since no output setup, writes are NOP's */ - cpool_setup(&ci); - - (void)readU2(&ci); /* access flags */ - this_class = readU2(&ci); /* 'this' class */ - - /* Get 'this' constant pool entry */ - cs = cpool_entry(&ci, (CrwCpoolIndex)(cpool_entry(&ci, this_class).index1)); - - /* Duplicate the name */ - name = (char *)duplicate(&ci, cs.ptr, cs.len); - - /* Cleanup before we leave. */ - cleanup(&ci); - - /* Return malloc space */ - return name; -}
--- a/jdk/src/demo/share/jvmti/java_crw_demo/java_crw_demo.h Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,196 +0,0 @@ -/* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - -#ifndef JAVA_CRW_DEMO_H -#define JAVA_CRW_DEMO_H - -#include <jni.h> - -#ifdef __cplusplus -extern "C" { -#endif - -/* This callback is used to notify the caller of a fatal error. */ - -typedef void (*FatalErrorHandler)(const char*message, const char*file, int line); - -/* This callback is used to return the method information for a class. - * Since the information was already read here, it was useful to - * return it here, with no JVMTI phase restrictions. - * If the class file does represent a "class" and it has methods, then - * this callback will be called with the class number and pointers to - * the array of names, array of signatures, and the count of methods. - */ - -typedef void (*MethodNumberRegister)(unsigned, const char**, const char**, int); - -/* Class file reader/writer interface. Basic input is a classfile image - * and details about what to inject. The output is a new classfile image - * that was allocated with malloc(), and should be freed by the caller. - */ - -/* Names of external symbols to look for. These are the names that we - * try and lookup in the shared library. On Windows 2000, the naming - * convention is to prefix a "_" and suffix a "@N" where N is 4 times - * the number or arguments supplied.It has 19 args, so 76 = 19*4. - * On Windows 2003, Linux, and Solaris, the first name will be - * found, on Windows 2000 a second try should find the second name. - * - * WARNING: If You change the JavaCrwDemo typedef, you MUST change - * multiple things in this file, including this name. - */ - -#define JAVA_CRW_DEMO_SYMBOLS { "java_crw_demo", "_java_crw_demo@76" } - -/* Typedef needed for type casting in dynamic access situations. */ - -typedef void (JNICALL *JavaCrwDemo)( - unsigned class_number, - const char *name, - const unsigned char *file_image, - long file_len, - int system_class, - char* tclass_name, - char* tclass_sig, - char* call_name, - char* call_sig, - char* return_name, - char* return_sig, - char* obj_init_name, - char* obj_init_sig, - char* newarray_name, - char* newarray_sig, - unsigned char **pnew_file_image, - long *pnew_file_len, - FatalErrorHandler fatal_error_handler, - MethodNumberRegister mnum_callback -); - -/* Function export (should match typedef above) */ - -JNIEXPORT void JNICALL java_crw_demo( - - unsigned class_number, /* Caller assigned class number for class */ - - const char *name, /* Internal class name, e.g. java/lang/Object */ - /* (Do not use "java.lang.Object" format) */ - - const unsigned char - *file_image, /* Pointer to classfile image for this class */ - - long file_len, /* Length of the classfile in bytes */ - - int system_class, /* Set to 1 if this is a system class */ - /* (prevents injections into empty */ - /* <clinit>, finalize, and <init> methods) */ - - char* tclass_name, /* Class that has methods we will call at */ - /* the injection sites (tclass) */ - - char* tclass_sig, /* Signature of tclass */ - /* (Must be "L" + tclass_name + ";") */ - - char* call_name, /* Method name in tclass to call at offset 0 */ - /* for every method */ - - char* call_sig, /* Signature of this call_name method */ - /* (Must be "(II)V") */ - - char* return_name, /* Method name in tclass to call at all */ - /* return opcodes in every method */ - - char* return_sig, /* Signature of this return_name method */ - /* (Must be "(II)V") */ - - char* obj_init_name, /* Method name in tclass to call first thing */ - /* when injecting java.lang.Object.<init> */ - - char* obj_init_sig, /* Signature of this obj_init_name method */ - /* (Must be "(Ljava/lang/Object;)V") */ - - char* newarray_name, /* Method name in tclass to call after every */ - /* newarray opcode in every method */ - - char* newarray_sig, /* Signature of this method */ - /* (Must be "(Ljava/lang/Object;II)V") */ - - unsigned char - **pnew_file_image, /* Returns a pointer to new classfile image */ - - long *pnew_file_len, /* Returns the length of the new image */ - - FatalErrorHandler - fatal_error_handler, /* Pointer to function to call on any */ - /* fatal error. NULL sends error to stderr */ - - MethodNumberRegister - mnum_callback /* Pointer to function that gets called */ - /* with all details on methods in this */ - /* class. NULL means skip this call. */ - - ); - - -/* External to read the class name out of a class file . - * - * WARNING: If You change the typedef, you MUST change - * multiple things in this file, including this name. - */ - -#define JAVA_CRW_DEMO_CLASSNAME_SYMBOLS \ - { "java_crw_demo_classname", "_java_crw_demo_classname@12" } - -/* Typedef needed for type casting in dynamic access situations. */ - -typedef char * (JNICALL *JavaCrwDemoClassname)( - const unsigned char *file_image, - long file_len, - FatalErrorHandler fatal_error_handler); - -JNIEXPORT char * JNICALL java_crw_demo_classname( - const unsigned char *file_image, - long file_len, - FatalErrorHandler fatal_error_handler); - -#ifdef __cplusplus -} /* extern "C" */ -#endif /* __cplusplus */ - -#endif
--- a/jdk/src/demo/share/jvmti/java_crw_demo/sample.makefile.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,144 +0,0 @@ -# -# Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -######################################################################## -# -# Sample GNU Makefile for building -# -# Example uses: -# gnumake JDK=<java_home> OSNAME=solaris [OPT=true] [LIBARCH=sparc] -# gnumake JDK=<java_home> OSNAME=solaris [OPT=true] [LIBARCH=sparcv9] -# gnumake JDK=<java_home> OSNAME=linux [OPT=true] -# gnumake JDK=<java_home> OSNAME=win32 [OPT=true] -# -######################################################################## - -# Source lists -LIBNAME=java_crw_demo -SOURCES=java_crw_demo.c - -# Solaris Studio C Compiler Version 12.4 -ifeq ($(OSNAME), solaris) - # Sun Solaris Compiler options needed - COMMON_FLAGS=-mt -KPIC - # Options that help find errors - COMMON_FLAGS+= -Xa -v -xc99=%none - # Check LIBARCH for any special compiler options - LIBARCH=$(shell uname -p) - ifeq ($(LIBARCH), sparc) - COMMON_FLAGS+=-xarch=v8 -xregs=no%appl - endif - ifeq ($(LIBARCH), sparcv9) - COMMON_FLAGS+=-xarch=v9 -xregs=no%appl - endif - ifeq ($(OPT), true) - CFLAGS=-xO2 $(COMMON_FLAGS) - else - CFLAGS=-g $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.o) - # Library name and options needed to build it - LIBRARY=lib$(LIBNAME).so - LDFLAGS=-z defs -ztext - # Libraries we are dependent on - LIBRARIES=-lc - # Building a shared library - LINK_SHARED=$(LINK.c) -G -o $@ -endif - -# Linux GNU C Compiler -ifeq ($(OSNAME), linux) - # GNU Compiler options needed to build it - COMMON_FLAGS=-fno-strict-aliasing -fPIC -fno-omit-frame-pointer - # Options that help find errors - COMMON_FLAGS+= -W -Wall -Wno-unused -Wno-parentheses - ifeq ($(OPT), true) - CFLAGS=-O2 $(COMMON_FLAGS) - else - CFLAGS=-g $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.o) - # Library name and options needed to build it - LIBRARY=lib$(LIBNAME).so - LDFLAGS=-Wl,-soname=$(LIBRARY) -static-libgcc - # Libraries we are dependent on - LIBRARIES=-lc - # Building a shared library - LINK_SHARED=$(LINK.c) -shared -o $@ -endif - -# Windows Microsoft C/C++ Optimizing Compiler Version 12 -ifeq ($(OSNAME), win32) - CC=cl - # Compiler options needed to build it - COMMON_FLAGS=-Gy -DWIN32 - # Options that help find errors - COMMON_FLAGS+=-W0 -WX - ifeq ($(OPT), true) - CFLAGS= -Ox -Op -Zi $(COMMON_FLAGS) - else - CFLAGS= -Od -Zi $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.obj) - # Library name and options needed to build it - LIBRARY=$(LIBNAME).dll - LDFLAGS= - # Libraries we are dependent on - LIBRARIES= - # Building a shared library - LINK_SHARED=link -dll -out:$@ -endif - -# Common -I options -CFLAGS += -I. -CFLAGS += -I$(JDK)/include -I$(JDK)/include/$(OSNAME) - -# Default rule (build both native library and jar file) -all: $(LIBRARY) - -# Build native library -$(LIBRARY): $(OBJECTS) - $(LINK_SHARED) $(OBJECTS) $(LIBRARIES) - -# Cleanup the built bits -clean: - rm -f -r classes - rm -f $(LIBRARY) $(OBJECTS) - -# Compilation rule only needed on Windows -ifeq ($(OSNAME), win32) -%.obj: %.c - $(COMPILE.c) $< -endif -
--- a/jdk/src/demo/share/jvmti/minst/Minst.java Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - - -/* Java class to hold static methods which will be called in byte code - * injections of all class files. - */ - -public class Minst { - - /* Master switch that activates methods. */ - - private static int engaged = 0; - - /* At the very beginning of every method, a call to method_entry() - * is injected. - */ - - public static void method_entry(int cnum, int mnum) { - Class<Minst> x = Minst.class; - synchronized ( x ) { - if ( engaged > 0 ) { - engaged = 0; - String className = "Unknown"; - String methodName = "Unknown"; - Exception exp = new Exception(); - StackTraceElement[] stack = exp.getStackTrace(); - if (stack.length > 1) { - StackTraceElement location = stack[1]; - className = location.getClassName(); - methodName = location.getMethodName(); - } - System.out.println("Reached method entry: " + - className + "." + methodName + "()"); - engaged++; - } - } - } - -}
--- a/jdk/src/demo/share/jvmti/minst/README.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,49 +0,0 @@ -# -# Copyright (c) 2006, 2007, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -minst - -This agent library can be used to inject code at method calls. -It uses the same java_crw_demo library used by HPROF to do BCI on all -or selected classfiles loaded into the Virtual Machine. -The class Minst.java can be customized to do whatever you wish, -within reason of course, and does not call native methods directly. - -You can use this agent library as follows: - - java -agentlib:minst ... - -To get help on the available options try: - - java -agentlib:minst=help - -See ${JAVA_HOME}/demo/jvmti/index.html for help running and building agents. -
--- a/jdk/src/demo/share/jvmti/minst/minst.c Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,481 +0,0 @@ -/* - * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - -#include "stdlib.h" - -#include "minst.h" -#include "java_crw_demo.h" - - -/* ------------------------------------------------------------------- */ -/* Some constant maximum sizes */ - -#define MAX_TOKEN_LENGTH 80 -#define MAX_METHOD_NAME_LENGTH 256 - -/* Some constant names that tie to Java class/method names. - * We assume the Java class whose static methods we will be calling - * looks like: - * - * public class Minst { - * private static int engaged; - * private static native void _method_entry(Object thr, int cnum, int mnum); - * public static void method_entry(int cnum, int mnum) - * { - * ... - * } - * } - * - */ - -#define MINST_class Minst /* Name of class we are using */ -#define MINST_entry method_entry /* Name of java entry method */ -#define MINST_engaged engaged /* Name of java static field */ - -/* C macros to create strings from tokens */ -#define _STRING(s) #s -#define STRING(s) _STRING(s) - -/* ------------------------------------------------------------------- */ - -/* Global agent data structure */ - -typedef struct { - /* JVMTI Environment */ - jvmtiEnv *jvmti; - jboolean vm_is_dead; - jboolean vm_is_started; - /* Data access Lock */ - jrawMonitorID lock; - /* Options */ - char *include; - char *exclude; - /* Class Count/ID */ - jint ccount; -} GlobalAgentData; - -static GlobalAgentData *gdata; - -/* Enter a critical section by doing a JVMTI Raw Monitor Enter */ -static void -enter_critical_section(jvmtiEnv *jvmti) -{ - jvmtiError error; - - error = (*jvmti)->RawMonitorEnter(jvmti, gdata->lock); - check_jvmti_error(jvmti, error, "Cannot enter with raw monitor"); -} - -/* Exit a critical section by doing a JVMTI Raw Monitor Exit */ -static void -exit_critical_section(jvmtiEnv *jvmti) -{ - jvmtiError error; - - error = (*jvmti)->RawMonitorExit(jvmti, gdata->lock); - check_jvmti_error(jvmti, error, "Cannot exit with raw monitor"); -} - -/* Callback for JVMTI_EVENT_VM_START */ -static void JNICALL -cbVMStart(jvmtiEnv *jvmti, JNIEnv *env) -{ - enter_critical_section(jvmti); { - /* Indicate VM has started */ - gdata->vm_is_started = JNI_TRUE; - } exit_critical_section(jvmti); -} - -/* Callback for JVMTI_EVENT_VM_INIT */ -static void JNICALL -cbVMInit(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) -{ - enter_critical_section(jvmti); { - jclass klass; - jfieldID field; - - /* Register Natives for class whose methods we use */ - klass = (*env)->FindClass(env, STRING(MINST_class)); - if ( klass == NULL ) { - fatal_error("ERROR: JNI: Cannot find %s with FindClass\n", - STRING(MINST_class)); - } - - /* Engage calls. */ - field = (*env)->GetStaticFieldID(env, klass, STRING(MINST_engaged), "I"); - if ( field == NULL ) { - fatal_error("ERROR: JNI: Cannot get field from %s\n", - STRING(MINST_class)); - } - (*env)->SetStaticIntField(env, klass, field, 1); - } exit_critical_section(jvmti); -} - -/* Callback for JVMTI_EVENT_VM_DEATH */ -static void JNICALL -cbVMDeath(jvmtiEnv *jvmti, JNIEnv *env) -{ - enter_critical_section(jvmti); { - jclass klass; - jfieldID field; - - /* The VM has died. */ - stdout_message("VMDeath\n"); - - /* Disengage calls in MINST_class. */ - klass = (*env)->FindClass(env, STRING(MINST_class)); - if ( klass == NULL ) { - fatal_error("ERROR: JNI: Cannot find %s with FindClass\n", - STRING(MINST_class)); - } - field = (*env)->GetStaticFieldID(env, klass, STRING(MINST_engaged), "I"); - if ( field == NULL ) { - fatal_error("ERROR: JNI: Cannot get field from %s\n", - STRING(MINST_class)); - } - (*env)->SetStaticIntField(env, klass, field, -1); - - /* The critical section here is important to hold back the VM death - * until all other callbacks have completed. - */ - - /* Since this critical section could be holding up other threads - * in other event callbacks, we need to indicate that the VM is - * dead so that the other callbacks can short circuit their work. - * We don't expect any further events after VmDeath but we do need - * to be careful that existing threads might be in our own agent - * callback code. - */ - gdata->vm_is_dead = JNI_TRUE; - - } exit_critical_section(jvmti); - -} - -/* Callback for JVMTI_EVENT_CLASS_FILE_LOAD_HOOK */ -static void JNICALL -cbClassFileLoadHook(jvmtiEnv *jvmti, JNIEnv* env, - jclass class_being_redefined, jobject loader, - const char* name, jobject protection_domain, - jint class_data_len, const unsigned char* class_data, - jint* new_class_data_len, unsigned char** new_class_data) -{ - enter_critical_section(jvmti); { - /* It's possible we get here right after VmDeath event, be careful */ - if ( !gdata->vm_is_dead ) { - - const char *classname; - - /* Name could be NULL */ - if ( name == NULL ) { - classname = java_crw_demo_classname(class_data, class_data_len, - NULL); - if ( classname == NULL ) { - fatal_error("ERROR: No classname inside classfile\n"); - } - } else { - classname = strdup(name); - if ( classname == NULL ) { - fatal_error("ERROR: Out of malloc memory\n"); - } - } - - *new_class_data_len = 0; - *new_class_data = NULL; - - /* The tracker class itself? */ - if ( interested((char*)classname, "", gdata->include, gdata->exclude) - && strcmp(classname, STRING(MINST_class)) != 0 ) { - jint cnum; - int system_class; - unsigned char *new_image; - long new_length; - - /* Get unique number for every class file image loaded */ - cnum = gdata->ccount++; - - /* Is it a system class? If the class load is before VmStart - * then we will consider it a system class that should - * be treated carefully. (See java_crw_demo) - */ - system_class = 0; - if ( !gdata->vm_is_started ) { - system_class = 1; - } - - new_image = NULL; - new_length = 0; - - /* Call the class file reader/write demo code */ - java_crw_demo(cnum, - classname, - class_data, - class_data_len, - system_class, - STRING(MINST_class), "L" STRING(MINST_class) ";", - STRING(MINST_entry), "(II)V", - NULL, NULL, - NULL, NULL, - NULL, NULL, - &new_image, - &new_length, - NULL, - NULL); - - /* If we got back a new class image, return it back as "the" - * new class image. This must be JVMTI Allocate space. - */ - if ( new_length > 0 ) { - unsigned char *jvmti_space; - - jvmti_space = (unsigned char *)allocate(jvmti, (jint)new_length); - (void)memcpy((void*)jvmti_space, (void*)new_image, (int)new_length); - *new_class_data_len = (jint)new_length; - *new_class_data = jvmti_space; /* VM will deallocate */ - } - - /* Always free up the space we get from java_crw_demo() */ - if ( new_image != NULL ) { - (void)free((void*)new_image); /* Free malloc() space with free() */ - } - } - (void)free((void*)classname); - } - } exit_critical_section(jvmti); -} - -/* Parse the options for this minst agent */ -static void -parse_agent_options(char *options) -{ - char token[MAX_TOKEN_LENGTH]; - char *next; - - /* Parse options and set flags in gdata */ - if ( options==NULL ) { - return; - } - - /* Get the first token from the options string. */ - next = get_token(options, ",=", token, sizeof(token)); - - /* While not at the end of the options string, process this option. */ - while ( next != NULL ) { - if ( strcmp(token,"help")==0 ) { - stdout_message("The minst JVMTI demo agent\n"); - stdout_message("\n"); - stdout_message(" java -agent:minst[=options] ...\n"); - stdout_message("\n"); - stdout_message("The options are comma separated:\n"); - stdout_message("\t help\t\t\t Print help information\n"); - stdout_message("\t include=item\t\t Only these classes/methods\n"); - stdout_message("\t exclude=item\t\t Exclude these classes/methods\n"); - stdout_message("\n"); - stdout_message("item\t Qualified class and/or method names\n"); - stdout_message("\t\t e.g. (*.<init>;Foobar.method;sun.*)\n"); - stdout_message("\n"); - exit(0); - } else if ( strcmp(token,"include")==0 ) { - int used; - int maxlen; - - maxlen = MAX_METHOD_NAME_LENGTH; - if ( gdata->include == NULL ) { - gdata->include = (char*)calloc(maxlen+1, 1); - used = 0; - } else { - used = (int)strlen(gdata->include); - gdata->include[used++] = ','; - gdata->include[used] = 0; - gdata->include = (char*) - realloc((void*)gdata->include, used+maxlen+1); - } - if ( gdata->include == NULL ) { - fatal_error("ERROR: Out of malloc memory\n"); - } - /* Add this item to the list */ - next = get_token(next, ",=", gdata->include+used, maxlen); - /* Check for token scan error */ - if ( next==NULL ) { - fatal_error("ERROR: include option error\n"); - } - } else if ( strcmp(token,"exclude")==0 ) { - int used; - int maxlen; - - maxlen = MAX_METHOD_NAME_LENGTH; - if ( gdata->exclude == NULL ) { - gdata->exclude = (char*)calloc(maxlen+1, 1); - used = 0; - } else { - used = (int)strlen(gdata->exclude); - gdata->exclude[used++] = ','; - gdata->exclude[used] = 0; - gdata->exclude = (char*) - realloc((void*)gdata->exclude, used+maxlen+1); - } - if ( gdata->exclude == NULL ) { - fatal_error("ERROR: Out of malloc memory\n"); - } - /* Add this item to the list */ - next = get_token(next, ",=", gdata->exclude+used, maxlen); - /* Check for token scan error */ - if ( next==NULL ) { - fatal_error("ERROR: exclude option error\n"); - } - } else if ( token[0]!=0 ) { - /* We got a non-empty token and we don't know what it is. */ - fatal_error("ERROR: Unknown option: %s\n", token); - } - /* Get the next token (returns NULL if there are no more) */ - next = get_token(next, ",=", token, sizeof(token)); - } -} - -/* Agent_OnLoad: This is called immediately after the shared library is - * loaded. This is the first code executed. - */ -JNIEXPORT jint JNICALL -DEF_Agent_OnLoad(JavaVM *vm, char *options, void *reserved) -{ - static GlobalAgentData data; - jvmtiEnv *jvmti; - jvmtiError error; - jint res; - jvmtiCapabilities capabilities; - jvmtiEventCallbacks callbacks; - - /* Setup initial global agent data area - * Use of static/extern data should be handled carefully here. - * We need to make sure that we are able to cleanup after ourselves - * so anything allocated in this library needs to be freed in - * the Agent_OnUnload() function. - */ - (void)memset((void*)&data, 0, sizeof(data)); - gdata = &data; - - /* First thing we need to do is get the jvmtiEnv* or JVMTI environment */ - res = (*vm)->GetEnv(vm, (void **)&jvmti, JVMTI_VERSION_1); - if (res != JNI_OK) { - /* This means that the VM was unable to obtain this version of the - * JVMTI interface, this is a fatal error. - */ - fatal_error("ERROR: Unable to access JVMTI Version 1 (0x%x)," - " is your JDK a 5.0 or newer version?" - " JNIEnv's GetEnv() returned %d\n", - JVMTI_VERSION_1, res); - } - - /* Here we save the jvmtiEnv* for Agent_OnUnload(). */ - gdata->jvmti = jvmti; - - /* Parse any options supplied on java command line */ - parse_agent_options(options); - - /* Immediately after getting the jvmtiEnv* we need to ask for the - * capabilities this agent will need. In this case we need to make - * sure that we can get all class load hooks. - */ - (void)memset(&capabilities,0, sizeof(capabilities)); - capabilities.can_generate_all_class_hook_events = 1; - error = (*jvmti)->AddCapabilities(jvmti, &capabilities); - check_jvmti_error(jvmti, error, "Unable to get necessary JVMTI capabilities."); - - /* Next we need to provide the pointers to the callback functions to - * to this jvmtiEnv* - */ - (void)memset(&callbacks,0, sizeof(callbacks)); - /* JVMTI_EVENT_VM_START */ - callbacks.VMStart = &cbVMStart; - /* JVMTI_EVENT_VM_INIT */ - callbacks.VMInit = &cbVMInit; - /* JVMTI_EVENT_VM_DEATH */ - callbacks.VMDeath = &cbVMDeath; - /* JVMTI_EVENT_CLASS_FILE_LOAD_HOOK */ - callbacks.ClassFileLoadHook = &cbClassFileLoadHook; - error = (*jvmti)->SetEventCallbacks(jvmti, &callbacks, (jint)sizeof(callbacks)); - check_jvmti_error(jvmti, error, "Cannot set jvmti callbacks"); - - /* At first the only initial events we are interested in are VM - * initialization, VM death, and Class File Loads. - * Once the VM is initialized we will request more events. - */ - error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_VM_START, (jthread)NULL); - check_jvmti_error(jvmti, error, "Cannot set event notification"); - error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_VM_INIT, (jthread)NULL); - check_jvmti_error(jvmti, error, "Cannot set event notification"); - error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_VM_DEATH, (jthread)NULL); - check_jvmti_error(jvmti, error, "Cannot set event notification"); - error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, (jthread)NULL); - check_jvmti_error(jvmti, error, "Cannot set event notification"); - - /* Here we create a raw monitor for our use in this agent to - * protect critical sections of code. - */ - error = (*jvmti)->CreateRawMonitor(jvmti, "agent data", &(gdata->lock)); - check_jvmti_error(jvmti, error, "Cannot create raw monitor"); - - /* Add demo jar file to boot classpath */ - add_demo_jar_to_bootclasspath(jvmti, "minst"); - - /* We return JNI_OK to signify success */ - return JNI_OK; -} - -/* Agent_OnUnload: This is called immediately before the shared library is - * unloaded. This is the last code executed. - */ -JNIEXPORT void JNICALL -DEF_Agent_OnUnload(JavaVM *vm) -{ - /* Make sure all malloc/calloc/strdup space is freed */ - if ( gdata->include != NULL ) { - (void)free((void*)gdata->include); - gdata->include = NULL; - } - if ( gdata->exclude != NULL ) { - (void)free((void*)gdata->exclude); - gdata->exclude = NULL; - } -}
--- a/jdk/src/demo/share/jvmti/minst/minst.h Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - -/* Primary minst #include file, should be included by most if not - * all minst source files. Gives access to the global data structure - * and all global macros. - */ - -#ifndef MINST_H -#define MINST_H - -/* Standard C functions used throughout. */ - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <stddef.h> -#include <stdarg.h> - -/* General JVM/Java functions, types and macros. */ - -#include <sys/types.h> -#include "jni.h" -#include "jvmti.h" - -/* Utility functions */ - -#include "agent_util.h" - -#endif
--- a/jdk/src/demo/share/jvmti/minst/sample.makefile.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,163 +0,0 @@ -# -# Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -######################################################################## -# -# Sample GNU Makefile for building JVMTI Demo minst -# -# Example uses: -# gnumake JDK=<java_home> OSNAME=solaris [OPT=true] [LIBARCH=sparc] -# gnumake JDK=<java_home> OSNAME=solaris [OPT=true] [LIBARCH=sparcv9] -# gnumake JDK=<java_home> OSNAME=linux [OPT=true] -# gnumake JDK=<java_home> OSNAME=win32 [OPT=true] -# -######################################################################## - -# Source lists -LIBNAME=minst -SOURCES=minst.c ../agent_util/agent_util.c -JAVA_SOURCES=Minst.java - -# Name of jar file that needs to be created -JARFILE=minst.jar - -# Solaris Studio C Compiler Version 12.4 -ifeq ($(OSNAME), solaris) - # Sun Solaris Compiler options needed - COMMON_FLAGS=-mt -KPIC - # Options that help find errors - COMMON_FLAGS+= -Xa -v -xc99=%none - # Check LIBARCH for any special compiler options - LIBARCH=$(shell uname -p) - ifeq ($(LIBARCH), sparc) - COMMON_FLAGS+=-xarch=v8 -xregs=no%appl - endif - ifeq ($(LIBARCH), sparcv9) - COMMON_FLAGS+=-xarch=v9 -xregs=no%appl - endif - ifeq ($(OPT), true) - CFLAGS=-xO2 $(COMMON_FLAGS) - else - CFLAGS=-g $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.o) - # Library name and options needed to build it - LIBRARY=lib$(LIBNAME).so - LDFLAGS=-z defs -ztext - # Libraries we are dependent on - LIBRARIES=-L $(JDK)/jre/lib/$(LIBARCH) -ljava_crw_demo -lc - # Building a shared library - LINK_SHARED=$(LINK.c) -G -o $@ -endif - -# Linux GNU C Compiler -ifeq ($(OSNAME), linux) - # GNU Compiler options needed to build it - COMMON_FLAGS=-fno-strict-aliasing -fPIC -fno-omit-frame-pointer - # Options that help find errors - COMMON_FLAGS+= -W -Wall -Wno-unused -Wno-parentheses - ifeq ($(OPT), true) - CFLAGS=-O2 $(COMMON_FLAGS) - else - CFLAGS=-g $(COMMON_FLAGS) - endif - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.o) - # Library name and options needed to build it - LIBRARY=lib$(LIBNAME).so - LDFLAGS=-Wl,-soname=$(LIBRARY) -static-libgcc - # Libraries we are dependent on - LIBRARIES=-L $(JDK)/jre/lib/$(LIBARCH) -ljava_crw_demo -lc - # Building a shared library - LINK_SHARED=$(LINK.c) -shared -o $@ -endif - -# Windows Microsoft C/C++ Optimizing Compiler Version 12 -ifeq ($(OSNAME), win32) - CC=cl - # Compiler options needed to build it - COMMON_FLAGS=-Gy -DWIN32 - # Options that help find errors - COMMON_FLAGS+=-W0 -WX - ifeq ($(OPT), true) - CFLAGS= -Ox -Op -Zi $(COMMON_FLAGS) - else - CFLAGS= -Od -Zi $(COMMON_FLAGS) - endif - # Add in java_crw_demo obj file on windows (easier) - SOURCES+=../java_crw_demo/java_crw_demo.c - # Object files needed to create library - OBJECTS=$(SOURCES:%.c=%.obj) - # Library name and options needed to build it - LIBRARY=$(LIBNAME).dll - LDFLAGS= - # Libraries we are dependent on - LIBRARIES=$(JDK)/ - # Building a shared library - LINK_SHARED=link -dll -out:$@ -endif - -# Common -I options -CFLAGS += -I. -CFLAGS += -I../agent_util -CFLAGS += -I../java_crw_demo -CFLAGS += -I$(JDK)/include -I$(JDK)/include/$(OSNAME) - -# Default rule (build both native library and jar file) -all: $(LIBRARY) $(JARFILE) - -# Build native library -$(LIBRARY): $(OBJECTS) - $(LINK_SHARED) $(OBJECTS) $(LIBRARIES) - -# Build jar file -$(JARFILE): $(JAVA_SOURCES) - rm -f -r classes - mkdir -p classes - $(JDK)/bin/javac -d classes $(JAVA_SOURCES) - (cd classes; $(JDK)/bin/jar cf ../$@ *) - -# Cleanup the built bits -clean: - rm -f -r classes - rm -f $(LIBRARY) $(JARFILE) $(OBJECTS) - -# Simple tester -test: all - LD_LIBRARY_PATH=. $(JDK)/bin/java -agentlib:$(LIBNAME) -Xbootclasspath/a:./$(JARFILE) -version - -# Compilation rule only needed on Windows -ifeq ($(OSNAME), win32) -%.obj: %.c - $(COMPILE.c) $< -endif -
--- a/jdk/src/demo/share/jvmti/mtrace/Mtrace.java Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - - -/* Java class to hold static methods which will be called in byte code - * injections of all class files. - */ - -public class Mtrace { - - /* Master switch that activates methods. */ - - private static int engaged = 0; - - /* At the very beginning of every method, a call to method_entry() - * is injected. - */ - - private static native void _method_entry(Object thr, int cnum, int mnum); - public static void method_entry(int cnum, int mnum) - { - if ( engaged != 0 ) { - _method_entry(Thread.currentThread(), cnum, mnum); - } - } - - /* Before any of the return bytecodes, a call to method_exit() - * is injected. - */ - - private static native void _method_exit(Object thr, int cnum, int mnum); - public static void method_exit(int cnum, int mnum) - { - if ( engaged != 0 ) { - _method_exit(Thread.currentThread(), cnum, mnum); - } - } - -}
--- a/jdk/src/demo/share/jvmti/mtrace/README.txt Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,50 +0,0 @@ -# -# Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# - Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# - Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# - Neither the name of Oracle nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -mtrace - -This agent library can be used to track method call and return counts. -It uses the same java_crw_demo library used by HPROF to do BCI on all or -selected classfiles loaded into the Virtual Machine. It will print out a -sorted list of the most heavily used classes (as determined by the number -of method calls into the class) and also include the call and return counts -for all methods that are called. - -You can use this agent library as follows: - - java -Xbootclasspath/a:mtrace.jar -agentlib:mtrace ... - -To get help on the available options try: - - java -agentlib:mtrace=help - -See ${JAVA_HOME}/demo/jvmti/index.html for help running and building agents. -
--- a/jdk/src/demo/share/jvmti/mtrace/mtrace.c Mon Apr 17 09:08:38 2017 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,833 +0,0 @@ -/* - * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Oracle nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This source code is provided to illustrate the usage of a given feature - * or technique and has been deliberately simplified. Additional steps - * required for a production-quality application, such as security checks, - * input validation and proper error handling, might not be present in - * this sample code. - */ - - -#include "stdlib.h" - -#include "mtrace.h" -#include "java_crw_demo.h" - - -/* ------------------------------------------------------------------- */ -/* Some constant maximum sizes */ - -#define MAX_TOKEN_LENGTH 16 -#define MAX_THREAD_NAME_LENGTH 512 -#define MAX_METHOD_NAME_LENGTH 1024 - -/* Some constant names that tie to Java class/method names. - * We assume the Java class whose static methods we will be calling - * looks like: - * - * public class Mtrace { - * private static int engaged; - * private static native void _method_entry(Object thr, int cnum, int mnum); - * public static void method_entry(int cnum, int mnum) - * { - * if ( engaged != 0 ) { - * _method_entry(Thread.currentThread(), cnum, mnum); - * } - * } - * private static native void _method_exit(Object thr, int cnum, int mnum); - * public static void method_exit(int cnum, int mnum) - * { - * if ( engaged != 0 ) { - * _method_exit(Thread.currentThread(), cnum, mnum); - * } - * } - * } - * - * The engaged field allows us to inject all classes (even system classes) - * and delay the actual calls to the native code until the VM has reached - * a safe time to call native methods (Past the JVMTI VM_START event). - * - */ - -#define MTRACE_class Mtrace /* Name of class we are using */ -#define MTRACE_entry method_entry /* Name of java entry method */ -#define MTRACE_exit method_exit /* Name of java exit method */ -#define MTRACE_native_entry _method_entry /* Name of java entry native */ -#define MTRACE_native_exit _method_exit /* Name of java exit native */ -#define MTRACE_engaged engaged /* Name of java static field */ - -/* C macros to create strings from tokens */ -#define _STRING(s) #s -#define STRING(s) _STRING(s) - -/* ------------------------------------------------------------------- */ - -/* Data structure to hold method and class information in agent */ - -typedef struct MethodInfo { - const char *name; /* Method name */ - const char *signature; /* Method signature */ - int calls; /* Method call count */ - int returns; /* Method return count */ -} MethodInfo; - -typedef struct ClassInfo { - const char *name; /* Class name */ - int mcount; /* Method count */ - MethodInfo *methods; /* Method information */ - int calls; /* Method call count for this class */ -} ClassInfo; - -/* Global agent data structure */ - -typedef struct { - /* JVMTI Environment */ - jvmtiEnv *jvmti; - jboolean vm_is_dead; - jboolean vm_is_started; - /* Data access Lock */ - jrawMonitorID lock; - /* Options */ - char *include; - char *exclude; - int max_count; - /* ClassInfo Table */ - ClassInfo *classes; - jint ccount; -} GlobalAgentData; - -static GlobalAgentData *gdata; - -/* Enter a critical section by doing a JVMTI Raw Monitor Enter */ -static void -enter_critical_section(jvmtiEnv *jvmti) -{ - jvmtiError error; - - error = (*jvmti)->RawMonitorEnter(jvmti, gdata->lock); - check_jvmti_error(jvmti, error, "Cannot enter with raw monitor"); -} - -/* Exit a critical section by doing a JVMTI Raw Monitor Exit */ -static void -exit_critical_section(jvmtiEnv *jvmti) -{ - jvmtiError error; - - error = (*jvmti)->RawMonitorExit(jvmti, gdata->lock); - check_jvmti_error(jvmti, error, "Cannot exit with raw monitor"); -} - -/* Get a name for a jthread */ -static void -get_thread_name(jvmtiEnv *jvmti, jthread thread, char *tname, int maxlen) -{ - jvmtiThreadInfo info; - jvmtiError error; - - /* Make sure the stack variables are garbage free */ - (void)memset(&info,0, sizeof(info)); - - /* Assume the name is unknown for now */ - (void)strcpy(tname, "Unknown"); - - /* Get the thread information, which includes the name */ - error = (*jvmti)->GetThreadInfo(jvmti, thread, &info); - check_jvmti_error(jvmti, error, "Cannot get thread info"); - - /* The thread might not have a name, be careful here. */ - if ( info.name != NULL ) { - int len; - - /* Copy the thread name into tname if it will fit */ - len = (int)strlen(info.name); - if ( len < maxlen ) { - (void)strcpy(tname, info.name); - } - - /* Every string allocated by JVMTI needs to be freed */ - deallocate(jvmti, (void*)info.name); - } -} - -/* Qsort class compare routine */ -static int -class_compar(const void *e1, const void *e2) -{ - ClassInfo *c1 = (ClassInfo*)e1; - ClassInfo *c2 = (ClassInfo*)e2; - if ( c1->calls > c2->calls ) return 1; - if ( c1->calls < c2->calls ) return -1; - return 0; -} - -/* Qsort method compare routine */ -static int -method_compar(const void *e1, const void *e2) -{ - MethodInfo *m1 = (MethodInfo*)e1; - MethodInfo *m2 = (MethodInfo*)e2; - if ( m1->calls > m2->calls ) return 1; - if ( m1->calls < m2->calls ) return -1; - return 0; -} - -/* Callback from java_crw_demo() that gives us mnum mappings */ -static void -mnum_callbacks(unsigned cnum, const char **names, const char**sigs, int mcount) -{ - ClassInfo *cp; - int mnum; - - if ( cnum >= (unsigned)gdata->ccount ) { - fatal_error("ERROR: Class number out of range\n"); - } - if ( mcount == 0 ) { - return; - } - - cp = gdata->classes + (int)cnum; - cp->calls = 0; - cp->mcount = mcount; - cp->methods = (MethodInfo*)calloc(mcount, sizeof(MethodInfo)); - if ( cp->methods == NULL ) { - fatal_error("ERROR: Out of malloc memory\n"); - } - - for ( mnum = 0 ; mnum < mcount ; mnum++ ) { - MethodInfo *mp; - - mp = cp->methods + mnum; - mp->name = (const char *)strdup(names[mnum]); - if ( mp->name == NULL ) { - fatal_error("ERROR: Out of malloc memory\n"); - } - mp->signature = (const char *)strdup(sigs[mnum]); - if ( mp->signature == NULL ) { - fatal_error("ERROR: Out of malloc memory\n"); - } - } -} - -/* Java Native Method for entry */ -static void -MTRACE_native_entry(JNIEnv *env, jclass klass, jobject thread, jint cnum, jint mnum) -{ - enter_critical_section(gdata->jvmti); { - /* It's possible we get here right after VmDeath event, be careful */ - if ( !gdata->vm_is_dead ) { - ClassInfo *cp; - MethodInfo *mp; - - if ( cnum >= gdata->ccount ) { - fatal_error("ERROR: Class number out of range\n"); - } - cp = gdata->classes + cnum; - if ( mnum >= cp->mcount ) { - fatal_error("ERROR: Method number out of range\n"); - } - mp = cp->methods + mnum; - if ( interested((char*)cp->name, (char*)mp->name, - gdata->include, gdata->exclude) ) { - mp->calls++; - cp->calls++; - } - } - } exit_critical_section(gdata->jvmti); -} - -/* Java Native Method for exit */ -static void -MTRACE_native_exit(JNIEnv *env, jclass klass, jobject thread, jint cnum, jint mnum) -{ - enter_critical_section(gdata->jvmti); { - /* It's possible we get here right after VmDeath event, be careful */ - if ( !gdata->vm_is_dead ) { - ClassInfo *cp; - MethodInfo *mp; - - if ( cnum >= gdata->ccount ) { - fatal_error("ERROR: Class number out of range\n"); - } - cp = gdata->classes + cnum; - if ( mnum >= cp->mcount ) { - fatal_error("ERROR: Method number out of range\n"); - } - mp = cp->methods + mnum; - if ( interested((char*)cp->name, (char*)mp->name, - gdata->include, gdata->exclude) ) { - mp->returns++; - } - } - } exit_critical_section(gdata->jvmti); -} - -/* Callback for JVMTI_EVENT_VM_START */ -static void JNICALL -cbVMStart(jvmtiEnv *jvmti, JNIEnv *env) -{ - enter_critical_section(jvmti); { - jclass klass; - jfieldID field; - int rc; - - /* Java Native Methods for class */ - static JNINativeMethod registry[2] = { - {STRING(MTRACE_native_entry), "(Ljava/lang/Object;II)V", - (void*)&MTRACE_native_entry}, - {STRING(MTRACE_native_exit), "(Ljava/lang/Object;II)V", - (void*)&MTRACE_native_exit} - }; - - /* The VM has started. */ - stdout_message("VMStart\n"); - - /* Register Natives for class whose methods we use */ - klass = (*env)->FindClass(env, STRING(MTRACE_class)); - if ( klass == NULL ) { - fatal_error("ERROR: JNI: Cannot find %s with FindClass\n", - STRING(MTRACE_class)); - } - rc = (*env)->RegisterNatives(env, klass, registry, 2); - if ( rc != 0 ) { - fatal_error("ERROR: JNI: Cannot register native methods for %s\n", - STRING(MTRACE_class)); - } - - /* Engage calls. */ - field = (*env)->GetStaticFieldID(env, klass, STRING(MTRACE_engaged), "I"); - if ( field == NULL ) { - fatal_error("ERROR: JNI: Cannot get field from %s\n", - STRING(MTRACE_class)); - } - (*env)->SetStaticIntField(env, klass, field, 1); - - /* Indicate VM has started */ - gdata->vm_is_started = JNI_TRUE; - - } exit_critical_section(jvmti); -} - -/* Callback for JVMTI_EVENT_VM_INIT */ -static void JNICALL -cbVMInit(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) -{ - enter_critical_section(jvmti); { - char tname[MAX_THREAD_NAME_LENGTH]; - static jvmtiEvent events[] = - { JVMTI_EVENT_THREAD_START, JVMTI_EVENT_THREAD_END }; - int i; - - /* The VM has started. */ - get_thread_name(jvmti, thread, tname, sizeof(tname)); - stdout_message("VMInit %s\n", tname); - - /* The VM is now initialized, at this time we make our requests - * for additional events. - */ - - for( i=0; i < (int)(sizeof(events)/sizeof(jvmtiEvent)); i++) { - jvmtiError error; - - /* Setup event notification modes */ - error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, - events[i], (jthread)NULL); - check_jvmti_error(jvmti, error, "Cannot set event notification"); - } - - } exit_critical_section(jvmti); -} - -/* Callback for JVMTI_EVENT_VM_DEATH */ -static void JNICALL -cbVMDeath(jvmtiEnv *jvmti, JNIEnv *env) -{ - enter_critical_section(jvmti); { - jclass klass; - jfieldID field; - - /* The VM has died. */ - stdout_message("VMDeath\n"); - - /* Disengage calls in MTRACE_class. */ - klass = (*env)->FindClass(env, STRING(MTRACE_class)); - if ( klass == NULL ) { - fatal_error("ERROR: JNI: Cannot find %s with FindClass\n", - STRING(MTRACE_class)); - } - field = (*env)->GetStaticFieldID(env, klass, STRING(MTRACE_engaged), "I"); - if ( field == NULL ) { - fatal_error("ERROR: JNI: Cannot get field from %s\n", - STRING(MTRACE_class)); - } - (*env)->SetStaticIntField(env, klass, field, 0); - - /* The critical section here is important to hold back the VM death - * until all other callbacks have completed. - */ - - /* Since this critical section could be holding up other threads - * in other event callbacks, we need to indicate that the VM is - * dead so that the other callbacks can short circuit their work. - * We don't expect any further events after VmDeath but we do need - * to be careful that existing threads might be in our own agent - * callback code. - */ - gdata->vm_is_dead = JNI_TRUE; - - /* Dump out stats */ - stdout_message("Begin Class Stats\n"); - if ( gdata->ccount > 0 ) { - int cnum; - - /* Sort table (in place) by number of method calls into class. */ - /* Note: Do not use this table after this qsort! */ - qsort(gdata->classes, gdata->ccount, sizeof(ClassInfo), - &class_compar); - - /* Dump out gdata->max_count most called classes */ - for ( cnum=gdata->ccount-1 ; - cnum >= 0 && cnum >= gdata->ccount - gdata->max_count; - cnum-- ) { - ClassInfo *cp; - int mnum; - - cp = gdata->classes + cnum; - stdout_message("Class %s %d calls\n", cp->name, cp->calls); - if ( cp->calls==0 ) continue; - - /* Sort method table (in place) by number of method calls. */ - /* Note: Do not use this table after this qsort! */ - qsort(cp->methods, cp->mcount, sizeof(MethodInfo), - &method_compar); - for ( mnum=cp->mcount-1 ; mnum >= 0 ; mnum-- ) { - MethodInfo *mp; - - mp = cp->methods + mnum; - if ( mp->calls==0 ) continue; - stdout_message("\tMethod %s %s %d calls %d returns\n", - mp->name, mp->signature, mp->calls, mp->returns); - } - } - } - stdout_message("End Class Stats\n"); - (void)fflush(stdout); - - } exit_critical_section(jvmti); - -} - -/* Callback for JVMTI_EVENT_THREAD_START */ -static void JNICALL -cbThreadStart(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) -{ - enter_critical_section(jvmti); { - /* It's possible we get here right after VmDeath event, be careful */ - if ( !gdata->vm_is_dead ) { - char tname[MAX_THREAD_NAME_LENGTH]; - - get_thread_name(jvmti, thread, tname, sizeof(tname)); - stdout_message("ThreadStart %s\n", tname); - } - } exit_critical_section(jvmti); -} - -/* Callback for JVMTI_EVENT_THREAD_END */ -static void JNICALL -cbThreadEnd(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) -{ - enter_critical_section(jvmti); { - /* It's possible we get here right after VmDeath event, be careful */ - if ( !gdata->vm_is_dead ) { - char tname[MAX_THREAD_NAME_LENGTH]; - - get_thread_name(jvmti, thread, tname, sizeof(tname)); - stdout_message("ThreadEnd %s\n", tname); - } - } exit_critical_section(jvmti); -} - -/* Callback for JVMTI_EVENT_CLASS_FILE_LOAD_HOOK */ -static void JNICALL -cbClassFileLoadHook(jvmtiEnv *jvmti, JNIEnv* env, - jclass class_being_redefined, jobject loader, - const char* name, jobject protection_domain, - jint class_data_len, const unsigned char* class_data, - jint* new_class_data_len, unsigned char** new_class_data) -{ - enter_critical_section(jvmti); { - /* It's possible we get here right after VmDeath event, be careful */ - if ( !gdata->vm_is_dead ) { - - const char *classname; - - /* Name could be NULL */ - if ( name == NULL ) { - classname = java_crw_demo_classname(class_data, class_data_len, - NULL); - if ( classname == NULL ) { - fatal_error("ERROR: No classname inside classfile\n"); - } - } else { - classname = strdup(name); - if ( classname == NULL ) { - fatal_error("ERROR: Out of malloc memory\n"); - } - } - - *new_class_data_len = 0; - *new_class_data = NULL; - - /* The tracker class itself? */ - if ( interested((char*)classname, "", gdata->include, gdata->exclude) - && strcmp(classname, STRING(MTRACE_class)) != 0 ) { - jint cnum; - int system_class; - unsigned char *new_image; - long new_length; - ClassInfo *cp; - - /* Get unique number for every class file image loaded */ - cnum = gdata->ccount++; - - /* Save away class information */ - if ( gdata->classes == NULL ) { - gdata->classes = (ClassInfo*)malloc( - gdata->ccount*sizeof(ClassInfo)); - } else { - gdata->classes = (ClassInfo*) - realloc((void*)gdata->classes, - gdata->ccount*sizeof(ClassInfo)); - } - if ( gdata->classes == NULL ) { - fatal_error("ERROR: Out of malloc memory\n"); - } - cp = gdata->classes + cnum; - cp->name = (const char *)strdup(classname); - if ( cp->name == NULL ) { - fatal_error("ERROR: Out of malloc memory\n"); - } - cp->calls = 0; - cp->mcount = 0; - cp->methods = NULL; - - /* Is it a system class? If the class load is before VmStart - * then we will consider it a system class that should - * be treated carefully. (See java_crw_demo) - */ - system_class = 0; - if ( !gdata->vm_is_started ) { - system_class = 1; - } - - new_image = NULL; - new_length = 0; - - /* Call the class file reader/write demo code */ - java_crw_demo(cnum, - classname, - class_data, - class_data_len, - system_class, - STRING(MTRACE_class), "L" STRING(MTRACE_class) ";", - STRING(MTRACE_entry), "(II)V", - STRING(MTRACE_exit), "(II)V", - NULL, NULL, - NULL, NULL, - &new_image, - &new_length, - NULL, - &mnum_callbacks); - - /* If we got back a new class image, return it back as "the" - * new class image. This must be JVMTI Allocate space. - */ - if ( new_length > 0 ) { - unsigned char *jvmti_space; - - jvmti_space = (unsigned char *)allocate(jvmti, (jint)new_length); - (void)memcpy((void*)jvmti_space, (void*)new_image, (int)new_length); - *new_class_data_len = (jint)new_length; - *new_class_data = jvmti_space; /* VM will deallocate */ - } - - /* Always free up the space we get from java_crw_demo() */ - if ( new_image != NULL ) { - (void)free((void*)new_image); /* Free malloc() space with free() */ - } - } - (void)free((void*)classname); - } - } exit_critical_section(jvmti); -} - -/* Parse the options for this mtrace agent */ -static void -parse_agent_options(char *options) -{ - char token[MAX_TOKEN_LENGTH]; - char *next; - - gdata->max_count = 10; /* Default max=n */ - - /* Parse options and set flags in gdata */ - if ( options==NULL ) { - return; - } - - /* Get the first token from the options string. */ - next = get_token(options, ",=", token, sizeof(token)); - - /* While not at the end of the options string, process this option. */ - while ( next != NULL ) { - if ( strcmp(token,"help")==0 ) { - stdout_message("The mtrace JVMTI demo agent\n"); - stdout_message("\n"); - stdout_message(" java -agent:mtrace[=options] ...\n"); - stdout_message("\n"); - stdout_message("The options are comma separated:\n"); - stdout_message("\t help\t\t\t Print help information\n"); - stdout_message("\t max=n\t\t Only list top n classes\n"); - stdout_message("\t include=item\t\t Only these classes/methods\n"); - stdout_message("\t exclude=item\t\t Exclude these classes/methods\n"); - stdout_message("\n"); - stdout_message("item\t Qualified class and/or method names\n"); - stdout_message("\t\t e.g. (*.<init>;Foobar.method;sun.*)\n"); - stdout_message("\n"); - exit(0); - } else if ( strcmp(token,"max")==0 ) { - char number[MAX_TOKEN_LENGTH]; - - /* Get the numeric option */ - next = get_token(next, ",=", number, (int)sizeof(number)); - /* Check for token scan error */ - if ( next==NULL ) { - fatal_error("ERROR: max=n option error\n"); - } - /* Save numeric value */ - gdata->max_count = atoi(number); - } else if ( strcmp(token,"include")==0 ) { - int used; - int maxlen; - - maxlen = MAX_METHOD_NAME_LENGTH; - if ( gdata->include == NULL ) { - gdata->include = (char*)calloc(maxlen+1, 1); - used = 0; - } else { - used = (int)strlen(gdata->include); - gdata->include[used++] = ','; - gdata->include[used] = 0; - gdata->include = (char*)<