diff --git a/jdk/make/CompileDemos.gmk b/jdk/make/CompileDemos.gmk index 123711d102c..35bf0b4a691 100644 --- a/jdk/make/CompileDemos.gmk +++ b/jdk/make/CompileDemos.gmk @@ -314,19 +314,6 @@ $(eval $(call SetupJVMTIDemo,compiledMethodLoad, agent_util)) $(eval $(call SetupJVMTIDemo,gctest, agent_util)) $(eval $(call SetupJVMTIDemo,heapTracker, agent_util java_crw_demo)) $(eval $(call SetupJVMTIDemo,heapViewer, agent_util)) - -# On AIX, hprof requires 'dladdr' from src/aix/porting/porting_aix.cpp -BUILD_LIBHPROF_AIX_EXTRA_SRC := -BUILD_LIBHPROF_AIX_EXTRA_CFLAGS := -ifeq ($(OPENJDK_TARGET_OS), aix) - BUILD_LIBHPROF_AIX_EXTRA_SRC += $(JDK_TOPDIR)/src/aix/porting - BUILD_LIBHPROF_AIX_EXTRA_CFLAGS += -I$(JDK_TOPDIR)/src/aix/porting -endif - -$(eval $(call SetupJVMTIDemo,hprof, java_crw_demo, \ - $(BUILD_LIBHPROF_AIX_EXTRA_CFLAGS), C, \ - -ldl, ws2_32.lib winmm.lib, -lsocket -lnsl, -lpthread, $(BUILD_LIBHPROF_AIX_EXTRA_SRC))) - $(eval $(call SetupJVMTIDemo,minst, agent_util java_crw_demo)) $(eval $(call SetupJVMTIDemo,mtrace, agent_util java_crw_demo)) $(eval $(call SetupJVMTIDemo,waiters, agent_util, , C++)) @@ -334,34 +321,6 @@ $(eval $(call SetupJVMTIDemo,versionCheck, agent_util)) ################################################################################################## -$(JDK_OUTPUTDIR)/demo/jpda/com/sun/tools/example/README: \ - $(JDK_TOPDIR)/src/demo/share/jpda/com/sun/tools/example/README - $(call install-file) - $(CHMOD) -f ug+w $@ - -$(eval $(call SetupArchive,JPDA_JAR, \ - $(JDK_OUTPUTDIR)/demo/jpda/com/sun/tools/example/README, \ - SRCS := $(JDK_TOPDIR)/src/demo/share/jpda \ - $(JDK_TOPDIR)/src/jdk.jdi/share/classes \ - $(JDK_OUTPUTDIR)/demo/jpda/com/sun/tools/example, \ - INCLUDES := com/sun/tools/example README, \ - SUFFIXES := .java .html .jj README, \ - JAR := $(JDK_OUTPUTDIR)/demo/jpda/examples.jar, \ - MANIFEST := $(JDK_TOPDIR)/make/data/mainmanifest/manifest.mf, \ - EXTRA_MANIFEST_ATTR := Main-Class:$$(SPACE), \ - SKIP_METAINF := true)) - -$(eval $(call SetupZipArchive,JPDA_ZIP, \ - SRC := $(JDK_TOPDIR)/src/demo/share/jpda \ - $(JDK_TOPDIR)/src/jdk.jdi/share/classes, \ - INCLUDES := com/sun/tools/example, \ - SUFFIXES := .java .html .jj README, \ - ZIP := $(JDK_OUTPUTDIR)/demo/jpda/src.zip)) - -BUILD_DEMOS += $(JPDA_JAR) $(JPDA_ZIP) - -################################################################################################## - $(JDK_OUTPUTDIR)/demo/management/index.html: $(DEMO_SHARE_SRC)/management/index.html $(call install-file) $(CHMOD) -f ug+w $@ diff --git a/jdk/make/Tools.gmk b/jdk/make/Tools.gmk index 4cfa33fc9f8..b68d19c3d34 100644 --- a/jdk/make/Tools.gmk +++ b/jdk/make/Tools.gmk @@ -134,7 +134,7 @@ TOOL_CHECKDEPS = $(JAVA_SMALL) -Xbootclasspath/p:$(INTERIM_LANGTOOLS_JAR) \ TOOL_GENMODULESXML = $(JAVA_SMALL) -Xbootclasspath/p:$(INTERIM_LANGTOOLS_JAR) \ -cp "$(JDK_OUTPUTDIR)/btclasses$(PATH_SEP)$(JDK_OUTPUTDIR)" \ - build.tools.module.GenerateModulesXml + build.tools.module.GenJdepsModulesXml ########################################################################################## diff --git a/jdk/make/copy/Copy-jdk.hprof.agent.gmk b/jdk/make/copy/Copy-jdk.hprof.agent.gmk index 738af52b20d..069e915514f 100644 --- a/jdk/make/copy/Copy-jdk.hprof.agent.gmk +++ b/jdk/make/copy/Copy-jdk.hprof.agent.gmk @@ -27,7 +27,7 @@ include CopyCommon.gmk ################################################################################ -HPROF_SRC := $(JDK_TOPDIR)/src/demo/share/jvmti/hprof/jvm.hprof.txt +HPROF_SRC := $(JDK_TOPDIR)/src/jdk.hprof.agent/share/native/libhprof/jvm.hprof.txt $(LIB_DST_DIR)/jvm.hprof.txt: $(HPROF_SRC) $(call install-file) diff --git a/jdk/make/data/fontconfig/aix.fontconfig.properties b/jdk/make/data/fontconfig/aix.fontconfig.properties index 29e7c7d9510..f203f759894 100644 --- a/jdk/make/data/fontconfig/aix.fontconfig.properties +++ b/jdk/make/data/fontconfig/aix.fontconfig.properties @@ -24,9 +24,14 @@ # questions. # -# Minimal version for AIX using the standard Latin Type1 Fonts from the -# package X11.fnt.iso_T1. These fonts are installed by default into -# "/usr/lpp/X11/lib/X11/fonts/Type1" and sym-linked to "/usr/lib/X11/fonts/Type1" +# +# Portions Copyright (c) 2014 IBM Corporation +# + +# This file references the standard Latin Type1 fonts from the AIX package +# X11.fnt.iso_T1 and the Unicode TrueType fonts from X11.fnt.ucs.ttf. They +# are located by default under "/usr/lpp/X11/lib/X11/fonts/{Type1,TrueType}" +# and sym-linked to "/usr/lib/X11/fonts/". # Version @@ -34,44 +39,381 @@ version=1 # Component Font Mappings -dialog.plain.latin-1=-*-helvetica-medium-r-normal--*-%d-100-100-p-*-iso10646-1 -dialog.bold.latin-1=-*-helvetica-bold-r-normal--*-%d-100-100-p-*-iso10646-1 -dialog.italic.latin-1=-*-helvetica-medium-o-normal--*-%d-100-100-p-*-iso10646-1 -dialog.bolditalic.latin-1=-*-helvetica-bold-o-normal--*-%d-100-100-p-*-iso10646-1 +allfonts.iso10646-extB=-monotype-sansmonowtextb-medium-r-normal--*-%d-75-75-m-*-unicode-2 -dialoginput.plain.latin-1=-*-courier-medium-r-normal--*-%d-100-100-m-*-iso10646-1 -dialoginput.bold.latin-1=-*-courier-bold-r-normal--*-%d-100-100-m-*-iso10646-1 -dialoginput.italic.latin-1=-*-courier-medium-o-normal--*-%d-100-100-m-*-iso10646-1 -dialoginput.bolditalic.latin-1=-*-courier-bold-o-normal--*-%d-100-100-m-*-iso10646-1 -sansserif.plain.latin-1=-*-helvetica-medium-r-normal--*-%d-100-100-p-*-iso10646-1 -sansserif.bold.latin-1=-*-helvetica-bold-r-normal--*-%d-100-100-p-*-iso10646-1 -sansserif.italic.latin-1=-*-helvetica-medium-o-normal--*-%d-100-100-p-*-iso10646-1 -sansserif.bolditalic.latin-1=-*-helvetica-bold-o-normal--*-%d-100-100-p-*-iso10646-1 +dialog.plain.latin-1=-*-helvetica-medium-r-normal--*-%d-100-100-p-*-iso8859-1 +dialog.plain.thai=-ibm-thaihelvetica-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0 +dialog.plain.ukranian-ibm1124=-*-*-medium-r-normal--*-%d-75-75-p-*-ucs2.i18n-0 +dialog.plain.japanese-x0208=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +dialog.plain.japanese-x0201=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +dialog.plain.japanese-udc=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +dialog.plain.japanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +dialog.plain.korean=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +dialog.plain.korean-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +dialog.plain.chinese=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +dialog.plain.chinese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +dialog.plain.taiwanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 -serif.plain.latin-1=-*-times new roman-medium-r-normal--*-%d-100-100-p-*-iso10646-1 -serif.bold.latin-1=-*-times new roman-bold-r-normal--*-%d-100-100-p-*-iso10646-1 -serif.italic.latin-1=-*-times new roman-medium-i-normal--*-%d-100-100-p-*-iso10646-1 -serif.bolditalic.latin-1=-*-times new roman-bold-i-normal--*-%d-100-100-p-*-iso10646-1 +dialog.bold.latin-1=-*-helvetica-bold-r-normal--*-%d-100-100-p-*-iso8859-1 +dialog.bold.thai=-ibm-thaihelvetica-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0 +dialog.bold.ukranian-ibm1124=-*-*-bold-r-normal--*-%d-75-75-p-*-ucs2.i18n-0 +dialog.bold.japanese-x0208=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +dialog.bold.japanese-x0201=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +dialog.bold.japanese-udc=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +dialog.bold.japanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +dialog.bold.korean=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +dialog.bold.korean-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +dialog.bold.chinese=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +dialog.bold.chinese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +dialog.bold.taiwanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 -monospaced.plain.latin-1=-*-courier-medium-r-normal--*-%d-100-100-m-*-iso10646-1 -monospaced.bold.latin-1=-*-courier-bold-r-normal--*-%d-100-100-m-*-iso10646-1 -monospaced.italic.latin-1=-*-courier-medium-o-normal--*-%d-100-100-m-*-iso10646-1 -monospaced.bolditalic.latin-1=-*-courier-bold-o-normal--*-%d-100-100-m-*-iso10646-1 +dialog.italic.latin-1=-*-helvetica-medium-o-normal--*-%d-100-100-p-*-iso8859-1 +dialog.italic.thai=-ibm-thaihelvetica-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0 +dialog.italic.ukranian-ibm1124=-*-*-medium-i-normal--*-%d-75-75-p-*-ucs2.i18n-0 +dialog.italic.japanese-x0208=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +dialog.italic.japanese-x0201=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +dialog.italic.japanese-udc=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +dialog.italic.japanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +dialog.italic.korean=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +dialog.italic.korean-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +dialog.italic.chinese=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +dialog.italic.chinese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +dialog.italic.taiwanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +dialog.bolditalic.latin-1=-*-helvetica-bold-o-normal--*-%d-100-100-p-*-iso8859-1 +dialog.bolditalic.thai=-ibm-thaihelvetica-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0 +dialog.bolditalic.ukranian-ibm1124=-*-*-medium-r-normal--*-%d-75-75-p-*-ucs2.i18n-0 +dialog.bolditalic.japanese-x0208=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +dialog.bolditalic.japanese-x0201=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +dialog.bolditalic.japanese-udc=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +dialog.bolditalic.japanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +dialog.bolditalic.korean=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +dialog.bolditalic.korean-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +dialog.bolditalic.chinese=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +dialog.bolditalic.chinese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +dialog.bolditalic.taiwanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +dialoginput.plain.latin-1=-*-courier-medium-r-normal--*-%d-100-100-m-*-iso8859-1 +dialoginput.plain.thai=-ibm-thaicourier-medium-r-normal--*-%d-75-75-m-*-ucs2.thai-0 +dialoginput.plain.ukranian-ibm1124=-*-*-medium-r-normal--*-%d-75-75-m-*-ucs2.i18n-0 +dialoginput.plain.japanese-x0208=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +dialoginput.plain.japanese-x0201=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +dialoginput.plain.japanese-udc=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +dialoginput.plain.japanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +dialoginput.plain.korean=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +dialoginput.plain.korean-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +dialoginput.plain.chinese=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +dialoginput.plain.chinese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +dialoginput.plain.taiwanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +dialoginput.bold.latin-1=-*-courier-bold-r-normal--*-%d-100-100-m-*-iso8859-1 +dialoginput.bold.thai=-ibm-thaicourier-medium-r-normal--*-%d-75-75-m-*-ucs2.thai-0 +dialoginput.bold.ukranian-ibm1124=-*-*-bold-r-normal--*-%d-75-75-m-*-ucs2.i18n-0 +dialoginput.bold.japanese-x0208=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +dialoginput.bold.japanese-x0201=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +dialoginput.bold.japanese-udc=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +dialoginput.bold.japanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +dialoginput.bold.korean=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +dialoginput.bold.korean-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +dialoginput.bold.chinese=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +dialoginput.bold.chinese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +dialoginput.bold.taiwanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +dialoginput.italic.latin-1=-*-courier-medium-o-normal--*-%d-100-100-m-*-iso8859-1 +dialoginput.italic.thai=-ibm-thaicourier-medium-r-normal--*-%d-75-75-m-*-ucs2.thai-0 +dialoginput.italic.ukranian-ibm1124=-*-*-medium-i-normal--*-%d-75-75-m-*-ucs2.i18n-0 +dialoginput.italic.japanese-x0208=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +dialoginput.italic.japanese-x0201=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +dialoginput.italic.japanese-udc=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +dialoginput.italic.japanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +dialoginput.italic.korean=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +dialoginput.italic.korean-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +dialoginput.italic.chinese=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +dialoginput.italic.chinese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +dialoginput.italic.taiwanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +dialoginput.bolditalic.latin-1=-*-courier-bold-o-normal--*-%d-100-100-m-*-iso8859-1 +dialoginput.bolditalic.thai=-ibm-thaicourier-medium-r-normal--*-%d-75-75-m-*-ucs2.thai-0 +dialoginput.bolditalic.ukranian-ibm1124=-*-*-medium-r-normal--*-%d-75-75-m-*-ucs2.i18n-0 +dialoginput.bolditalic.japanese-x0208=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +dialoginput.bolditalic.japanese-x0201=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +dialoginput.bolditalic.japanese-udc=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +dialoginput.bolditalic.japanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +dialoginput.bolditalic.korean=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +dialoginput.bolditalic.korean-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +dialoginput.bolditalic.chinese=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +dialoginput.bolditalic.chinese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +dialoginput.bolditalic.taiwanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +sansserif.plain.latin-1=-*-helvetica-medium-r-normal--*-%d-100-100-p-*-iso8859-1 +sansserif.plain.thai=-ibm-thaihelvetica-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0 +sansserif.plain.ukranian-ibm1124=-*-*-medium-r-normal--*-%d-75-75-p-*-ucs2.i18n-0 +sansserif.plain.japanese-x0208=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +sansserif.plain.japanese-x0201=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +sansserif.plain.japanese-udc=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +sansserif.plain.japanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +sansserif.plain.korean=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +sansserif.plain.korean-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +sansserif.plain.chinese=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +sansserif.plain.chinese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +sansserif.plain.taiwanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +sansserif.bold.latin-1=-*-helvetica-bold-r-normal--*-%d-100-100-p-*-iso8859-1 +sansserif.bold.thai=-ibm-thaihelvetica-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0 +sansserif.bold.ukranian-ibm1124=-*-*-bold-r-normal--*-%d-75-75-p-*-ucs2.i18n-0 +sansserif.bold.japanese-x0208=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +sansserif.bold.japanese-x0201=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +sansserif.bold.japanese-udc=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +sansserif.bold.japanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +sansserif.bold.korean=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +sansserif.bold.korean-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +sansserif.bold.chinese=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +sansserif.bold.chinese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +sansserif.bold.taiwanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +sansserif.italic.latin-1=-*-helvetica-medium-o-normal--*-%d-100-100-p-*-iso8859-1 +sansserif.italic.thai=-ibm-thaihelvetica-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0 +sansserif.italic.ukranian-ibm1124=-*-*-medium-i-normal--*-%d-75-75-p-*-ucs2.i18n-0 +sansserif.italic.japanese-x0208=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +sansserif.italic.japanese-x0201=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +sansserif.italic.japanese-udc=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +sansserif.italic.japanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +sansserif.italic.korean=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +sansserif.italic.korean-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +sansserif.italic.chinese=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +sansserif.italic.chinese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +sansserif.italic.taiwanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +sansserif.bolditalic.latin-1=-*-helvetica-bold-o-normal--*-%d-100-100-p-*-iso8859-1 +sansserif.bolditalic.thai=-ibm-thaihelvetica-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0 +sansserif.bolditalic.ukranian-ibm1124=-*-*-medium-r-normal--*-%d-75-75-p-*-ucs2.i18n-0 +sansserif.bolditalic.japanese-x0208=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +sansserif.bolditalic.japanese-x0201=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +sansserif.bolditalic.japanese-udc=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +sansserif.bolditalic.japanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +sansserif.bolditalic.korean=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +sansserif.bolditalic.korean-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +sansserif.bolditalic.chinese=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +sansserif.bolditalic.chinese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +sansserif.bolditalic.taiwanese-iso10646=-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +serif.plain.latin-1=-*-times new roman-medium-r-normal--*-%d-100-100-p-*-iso8859-1 +serif.plain.thai=-ibm-thaitimes-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0 +serif.plain.ukranian-ibm1124=-*-*-medium-r-normal--*-%d-75-75-p-*-ucs2.i18n-0 +serif.plain.japanese-x0208=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +serif.plain.japanese-x0201=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +serif.plain.japanese-udc=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +serif.plain.japanese-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +serif.plain.korean=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +serif.plain.korean-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +serif.plain.chinese=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +serif.plain.chinese-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +serif.plain.taiwanese-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +serif.bold.latin-1=-*-times new roman-bold-r-normal--*-%d-100-100-p-*-iso8859-1 +serif.bold.thai=-ibm-thaitimes-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0 +serif.bold.ukranian-ibm1124=-*-*-bold-r-normal--*-%d-75-75-p-*-ucs2.i18n-0 +serif.bold.japanese-x0208=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +serif.bold.japanese-x0201=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +serif.bold.japanese-udc=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +serif.bold.japanese-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +serif.bold.korean=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +serif.bold.korean-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +serif.bold.chinese=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +serif.bold.chinese-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +serif.bold.taiwanese-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + + +serif.italic.latin-1=-*-times new roman-medium-i-normal--*-%d-100-100-p-*-iso8859-1 +serif.italic.thai=-ibm-thaitimes-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0 +serif.italic.ukranian-ibm1124=-*-*-medium-i-normal--*-%d-75-75-p-*-ucs2.i18n-0 +serif.italic.japanese-x0208=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +serif.italic.japanese-x0201=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +serif.italic.japanese-udc=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +serif.italic.japanese-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +serif.italic.korean=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +serif.italic.korean-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +serif.italic.chinese=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +serif.italic.chinese-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +serif.italic.taiwanese-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +serif.bolditalic.latin-1=-*-times new roman-bold-i-normal--*-%d-100-100-p-*-iso8859-1 +serif.bolditalic.thai=-ibm-thaitimes-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0 +serif.bolditalic.ukranian-ibm1124=-*-*-medium-r-normal--*-%d-75-75-p-*-ucs2.i18n-0 +serif.bolditalic.japanese-x0208=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +serif.bolditalic.japanese-x0201=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +serif.bolditalic.japanese-udc=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +serif.bolditalic.japanese-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +serif.bolditalic.korean=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +serif.bolditalic.korean-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +serif.bolditalic.chinese=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +serif.bolditalic.chinese-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +serif.bolditalic.taiwanese-iso10646=-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +monospaced.plain.latin-1=-*-courier-medium-r-normal--*-%d-100-100-m-*-iso8859-1 +monospaced.plain.thai=-ibm-thaicourier-medium-r-normal--*-%d-75-75-m-*-ucs2.thai-0 +monospaced.plain.ukranian-ibm1124=-*-*-medium-r-normal--*-%d-75-75-m-*-ucs2.i18n-0 +monospaced.plain.japanese-x0208=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +monospaced.plain.japanese-x0201=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +monospaced.plain.japanese-udc=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +monospaced.plain.japanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +monospaced.plain.korean=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +monospaced.plain.korean-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +monospaced.plain.chinese=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +monospaced.plain.chinese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +monospaced.plain.taiwanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +monospaced.bold.latin-1=-*-courier-bold-r-normal--*-%d-100-100-m-*-iso8859-1 +monospaced.bold.thai=-ibm-thaicourier-medium-r-normal--*-%d-75-75-m-*-ucs2.thai-0 +monospaced.bold.ukranian-ibm1124=-*-*-bold-r-normal--*-%d-75-75-m-*-ucs2.i18n-0 +monospaced.bold.japanese-x0208=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +monospaced.bold.japanese-x0201=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +monospaced.bold.japanese-udc=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +monospaced.bold.japanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +monospaced.bold.korean=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +monospaced.bold.korean-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +monospaced.bold.chinese=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +monospaced.bold.chinese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +monospaced.bold.taiwanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +monospaced.italic.latin-1=-*-courier-medium-o-normal--*-%d-100-100-m-*-iso8859-1 +monospaced.italic.thai=-ibm-thaicourier-medium-r-normal--*-%d-75-75-m-*-ucs2.thai-0 +monospaced.italic.ukranian-ibm1124=-*-*-medium-i-normal--*-%d-75-75-m-*-ucs2.i18n-0 +monospaced.italic.japanese-x0208=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +monospaced.italic.japanese-x0201=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +monospaced.italic.japanese-udc=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +monospaced.italic.japanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +monospaced.italic.korean=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +monospaced.italic.korean-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +monospaced.italic.chinese=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +monospaced.italic.chinese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +monospaced.italic.taiwanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 + +monospaced.bolditalic.latin-1=-*-courier-bold-o-normal--*-%d-100-100-m-*-iso8859-1 +monospaced.bolditalic.thai=-ibm-thaicourier-medium-r-normal--*-%d-75-75-m-*-ucs2.thai-0 +monospaced.bolditalic.ukranian-ibm1124=-*-*-medium-r-normal--*-%d-75-75-m-*-ucs2.i18n-0 +monospaced.bolditalic.japanese-x0208=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0 +monospaced.bolditalic.japanese-x0201=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0 +monospaced.bolditalic.japanese-udc=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp +monospaced.bolditalic.japanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0 +monospaced.bolditalic.korean=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0 +monospaced.bolditalic.korean-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0 +monospaced.bolditalic.chinese=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0 +monospaced.bolditalic.chinese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0 +monospaced.bolditalic.taiwanese-iso10646=-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0 # Search Sequences sequence.allfonts=latin-1 +sequence.allfonts.UTF-8=latin-1,japanese-iso10646 +# Uk_UA +sequence.allfonts.x-IBM1124=latin-1,ukranian-ibm1124 +# Japanese +sequence.allfonts.x-IBM943C=latin-1,japanese-x0201,japanese-x0208,japanese-udc +sequence.allfonts.x-IBM29626C=latin-1,japanese-x0201,japanese-x0208,japanese-udc +sequence.allfonts.UTF-8.ja=japanese-iso10646,latin-1,iso10646-extB +# Chinese +sequence.allfonts.x-EUC_CN=latin-1,chinese +sequence.allfonts.GB18030=latin-1,chinese-iso10646,iso10646-extB +sequence.allfonts.UTF-8.zh.CN=latin-1,chinese-iso10646,iso10646-extB +# Taiwanese +sequence.allfonts.x-IBM964=latin-1,taiwanese-iso10646 +sequence.allfonts.Big5=latin-1,taiwanese-iso10646 +sequence.allfonts.UTF-8.zh.TW=latin-1,taiwanese-iso10646 +# Korean +sequence.allfonts.x-IBM970=latin-1,korean +sequence.allfonts.UTF-8.ko=latin-1,korean-iso10646 +# Thai +sequence.allfonts.TIS-620=latin-1,thai +sequence.allfonts.UTF-8.th=latin-1,thai +# fallback +sequence.fallback=thai,chinese-iso10646,taiwanese-iso10646,japanese-iso10646,korean-iso10646,iso10646-extB + +# Exclusion Ranges +exclusion.japanese-iso10646=0000-00ff + +# Font File Names +filename.-*-courier-medium-r-normal--*-%d-100-100-m-*-iso8859-1=/usr/lpp/X11/lib/X11/fonts/Type1/cour.pfa +filename.-*-courier-bold-r-normal--*-%d-100-100-m-*-iso8859-1=/usr/lpp/X11/lib/X11/fonts/Type1/courb.pfa +filename.-*-courier-medium-o-normal--*-%d-100-100-m-*-iso8859-1=/usr/lpp/X11/lib/X11/fonts/Type1/couri.pfa +filename.-*-courier-bold-o-normal--*-%d-100-100-m-*-iso8859-1=/usr/lpp/X11/lib/X11/fonts/Type1/courbi.pfa +filename.-*-helvetica-medium-r-normal--*-%d-100-100-p-*-iso8859-1=/usr/lpp/X11/lib/X11/fonts/Type1/helv.pfa +filename.-*-helvetica-bold-r-normal--*-%d-100-100-p-*-iso8859-1=/usr/lpp/X11/lib/X11/fonts/Type1/helvb.pfa +filename.-*-helvetica-medium-o-normal--*-%d-100-100-p-*-iso8859-1=/usr/lpp/X11/lib/X11/fonts/Type1/helvi.pfa +filename.-*-helvetica-bold-o-normal--*-%d-100-100-p-*-iso8859-1=/usr/lpp/X11/lib/X11/fonts/Type1/helvbi.pfa +filename.-*-times_new_roman-medium-r-normal--*-%d-100-100-p-*-iso8859-1=/usr/lpp/X11/lib/X11/fonts/Type1/tnr.pfa +filename.-*-times_new_roman-bold-r-normal--*-%d-100-100-p-*-iso8859-1=/usr/lpp/X11/lib/X11/fonts/Type1/tnrb.pfa +filename.-*-times_new_roman-medium-i-normal--*-%d-100-100-p-*-iso8859-1=/usr/lpp/X11/lib/X11/fonts/Type1/tnri.pfa +filename.-*-times_new_roman-bold-i-normal--*-%d-100-100-p-*-iso8859-1=/usr/lpp/X11/lib/X11/fonts/Type1/tnrbi.pfa + + +filename.-monotype-sansmonowtextb-medium-r-normal--*-%d-75-75-m-*-unicode-2=/usr/lpp/X11/lib/X11/fonts/TrueType/MTSanXBA.ttf + +filename.-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_j.ttf +filename.-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_j.ttf +filename.-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_j.ttf +filename.-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_j.ttf +filename.-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_k.ttf +filename.-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_k.ttf +filename.-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_s.ttf +filename.-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_s.ttf +filename.-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_s.ttf +filename.-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_s.ttf +filename.-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_t.ttf + +filename.-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdj.ttf +filename.-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdj.ttf +filename.-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdj.ttf +filename.-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdj.ttf +filename.-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdk.ttf +filename.-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdk.ttf +filename.-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansds.ttf +filename.-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansds.ttf +filename.-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdt.ttf +filename.-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0208.1983-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsans_j.ttf +filename.-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-jisx0201.1976-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsans_j.ttf +filename.-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ibm-udcjp=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsans_j.ttf +filename.-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_japan-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsans_j.ttf +filename.-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ksc5601.1987-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsans_k.ttf +filename.-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_korea-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsans_k.ttf +filename.-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-gb2312.1980-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsans_s.ttf +filename.-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_china-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsans_s.ttf +filename.-monotype-sanswt-medium-r-normal--*-%d-75-75-*-*-ucs2.cjk_taiwan-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsans_t.ttf + +filename.-monotype-timesnewromanwt-medium-r-normal--*-%d-75-75-*-*-iso8859-15=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_j.ttf +filename.-monotype-sansmonowt-medium-r-normal--*-%d-75-75-*-*-iso8859-15=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdj.ttf + +filename.-ibm-thaicourier-medium-r-normal--*-%d-75-75-m-*-ucs2.thai-0=/usr/lpp/X11/lib/X11/fonts/TrueType/courth.ttf +filename.-ibm-thaihelvetica-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0=/usr/lpp/X11/lib/X11/fonts/TrueType/helvth.ttf +filename.-ibm-thaitimes-medium-r-normal--*-%d-75-75-p-*-ucs2.thai-0=/usr/lpp/X11/lib/X11/fonts/TrueType/timeth.ttf + +filename.-*-*-medium-r-normal--*-%d-*-*-p-*-ibm-1046=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_j.ttf +filename.-*-*-bold-r-normal--*-%d-*-*-p-*-ibm-1046=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_j.ttf +filename.-*-*-medium-i-normal--*-%d-*-*-p-*-ibm-1046=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_j.ttf +filename.-*-*-bold-i-normal--*-%d-*-*-p-*-ibm-1046=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_j.ttf +filename.-*-*-medium-r-normal--*-%d-*-*-m-*-ibm-1046=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdj.ttf +filename.-*-*-bold-r-normal--*-%d-*-*-m-*-ibm-1046=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdj.ttf +filename.-*-*-medium-i-normal--*-%d-*-*-m-*-ibm-1046=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdj.ttf +filename.-*-*-bold-i-normal--*-%d-*-*-m-*-ibm-1046=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdj.ttf + +filename.-*-*-medium-r-normal--*-%d-75-75-p-*-ucs2.i18n-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_j.ttf +filename.-*-*-bold-r-normal--*-%d-75-75-p-*-ucs2.i18n-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_j.ttf +filename.-*-*-medium-i-normal--*-%d-75-75-p-*-ucs2.i18n-0=/usr/lpp/X11/lib/X11/fonts/TrueType/tnrwt_j.ttf +filename.-*-*-medium-r-normal--*-%d-75-75-m-*-ucs2.i18n-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdj.ttf +filename.-*-*-bold-r-normal--*-%d-75-75-m-*-ucs2.i18n-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdj.ttf +filename.-*-*-medium-i-normal--*-%d-75-75-m-*-ucs2.i18n-0=/usr/lpp/X11/lib/X11/fonts/TrueType/mtsansdj.ttf + +# AWT font path +awtfontpath.japanese-x0201=/usr/lpp/X11/lib/X11/fonts/TrueType +awtfontpath.japanese-x0208=/usr/lpp/X11/lib/X11/fonts/TrueType +awtfontpath.japanese-udc=/usr/lpp/X11/lib/X11/fonts/TrueType +awtfontpath.japanese-iso10646=/usr/lpp/X11/lib/X11/fonts/TrueType +awtfontpath.korean=/usr/lpp/X11/lib/X11/fonts/TrueType +awtfontpath.korean-iso10646=/usr/lpp/X11/lib/X11/fonts/TrueType +awtfontpath.chinese=/usr/lpp/X11/lib/X11/fonts/TrueType +awtfontpath.chinese-iso10646=/usr/lpp/X11/lib/X11/fonts/TrueType +awtfontpath.taiwanese-iso10646=/usr/lpp/X11/lib/X11/fonts/TrueType +awtfontpath.thai=/usr/lpp/X11/lib/X11/fonts/TrueType +awtfontpath.iso10646-extB=/usr/lpp/X11/lib/X11/fonts/TrueType -filename.-*-courier-medium-r-normal--*-%d-100-100-m-*-iso10646-1=/usr/lpp/X11/lib/X11/fonts/Type1/cour.pfa -filename.-*-courier-bold-r-normal--*-%d-100-100-m-*-iso10646-1=/usr/lpp/X11/lib/X11/fonts/Type1/courb.pfa -filename.-*-courier-medium-o-normal--*-%d-100-100-m-*-iso10646-1=/usr/lpp/X11/lib/X11/fonts/Type1/couri.pfa -filename.-*-courier-bold-o-normal--*-%d-100-100-m-*-iso10646-1=/usr/lpp/X11/lib/X11/fonts/Type1/courbi.pfa -filename.-*-helvetica-medium-r-normal--*-%d-100-100-p-*-iso10646-1=/usr/lpp/X11/lib/X11/fonts/Type1/helv.pfa -filename.-*-helvetica-bold-r-normal--*-%d-100-100-p-*-iso10646-1=/usr/lpp/X11/lib/X11/fonts/Type1/helvb.pfa -filename.-*-helvetica-medium-o-normal--*-%d-100-100-p-*-iso10646-1=/usr/lpp/X11/lib/X11/fonts/Type1/helvi.pfa -filename.-*-helvetica-bold-o-normal--*-%d-100-100-p-*-iso10646-1=/usr/lpp/X11/lib/X11/fonts/Type1/helvbi.pfa -filename.-*-times_new_roman-medium-r-normal--*-%d-100-100-p-*-iso10646-1=/usr/lpp/X11/lib/X11/fonts/Type1/tnr.pfa -filename.-*-times_new_roman-bold-r-normal--*-%d-100-100-p-*-iso10646-1=/usr/lpp/X11/lib/X11/fonts/Type1/tnrb.pfa -filename.-*-times_new_roman-medium-i-normal--*-%d-100-100-p-*-iso10646-1=/usr/lpp/X11/lib/X11/fonts/Type1/tnri.pfa -filename.-*-times_new_roman-bold-i-normal--*-%d-100-100-p-*-iso10646-1=/usr/lpp/X11/lib/X11/fonts/Type1/tnrbi.pfa diff --git a/jdk/make/ModulesXml.gmk b/jdk/make/gendata/Gendata-jdk.dev.gmk similarity index 57% rename from jdk/make/ModulesXml.gmk rename to jdk/make/gendata/Gendata-jdk.dev.gmk index 1399e46bace..3c24cf4b703 100644 --- a/jdk/make/ModulesXml.gmk +++ b/jdk/make/gendata/Gendata-jdk.dev.gmk @@ -23,47 +23,24 @@ # questions. # -# Default target declared first -default: all +include GendataCommon.gmk -include $(SPEC) -include MakeBase.gmk -include Tools.gmk +$(eval $(call IncludeCustomExtension, jdk, gendata/Gendata-jdk.dev.gmk)) + +GENDATA := $(JDK_OUTPUTDIR)/modules/jdk.dev/com/sun/tools/jdeps/resources/jdeps-modules.xml +METADATA_FILES += $(TOPDIR)/modules.xml # # Generate modules.xml for jdeps to use # It augments $(TOPDIR)/modules.xml to include module membership # -JDEPS_MODULES_XML := $(JDK_OUTPUTDIR)/modules/jdk.dev/com/sun/tools/jdeps/resources/modules.xml - -METADATA := $(JDK_OUTPUTDIR)/btclasses/build/tools/module/modules.xml -$(METADATA): $(TOPDIR)/modules.xml - $(call install-file) - -METADATA_FILES := $(METADATA) - -ifndef OPENJDK - CLOSED_METADATA := $(JDK_OUTPUTDIR)/btclasses/build/tools/module/closed/modules.xml - $(CLOSED_METADATA): $(TOPDIR)/closed/modules.xml - $(call install-file) - - METADATA_FILES += $(CLOSED_METADATA) -endif - -$(JDEPS_MODULES_XML): $(BUILD_TOOLS_JDK) $(METADATA_FILES) +$(GENDATA): $(BUILD_TOOLS_JDK) $(METADATA_FILES) $(MKDIR) -p $(@D) $(RM) $@ - $(TOOL_GENMODULESXML) $@ $(JDK_OUTPUTDIR)/modules + $(TOOL_GENMODULESXML) -o $@ -mp $(JDK_OUTPUTDIR)/modules $(METADATA_FILES) -# -# Verify access across module boundaries -# -checkdeps: $(JDEPS_MODULES_XML) - $(ECHO) "Checking dependencies across JDK modules" - $(FIXPATH) $(JDK_OUTPUTDIR)/bin/jdeps -verify:access -mp $(JDK_OUTPUTDIR)/modules +jdk.dev: $(GENDATA) -gen-modules-xml: $(JDEPS_MODULES_XML) +all: $(GENDATA) -all: checkdeps - -.PHONY: all +.PHONY: all jdk.dev diff --git a/jdk/make/gensrc/GensrcProviders.gmk b/jdk/make/gensrc/GensrcProviders.gmk index 985f032169e..dca14083054 100644 --- a/jdk/make/gensrc/GensrcProviders.gmk +++ b/jdk/make/gensrc/GensrcProviders.gmk @@ -32,15 +32,6 @@ endef ################################################################################ -# Filter com.sun.tools.attach.spi.AttachProvider -$(JDK_OUTPUTDIR)/gensrc/jdk.attach/META-INF/services/com.sun.tools.attach.spi.AttachProvider: \ - $(JDK_TOPDIR)/src/jdk.attach/share/classes/META-INF/services/com.sun.tools.attach.spi.AttachProvider - $(process-provider) - -GENSRC_JDK_ATTACH += $(JDK_OUTPUTDIR)/gensrc/jdk.attach/META-INF/services/com.sun.tools.attach.spi.AttachProvider - -################################################################################ - # Filter com.sun.jdi.connect.Connector $(JDK_OUTPUTDIR)/gensrc/jdk.jdi/META-INF/services/com.sun.jdi.connect.Connector: \ $(JDK_TOPDIR)/src/jdk.jdi/share/classes/META-INF/services/com.sun.jdi.connect.Connector diff --git a/jdk/make/lib/Awt2dLibraries.gmk b/jdk/make/lib/Awt2dLibraries.gmk index c071b3f093d..e5161a35552 100644 --- a/jdk/make/lib/Awt2dLibraries.gmk +++ b/jdk/make/lib/Awt2dLibraries.gmk @@ -149,13 +149,17 @@ LIBAWT_DIRS := $(JDK_TOPDIR)/src/java.desktop/share/native/libawt \ $(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_API_DIR)/native/common/sun/awt \ # +ifeq ($(OPENJDK_TARGET_OS), aix) + LIBAWT_DIRS += $(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS)/native/libawt +endif + ifeq ($(OPENJDK_TARGET_OS), windows) LIBAWT_DIRS += $(JDK_TOPDIR)/src/java.desktop/share/native/common/sun/awt/utility else LIBAWT_EXFILES := sun/java2d/ShaderList.c endif -ifneq ($(filter $(OPENJDK_TARGET_OS), solaris linux macosx), ) +ifneq ($(filter $(OPENJDK_TARGET_OS), solaris linux macosx aix), ) LIBAWT_EXFILES += awt_Font.c CUPSfuncs.c fontpath.c X11Color.c endif @@ -165,14 +169,11 @@ endif LIBAWT_CFLAGS += -I$(JDK_OUTPUTDIR)/gensrc_headers/java.desktop \ $(addprefix -I, $(shell find $(LIBAWT_DIRS) -type d)) \ - -I$(JDK_TOPDIR)/src/java.desktop/$(OPENJDK_TARGET_OS_API_DIR)/native/common/sun/awt \ $(LIBJAVA_HEADER_FLAGS) \ $(addprefix -I, $(BUILD_LIBMLIB_IMAGE_SRC)) \ # -LIBAWT_CFLAGS += -D__MEDIALIB_OLD_NAMES -D__USE_J2D_NAMES \ - $(X_CFLAGS) \ - $(foreach dir, $(LIBAWT_DIRS), -I$(dir)) +LIBAWT_CFLAGS += -D__MEDIALIB_OLD_NAMES -D__USE_J2D_NAMES $(X_CFLAGS) ifeq ($(OPENJDK_TARGET_OS), macosx) endif diff --git a/jdk/make/lib/Lib-jdk.attach.gmk b/jdk/make/lib/Lib-jdk.attach.gmk index 65b7b1397d7..2b58e173efb 100644 --- a/jdk/make/lib/Lib-jdk.attach.gmk +++ b/jdk/make/lib/Lib-jdk.attach.gmk @@ -27,33 +27,11 @@ include LibCommon.gmk ################################################################################ -ifeq ($(OPENJDK_TARGET_OS), aix) - LIBATTACH_OS_API_DIR := aix -else - LIBATTACH_OS_API_DIR := $(OPENJDK_TARGET_OS_API_DIR) -endif - -LIBATTACH_SRC := $(JDK_TOPDIR)/src/jdk.attach/$(LIBATTACH_OS_API_DIR)/native/libattach - -LIBATTACH_EXCLUDE_FILES := -ifneq ($(OPENJDK_TARGET_OS), solaris) - LIBATTACH_EXCLUDE_FILES += SolarisVirtualMachine.c -endif -ifneq ($(OPENJDK_TARGET_OS), linux) - LIBATTACH_EXCLUDE_FILES += LinuxVirtualMachine.c -endif -ifneq ($(OPENJDK_TARGET_OS), macosx) - LIBATTACH_EXCLUDE_FILES += BsdVirtualMachine.c -endif -ifneq ($(OPENJDK_TARGET_OS),aix) - LIBATTACH_EXCLUDE_FILES += AixVirtualMachine.c -endif $(eval $(call SetupNativeCompilation,BUILD_LIBATTACH, \ LIBRARY := attach, \ OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \ - SRC := $(LIBATTACH_SRC), \ - EXCLUDE_FILES := $(LIBATTACH_EXCLUDE_FILES), \ + SRC := $(JDK_TOPDIR)/src/jdk.attach/$(OPENJDK_TARGET_OS)/native/libattach, \ LANG := C, \ OPTIMIZATION := LOW, \ CFLAGS := $(CFLAGS_JDKLIB) $(CFLAGS_WARNINGS_ARE_ERRORS) \ diff --git a/jdk/make/lib/Lib-jdk.hprof.agent.gmk b/jdk/make/lib/Lib-jdk.hprof.agent.gmk index 7b7ef69b2e0..a58687da251 100644 --- a/jdk/make/lib/Lib-jdk.hprof.agent.gmk +++ b/jdk/make/lib/Lib-jdk.hprof.agent.gmk @@ -27,11 +27,11 @@ include LibCommon.gmk ################################################################################ -BUILD_LIBHPROF_SRC := $(JDK_TOPDIR)/src/demo/share/jvmti/hprof \ - $(JDK_TOPDIR)/src/demo/$(OPENJDK_TARGET_OS_API_DIR)/jvmti/hprof +BUILD_LIBHPROF_SRC := $(call FindSrcDirsForLib, jdk.hprof.agent, hprof) + BUILD_LIBHPROF_CFLAGS := $(addprefix -I, $(BUILD_LIBHPROF_SRC)) \ -I$(JDK_TOPDIR)/src/demo/share/jvmti/java_crw_demo - + BUILD_LIBHPROF_LDFLAGS := LIBHPROF_OPTIMIZATION := HIGHEST diff --git a/jdk/make/lib/NetworkingLibraries.gmk b/jdk/make/lib/NetworkingLibraries.gmk index e61f80be925..a0825b06ce2 100644 --- a/jdk/make/lib/NetworkingLibraries.gmk +++ b/jdk/make/lib/NetworkingLibraries.gmk @@ -44,7 +44,7 @@ ifneq ($(OPENJDK_TARGET_OS), macosx) endif ifeq ($(OPENJDK_TARGET_OS), aix) - LIBNET_SRC_DIRS += $(JDK_TOPDIR)/src/aix/native/java/net/ + LIBNET_SRC_DIRS += $(JDK_TOPDIR)/src/java.base/$(OPENJDK_TARGET_OS)/native/libnet/java/net/ endif $(eval $(call SetupNativeCompilation,BUILD_LIBNET, \ diff --git a/jdk/make/lib/NioLibraries.gmk b/jdk/make/lib/NioLibraries.gmk index 259517c2aad..722115fdee5 100644 --- a/jdk/make/lib/NioLibraries.gmk +++ b/jdk/make/lib/NioLibraries.gmk @@ -56,17 +56,8 @@ endif ifeq ($(OPENJDK_TARGET_OS), aix) BUILD_LIBNIO_MAPFILE:=$(JDK_TOPDIR)/make/mapfiles/libnio/mapfile-$(OPENJDK_TARGET_OS) - BUILD_LIBNIO_FILES += \ - AixPollPort.c \ - InheritedChannel.c \ - AixNativeThread.c \ - PollArrayWrapper.c \ - UnixAsynchronousServerSocketChannelImpl.c \ - UnixAsynchronousSocketChannelImpl.c \ - GnomeFileTypeDetector.c \ - UnixCopyFile.c \ - AixNativeDispatcher.c \ - UnixNativeDispatcher.c + BUILD_LIBNIO_EXFILES += \ + NativeThread.c endif $(eval $(call SetupNativeCompilation,BUILD_LIBNIO, \ diff --git a/jdk/make/mapfiles/libattach/mapfile-aix b/jdk/make/mapfiles/libattach/mapfile-aix index 4c02da01fce..10ca49534ba 100644 --- a/jdk/make/mapfiles/libattach/mapfile-aix +++ b/jdk/make/mapfiles/libattach/mapfile-aix @@ -27,13 +27,13 @@ SUNWprivate_1.1 { global: - Java_sun_tools_attach_AixVirtualMachine_socket - Java_sun_tools_attach_AixVirtualMachine_connect - Java_sun_tools_attach_AixVirtualMachine_sendQuitTo - Java_sun_tools_attach_AixVirtualMachine_checkPermissions - Java_sun_tools_attach_AixVirtualMachine_close - Java_sun_tools_attach_AixVirtualMachine_read - Java_sun_tools_attach_AixVirtualMachine_write + Java_sun_tools_attach_VirtualMachineImpl_socket + Java_sun_tools_attach_VirtualMachineImpl_connect + Java_sun_tools_attach_VirtualMachineImpl_sendQuitTo + Java_sun_tools_attach_VirtualMachineImpl_checkPermissions + Java_sun_tools_attach_VirtualMachineImpl_close + Java_sun_tools_attach_VirtualMachineImpl_read + Java_sun_tools_attach_VirtualMachineImpl_write local: *; }; diff --git a/jdk/make/mapfiles/libattach/mapfile-linux b/jdk/make/mapfiles/libattach/mapfile-linux index fbfdedfdad9..b569ae5e637 100644 --- a/jdk/make/mapfiles/libattach/mapfile-linux +++ b/jdk/make/mapfiles/libattach/mapfile-linux @@ -27,17 +27,17 @@ SUNWprivate_1.1 { global: - Java_sun_tools_attach_LinuxVirtualMachine_checkPermissions; - Java_sun_tools_attach_LinuxVirtualMachine_close; - Java_sun_tools_attach_LinuxVirtualMachine_connect; - Java_sun_tools_attach_LinuxVirtualMachine_getLinuxThreadsManager; - Java_sun_tools_attach_LinuxVirtualMachine_isLinuxThreads; - Java_sun_tools_attach_LinuxVirtualMachine_open; - Java_sun_tools_attach_LinuxVirtualMachine_sendQuitTo; - Java_sun_tools_attach_LinuxVirtualMachine_sendQuitToChildrenOf; - Java_sun_tools_attach_LinuxVirtualMachine_socket; - Java_sun_tools_attach_LinuxVirtualMachine_read; - Java_sun_tools_attach_LinuxVirtualMachine_write; + Java_sun_tools_attach_VirtualMachineImpl_checkPermissions; + Java_sun_tools_attach_VirtualMachineImpl_close; + Java_sun_tools_attach_VirtualMachineImpl_connect; + Java_sun_tools_attach_VirtualMachineImpl_getLinuxThreadsManager; + Java_sun_tools_attach_VirtualMachineImpl_isLinuxThreads; + Java_sun_tools_attach_VirtualMachineImpl_open; + Java_sun_tools_attach_VirtualMachineImpl_sendQuitTo; + Java_sun_tools_attach_VirtualMachineImpl_sendQuitToChildrenOf; + Java_sun_tools_attach_VirtualMachineImpl_socket; + Java_sun_tools_attach_VirtualMachineImpl_read; + Java_sun_tools_attach_VirtualMachineImpl_write; local: *; }; diff --git a/jdk/make/mapfiles/libattach/mapfile-solaris b/jdk/make/mapfiles/libattach/mapfile-solaris index 6e61f754b99..df71490fdb8 100644 --- a/jdk/make/mapfiles/libattach/mapfile-solaris +++ b/jdk/make/mapfiles/libattach/mapfile-solaris @@ -27,12 +27,12 @@ SUNWprivate_1.1 { global: - Java_sun_tools_attach_SolarisVirtualMachine_checkPermissions; - Java_sun_tools_attach_SolarisVirtualMachine_enqueue; - Java_sun_tools_attach_SolarisVirtualMachine_open; - Java_sun_tools_attach_SolarisVirtualMachine_close; - Java_sun_tools_attach_SolarisVirtualMachine_read; - Java_sun_tools_attach_SolarisVirtualMachine_sigquit; + Java_sun_tools_attach_VirtualMachineImpl_checkPermissions; + Java_sun_tools_attach_VirtualMachineImpl_enqueue; + Java_sun_tools_attach_VirtualMachineImpl_open; + Java_sun_tools_attach_VirtualMachineImpl_close; + Java_sun_tools_attach_VirtualMachineImpl_read; + Java_sun_tools_attach_VirtualMachineImpl_sigquit; local: *; }; diff --git a/jdk/make/mapfiles/libnio/mapfile-linux b/jdk/make/mapfiles/libnio/mapfile-linux index 16f72e43cfa..53555c4763f 100644 --- a/jdk/make/mapfiles/libnio/mapfile-linux +++ b/jdk/make/mapfiles/libnio/mapfile-linux @@ -79,6 +79,7 @@ SUNWprivate_1.1 { Java_sun_nio_ch_InheritedChannel_close0; Java_sun_nio_ch_InheritedChannel_dup; Java_sun_nio_ch_InheritedChannel_dup2; + Java_sun_nio_ch_InheritedChannel_initIDs; Java_sun_nio_ch_InheritedChannel_open0; Java_sun_nio_ch_InheritedChannel_peerAddress0; Java_sun_nio_ch_InheritedChannel_peerPort0; diff --git a/jdk/make/mapfiles/libnio/mapfile-macosx b/jdk/make/mapfiles/libnio/mapfile-macosx index 4dd0dc513e4..d4b6dc5a219 100644 --- a/jdk/make/mapfiles/libnio/mapfile-macosx +++ b/jdk/make/mapfiles/libnio/mapfile-macosx @@ -62,6 +62,7 @@ SUNWprivate_1.1 { Java_sun_nio_ch_InheritedChannel_close0; Java_sun_nio_ch_InheritedChannel_dup; Java_sun_nio_ch_InheritedChannel_dup2; + Java_sun_nio_ch_InheritedChannel_initIDs; Java_sun_nio_ch_InheritedChannel_open0; Java_sun_nio_ch_InheritedChannel_peerAddress0; Java_sun_nio_ch_InheritedChannel_peerPort0; diff --git a/jdk/make/mapfiles/libnio/mapfile-solaris b/jdk/make/mapfiles/libnio/mapfile-solaris index 3933cef7ada..cdbb851bcad 100644 --- a/jdk/make/mapfiles/libnio/mapfile-solaris +++ b/jdk/make/mapfiles/libnio/mapfile-solaris @@ -67,6 +67,7 @@ SUNWprivate_1.1 { Java_sun_nio_ch_InheritedChannel_close0; Java_sun_nio_ch_InheritedChannel_dup; Java_sun_nio_ch_InheritedChannel_dup2; + Java_sun_nio_ch_InheritedChannel_initIDs; Java_sun_nio_ch_InheritedChannel_open0; Java_sun_nio_ch_InheritedChannel_peerAddress0; Java_sun_nio_ch_InheritedChannel_peerPort0; diff --git a/jdk/make/src/classes/build/tools/module/GenerateModulesXml.java b/jdk/make/src/classes/build/tools/module/GenJdepsModulesXml.java similarity index 90% rename from jdk/make/src/classes/build/tools/module/GenerateModulesXml.java rename to jdk/make/src/classes/build/tools/module/GenJdepsModulesXml.java index c2fdf4ae9d1..43ba458f326 100644 --- a/jdk/make/src/classes/build/tools/module/GenerateModulesXml.java +++ b/jdk/make/src/classes/build/tools/module/GenJdepsModulesXml.java @@ -25,6 +25,7 @@ package build.tools.module; +import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -49,47 +50,56 @@ import javax.xml.stream.events.Attribute; import javax.xml.stream.events.XMLEvent; /** - * This tool is used to generate com/sun/tools/jdeps/resources/modules.xml - * for jdeps to analyze dependencies and enforce module boundaries. + * GenJdepsModulesXml augments the input modules.xml file(s) + * to include the module membership from the given path to + * the JDK exploded image. The output file is used by jdeps + * to analyze dependencies and enforce module boundaries. * - * $ java build.tools.module.GenerateModulesXml \ - * com/sun/tools/jdeps/resources/modules.xml $OUTPUTDIR/modules + * The input modules.xml file defines the modular structure of + * the JDK as described in JEP 200: The Modular JDK + * (http://openjdk.java.net/jeps/200). * - * This will generate modules.xml as jdeps resources that extend - * the metadata to include module membership (jdeps needs the - * membership information to determine which module a type belongs to.) + * $ java build.tools.module.GenJdepsModulesXml \ + * -o com/sun/tools/jdeps/resources/modules.xml \ + * -mp $OUTPUTDIR/modules \ + * top/modules.xml */ -public final class GenerateModulesXml { +public final class GenJdepsModulesXml { private final static String USAGE = - "Usage: GenerateModulesXml build/modules"; + "Usage: GenJdepsModulesXml -o -mp build/modules path-to-modules-xml"; public static void main(String[] args) throws Exception { - if (args.length < 2) { + Path outfile = null; + Path modulepath = null; + int i = 0; + while (i < args.length) { + String arg = args[i]; + if (arg.equals("-o")) { + outfile = Paths.get(args[i+1]); + i = i+2; + } else if (arg.equals("-mp")) { + modulepath = Paths.get(args[i+1]); + i = i+2; + if (!Files.isDirectory(modulepath)) { + System.err.println(modulepath + " is not a directory"); + System.exit(1); + } + } else { + break; + } + } + if (outfile == null || modulepath == null || i >= args.length) { System.err.println(USAGE); System.exit(-1); } - Path outfile = Paths.get(args[0]); - Path modulepath = Paths.get(args[1]); - - if (!Files.isDirectory(modulepath)) { - System.err.println(modulepath + " is not a directory"); - System.exit(1); - } - GenerateModulesXml gentool = - new GenerateModulesXml(modulepath); - Set modules; - try (InputStream in = GenerateModulesXml.class.getResourceAsStream("modules.xml")) { - modules = gentool.load(in); - } - - InputStream in = GenerateModulesXml.class.getResourceAsStream("closed/modules.xml"); - if (in != null) { - try { + GenJdepsModulesXml gentool = new GenJdepsModulesXml(modulepath); + Set modules = new HashSet<>(); + for (; i < args.length; i++) { + Path p = Paths.get(args[i]); + try (InputStream in = new BufferedInputStream(Files.newInputStream(p))) { Set mods = gentool.load(in); modules.addAll(mods); - } finally { - in.close(); } } @@ -98,7 +108,7 @@ public final class GenerateModulesXml { } final Path modulepath; - public GenerateModulesXml(Path modulepath) { + public GenJdepsModulesXml(Path modulepath) { this.modulepath = modulepath; } @@ -275,7 +285,7 @@ public final class GenerateModulesXml { m.exports().keySet().stream() .filter(pn -> m.exports().get(pn).isEmpty()) .sorted() - .forEach(pn -> GenerateModulesXml.this.writeExportElement(xtw, pn, depth+1)); + .forEach(pn -> writeExportElement(xtw, pn, depth+1)); m.exports().entrySet().stream() .filter(e -> !e.getValue().isEmpty()) .sorted(Map.Entry.comparingByKey()) diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/README b/jdk/src/demo/share/jpda/com/sun/tools/example/README deleted file mode 100644 index 13e1540f14c..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/README +++ /dev/null @@ -1,3 +0,0 @@ -Please refer to the documentation in: - - doc/index.html diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/AccessWatchpointSpec.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/AccessWatchpointSpec.java deleted file mode 100644 index 0d9fe21a7d3..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/AccessWatchpointSpec.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; - -public class AccessWatchpointSpec extends WatchpointSpec { - - AccessWatchpointSpec(EventRequestSpecList specs, - ReferenceTypeSpec refSpec, String fieldId) { - super(specs, refSpec, fieldId); - } - - /** - * The 'refType' is known to match. - */ - @Override - void resolve(ReferenceType refType) throws InvalidTypeException, - NoSuchFieldException { - if (!(refType instanceof ClassType)) { - throw new InvalidTypeException(); - } - Field field = refType.fieldByName(fieldId); - if (field == null) { - throw new NoSuchFieldException(fieldId); - } - setRequest(refType.virtualMachine().eventRequestManager() - .createAccessWatchpointRequest(field)); - } - - @Override - public boolean equals(Object obj) { - return (obj instanceof AccessWatchpointSpec) && super.equals(obj); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/AmbiguousMethodException.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/AmbiguousMethodException.java deleted file mode 100644 index 97d54dd32c8..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/AmbiguousMethodException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public class AmbiguousMethodException extends Exception -{ - - private static final long serialVersionUID = 7793370943251707514L; - - public AmbiguousMethodException() - { - super(); - } - - public AmbiguousMethodException(String s) - { - super(s); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/BreakpointSpec.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/BreakpointSpec.java deleted file mode 100644 index 50059c1ff49..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/BreakpointSpec.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public abstract class BreakpointSpec extends EventRequestSpec { - - BreakpointSpec(EventRequestSpecList specs, ReferenceTypeSpec refSpec) { - super(specs, refSpec); - } - - @Override - void notifySet(SpecListener listener, SpecEvent evt) { - listener.breakpointSet(evt); - } - - @Override - void notifyDeferred(SpecListener listener, SpecEvent evt) { - listener.breakpointDeferred(evt); - } - - @Override - void notifyResolved(SpecListener listener, SpecEvent evt) { - listener.breakpointResolved(evt); - } - - @Override - void notifyDeleted(SpecListener listener, SpecEvent evt) { - listener.breakpointDeleted(evt); - } - - @Override - void notifyError(SpecListener listener, SpecErrorEvent evt) { - listener.breakpointError(evt); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ChildSession.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ChildSession.java deleted file mode 100644 index b6042a6e845..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ChildSession.java +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; -import com.sun.jdi.connect.LaunchingConnector; -import com.sun.jdi.connect.Connector; -import com.sun.jdi.connect.VMStartException; -import com.sun.jdi.connect.IllegalConnectorArgumentsException; -import java.io.*; -import java.util.Map; -import javax.swing.SwingUtilities; - - -class ChildSession extends Session { - - private Process process; - - private PrintWriter in; - private BufferedReader out; - private BufferedReader err; - - private InputListener input; - private OutputListener output; - private OutputListener error; - - public ChildSession(ExecutionManager runtime, - String userVMArgs, String cmdLine, - InputListener input, - OutputListener output, - OutputListener error, - OutputListener diagnostics) { - this(runtime, getVM(diagnostics, userVMArgs, cmdLine), - input, output, error, diagnostics); - } - - public ChildSession(ExecutionManager runtime, - LaunchingConnector connector, - Map arguments, - InputListener input, - OutputListener output, - OutputListener error, - OutputListener diagnostics) { - this(runtime, generalGetVM(diagnostics, connector, arguments), - input, output, error, diagnostics); - } - - private ChildSession(ExecutionManager runtime, - VirtualMachine vm, - InputListener input, - OutputListener output, - OutputListener error, - OutputListener diagnostics) { - super(vm, runtime, diagnostics); - this.input = input; - this.output = output; - this.error = error; - } - - @Override - public boolean attach() { - - if (!connectToVMProcess()) { - diagnostics.putString("Could not launch VM"); - return false; - } - - /* - * Create a Thread that will retrieve and display any output. - * Needs to be high priority, else debugger may exit before - * it can be displayed. - */ - - //### Rename InputWriter and OutputReader classes - //### Thread priorities cribbed from ttydebug. Think about them. - - OutputReader outputReader = - new OutputReader("output reader", "output", - out, output, diagnostics); - outputReader.setPriority(Thread.MAX_PRIORITY-1); - outputReader.start(); - - OutputReader errorReader = - new OutputReader("error reader", "error", - err, error, diagnostics); - errorReader.setPriority(Thread.MAX_PRIORITY-1); - errorReader.start(); - - InputWriter inputWriter = - new InputWriter("input writer", in, input); - inputWriter.setPriority(Thread.MAX_PRIORITY-1); - inputWriter.start(); - - if (!super.attach()) { - if (process != null) { - process.destroy(); - process = null; - } - return false; - } - - //### debug - //System.out.println("IO after attach: "+ inputWriter + " " + outputReader + " "+ errorReader); - - return true; - } - - @Override - public void detach() { - - //### debug - //System.out.println("IO before detach: "+ inputWriter + " " + outputReader + " "+ errorReader); - - super.detach(); - - /* - inputWriter.quit(); - outputReader.quit(); - errorReader.quit(); - */ - - if (process != null) { - process.destroy(); - process = null; - } - - } - - /** - * Launch child java interpreter, return host:port - */ - - static private void dumpStream(OutputListener diagnostics, - InputStream stream) throws IOException { - BufferedReader in = - new BufferedReader(new InputStreamReader(stream)); - String line; - while ((line = in.readLine()) != null) { - diagnostics.putString(line); - } - } - - static private void dumpFailedLaunchInfo(OutputListener diagnostics, - Process process) { - try { - dumpStream(diagnostics, process.getErrorStream()); - dumpStream(diagnostics, process.getInputStream()); - } catch (IOException e) { - diagnostics.putString("Unable to display process output: " + - e.getMessage()); - } - } - - static private VirtualMachine getVM(OutputListener diagnostics, - String userVMArgs, - String cmdLine) { - VirtualMachineManager manager = Bootstrap.virtualMachineManager(); - LaunchingConnector connector = manager.defaultConnector(); - Map arguments = connector.defaultArguments(); - arguments.get("options").setValue(userVMArgs); - arguments.get("main").setValue(cmdLine); - return generalGetVM(diagnostics, connector, arguments); - } - - static private VirtualMachine generalGetVM(OutputListener diagnostics, - LaunchingConnector connector, - Map arguments) { - VirtualMachine vm = null; - try { - diagnostics.putString("Starting child."); - vm = connector.launch(arguments); - } catch (IOException ioe) { - diagnostics.putString("Unable to start child: " + ioe.getMessage()); - } catch (IllegalConnectorArgumentsException icae) { - diagnostics.putString("Unable to start child: " + icae.getMessage()); - } catch (VMStartException vmse) { - diagnostics.putString("Unable to start child: " + vmse.getMessage() + '\n'); - dumpFailedLaunchInfo(diagnostics, vmse.process()); - } - return vm; - } - - private boolean connectToVMProcess() { - if (vm == null) { - return false; - } - process = vm.process(); - in = new PrintWriter(new OutputStreamWriter(process.getOutputStream())); - //### Note small buffer sizes! - out = new BufferedReader(new InputStreamReader(process.getInputStream()), 1); - err = new BufferedReader(new InputStreamReader(process.getErrorStream()), 1); - return true; - } - - /** - * Threads to handle application input/output. - */ - - private static class OutputReader extends Thread { - - private String streamName; - private BufferedReader stream; - private OutputListener output; - private OutputListener diagnostics; - private boolean running = true; - private char[] buffer = new char[512]; - - OutputReader(String threadName, - String streamName, - BufferedReader stream, - OutputListener output, - OutputListener diagnostics) { - super(threadName); - this.streamName = streamName; - this.stream = stream; - this.output = output; - this.diagnostics = diagnostics; - } - - @Override - public void run() { - try { - int count; - while (running && (count = stream.read(buffer, 0, 512)) != -1) { - if (count > 0) { - // Run in Swing event dispatcher thread. - final String chars = new String(buffer, 0, count); - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - output.putString(chars); - } - }); - } - //### Should we sleep briefly here? - } - } catch (IOException e) { - // Run in Swing event dispatcher thread. - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - diagnostics.putString("IO error reading " + - streamName + - " stream of child java interpreter"); - } - }); - } - } - } - - private static class InputWriter extends Thread { - - private PrintWriter stream; - private InputListener input; - private boolean running = true; - - InputWriter(String threadName, - PrintWriter stream, - InputListener input) { - super(threadName); - this.stream = stream; - this.input = input; - } - - @Override - public void run() { - String line; - while (running) { - line = input.getLine(); - stream.println(line); - // Should not be needed for println above! - stream.flush(); - } - } - } - -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/EvaluationException.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/EvaluationException.java deleted file mode 100644 index b9a02c37117..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/EvaluationException.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public class EvaluationException extends Exception { - - private static final long serialVersionUID = 4947109680354951694L; -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/EventRequestSpec.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/EventRequestSpec.java deleted file mode 100644 index 0ea58fb3ebd..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/EventRequestSpec.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; -import com.sun.jdi.request.EventRequest; - -abstract public class EventRequestSpec { - - static final int STATUS_UNRESOLVED = 1; - static final int STATUS_RESOLVED = 2; - static final int STATUS_ERROR = 3; - - static final Object specPropertyKey = "spec"; - - final EventRequestSpecList specs; - final ReferenceTypeSpec refSpec; - EventRequest request = null; - - int status = STATUS_UNRESOLVED; - - EventRequestSpec(EventRequestSpecList specs, ReferenceTypeSpec refSpec) { - this.specs = specs; - this.refSpec = refSpec; - } - - void setRequest(EventRequest request) { - this.request = request; - request.putProperty(specPropertyKey, this); - request.enable(); - } - - /** - * The 'refType' is known to match. - */ - abstract void resolve(ReferenceType refType) throws Exception; - - abstract void notifySet(SpecListener listener, SpecEvent evt); - abstract void notifyDeferred(SpecListener listener, SpecEvent evt); - abstract void notifyResolved(SpecListener listener, SpecEvent evt); - abstract void notifyDeleted(SpecListener listener, SpecEvent evt); - abstract void notifyError(SpecListener listener, SpecErrorEvent evt); - - /** - * The 'refType' is known to match. - */ - void resolveNotify(ReferenceType refType) { - try { - resolve(refType); - status = STATUS_RESOLVED; - specs.notifyResolved(this); - } catch(Exception exc) { - status = STATUS_ERROR; - specs.notifyError(this, exc); - } - } - - /** - * See if 'refType' matches and resolve. - */ - void attemptResolve(ReferenceType refType) { - if (!isResolved() && refSpec.matches(refType)) { - resolveNotify(refType); - } - } - - void attemptImmediateResolve(VirtualMachine vm) { - // try to resolve immediately - for (ReferenceType refType : vm.allClasses()) { - if (refSpec.matches(refType)) { - try { - resolve(refType); - status = STATUS_RESOLVED; - specs.notifySet(this); - } catch(Exception exc) { - status = STATUS_ERROR; - specs.notifyError(this, exc); - } - return; - } - } - specs.notifyDeferred(this); - } - - public EventRequest getEventRequest() { - return request; - } - - /** - * @return true if this spec has been resolved. - */ - public boolean isResolved() { - return status == STATUS_RESOLVED; - } - - /** - * @return true if this spec has not yet been resolved. - */ - public boolean isUnresolved() { - return status == STATUS_UNRESOLVED; - } - - /** - * @return true if this spec is unresolvable due to error. - */ - public boolean isErroneous() { - return status == STATUS_ERROR; - } - - public String getStatusString() { - switch (status) { - case STATUS_RESOLVED: - return "resolved"; - case STATUS_UNRESOLVED: - return "deferred"; - case STATUS_ERROR: - return "erroneous"; - } - return "unknown"; - } - - boolean isJavaIdentifier(String s) { - return Utils.isJavaIdentifier(s); - } - - public String errorMessageFor(Exception e) { - if (e instanceof IllegalArgumentException) { - return ("Invalid command syntax"); - } else if (e instanceof RuntimeException) { - // A runtime exception that we were not expecting - throw (RuntimeException)e; - } else { - return ("Internal error; unable to set" + this); - } - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/EventRequestSpecList.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/EventRequestSpecList.java deleted file mode 100644 index 17c001483c7..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/EventRequestSpecList.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; -import com.sun.jdi.request.*; - -import java.util.*; - -class EventRequestSpecList { - - // all specs - private List eventRequestSpecs = Collections.synchronizedList( - new ArrayList()); - - final ExecutionManager runtime; - - EventRequestSpecList(ExecutionManager runtime) { - this.runtime = runtime; - } - - /** - * Resolve all deferred eventRequests waiting for 'refType'. - */ - void resolve(ReferenceType refType) { - synchronized(eventRequestSpecs) { - for (EventRequestSpec spec : eventRequestSpecs) { - spec.attemptResolve(refType); - } - } - } - - void install(EventRequestSpec ers, VirtualMachine vm) { - synchronized (eventRequestSpecs) { - eventRequestSpecs.add(ers); - } - if (vm != null) { - ers.attemptImmediateResolve(vm); - } - } - - BreakpointSpec - createClassLineBreakpoint(String classPattern, int line) { - ReferenceTypeSpec refSpec = - new PatternReferenceTypeSpec(classPattern); - return new LineBreakpointSpec(this, refSpec, line); - } - - BreakpointSpec - createSourceLineBreakpoint(String sourceName, int line) { - ReferenceTypeSpec refSpec = - new SourceNameReferenceTypeSpec(sourceName, line); - return new LineBreakpointSpec(this, refSpec, line); - } - - BreakpointSpec - createMethodBreakpoint(String classPattern, - String methodId, List methodArgs) { - ReferenceTypeSpec refSpec = - new PatternReferenceTypeSpec(classPattern); - return new MethodBreakpointSpec(this, refSpec, - methodId, methodArgs); - } - - ExceptionSpec - createExceptionIntercept(String classPattern, - boolean notifyCaught, - boolean notifyUncaught) { - ReferenceTypeSpec refSpec = - new PatternReferenceTypeSpec(classPattern); - return new ExceptionSpec(this, refSpec, - notifyCaught, notifyUncaught); - } - - AccessWatchpointSpec - createAccessWatchpoint(String classPattern, String fieldId) { - ReferenceTypeSpec refSpec = - new PatternReferenceTypeSpec(classPattern); - return new AccessWatchpointSpec(this, refSpec, fieldId); - } - - ModificationWatchpointSpec - createModificationWatchpoint(String classPattern, String fieldId) { - ReferenceTypeSpec refSpec = - new PatternReferenceTypeSpec(classPattern); - return new ModificationWatchpointSpec(this, refSpec, fieldId); - } - - void delete(EventRequestSpec ers) { - EventRequest request = ers.getEventRequest(); - synchronized (eventRequestSpecs) { - eventRequestSpecs.remove(ers); - } - if (request != null) { - request.virtualMachine().eventRequestManager() - .deleteEventRequest(request); - } - notifyDeleted(ers); - //### notify delete - here? - } - - List eventRequestSpecs() { - // We need to make a copy to avoid synchronization problems - synchronized (eventRequestSpecs) { - return new ArrayList(eventRequestSpecs); - } - } - - // -------- notify routines -------------------- - - @SuppressWarnings("unchecked") - private Vector specListeners() { - return (Vector)runtime.specListeners.clone(); - } - - void notifySet(EventRequestSpec spec) { - Vector l = specListeners(); - SpecEvent evt = new SpecEvent(spec); - for (int i = 0; i < l.size(); i++) { - spec.notifySet(l.elementAt(i), evt); - } - } - - void notifyDeferred(EventRequestSpec spec) { - Vector l = specListeners(); - SpecEvent evt = new SpecEvent(spec); - for (int i = 0; i < l.size(); i++) { - spec.notifyDeferred(l.elementAt(i), evt); - } - } - - void notifyDeleted(EventRequestSpec spec) { - Vector l = specListeners(); - SpecEvent evt = new SpecEvent(spec); - for (int i = 0; i < l.size(); i++) { - spec.notifyDeleted(l.elementAt(i), evt); - } - } - - void notifyResolved(EventRequestSpec spec) { - Vector l = specListeners(); - SpecEvent evt = new SpecEvent(spec); - for (int i = 0; i < l.size(); i++) { - spec.notifyResolved(l.elementAt(i), evt); - } - } - - void notifyError(EventRequestSpec spec, Exception exc) { - Vector l = specListeners(); - SpecErrorEvent evt = new SpecErrorEvent(spec, exc); - for (int i = 0; i < l.size(); i++) { - spec.notifyError(l.elementAt(i), evt); - } - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ExceptionSpec.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ExceptionSpec.java deleted file mode 100644 index df87688152c..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ExceptionSpec.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.ReferenceType; - -public class ExceptionSpec extends EventRequestSpec { - - boolean notifyCaught; - boolean notifyUncaught; - - ExceptionSpec(EventRequestSpecList specs, ReferenceTypeSpec refSpec, - boolean notifyCaught, boolean notifyUncaught) - { - super(specs, refSpec); - this.notifyCaught = notifyCaught; - this.notifyUncaught = notifyUncaught; - } - - @Override - void notifySet(SpecListener listener, SpecEvent evt) { - listener.exceptionInterceptSet(evt); - } - - @Override - void notifyDeferred(SpecListener listener, SpecEvent evt) { - listener.exceptionInterceptDeferred(evt); - } - - @Override - void notifyResolved(SpecListener listener, SpecEvent evt) { - listener.exceptionInterceptResolved(evt); - } - - @Override - void notifyDeleted(SpecListener listener, SpecEvent evt) { - listener.exceptionInterceptDeleted(evt); - } - - @Override - void notifyError(SpecListener listener, SpecErrorEvent evt) { - listener.exceptionInterceptError(evt); - } - - /** - * The 'refType' is known to match. - */ - @Override - void resolve(ReferenceType refType) { - setRequest(refType.virtualMachine().eventRequestManager() - .createExceptionRequest(refType, - notifyCaught, notifyUncaught)); - } - - @Override - public int hashCode() { - return refSpec.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof ExceptionSpec) { - ExceptionSpec es = (ExceptionSpec)obj; - - return refSpec.equals(es.refSpec); - } else { - return false; - } - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("exception catch "); - sb.append(refSpec.toString()); - return sb.toString(); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ExecutionManager.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ExecutionManager.java deleted file mode 100644 index b5bc053a3c3..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ExecutionManager.java +++ /dev/null @@ -1,824 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; -import com.sun.jdi.request.*; -import com.sun.jdi.connect.*; -import com.sun.tools.example.debug.expr.ExpressionParser; -import com.sun.tools.example.debug.expr.ParseException; - -import java.io.*; -import java.util.*; - -import com.sun.tools.example.debug.event.*; - -import javax.swing.SwingUtilities; - -/** - * Move this towards being only state and functionality - * that spans across Sessions (and thus VMs). - */ -public class ExecutionManager { - - private Session session; - - /** - * Get/set JDI trace mode. - */ - int traceMode = VirtualMachine.TRACE_NONE; - - ////////////////// Listener registration ////////////////// - - // Session Listeners - - ArrayList sessionListeners = new ArrayList(); - - public void addSessionListener(SessionListener listener) { - sessionListeners.add(listener); - } - - public void removeSessionListener(SessionListener listener) { - sessionListeners.remove(listener); - } - - // Spec Listeners - - ArrayList specListeners = new ArrayList(); - - public void addSpecListener(SpecListener cl) { - specListeners.add(cl); - } - - public void removeSpecListener(SpecListener cl) { - specListeners.remove(cl); - } - - // JDI Listeners - - ArrayList jdiListeners = new ArrayList(); - - /** - * Adds a JDIListener - */ - public void addJDIListener(JDIListener jl) { - jdiListeners.add(jl); - } - - /** - * Adds a JDIListener - at the specified position - */ - public void addJDIListener(int index, JDIListener jl) { - jdiListeners.add(index, jl); - } - - /** - * Removes a JDIListener - */ - public void removeJDIListener(JDIListener jl) { - jdiListeners.remove(jl); - } - - // App Echo Listeners - - private ArrayList appEchoListeners = new ArrayList(); - - public void addApplicationEchoListener(OutputListener l) { - appEchoListeners.add(l); - } - - public void removeApplicationEchoListener(OutputListener l) { - appEchoListeners.remove(l); - } - - // App Output Listeners - - private ArrayList appOutputListeners = new ArrayList(); - - public void addApplicationOutputListener(OutputListener l) { - appOutputListeners.add(l); - } - - public void removeApplicationOutputListener(OutputListener l) { - appOutputListeners.remove(l); - } - - // App Error Listeners - - private ArrayList appErrorListeners = new ArrayList(); - - public void addApplicationErrorListener(OutputListener l) { - appErrorListeners.add(l); - } - - public void removeApplicationErrorListener(OutputListener l) { - appErrorListeners.remove(l); - } - - // Diagnostic Listeners - - private ArrayList diagnosticsListeners = new ArrayList(); - - public void addDiagnosticsListener(OutputListener l) { - diagnosticsListeners.add(l); - } - - public void removeDiagnosticsListener(OutputListener l) { - diagnosticsListeners.remove(l); - } - - /////////// End Listener Registration ////////////// - - //### We probably don't want this public - public VirtualMachine vm() { - return session == null ? null : session.vm; - } - - void ensureActiveSession() throws NoSessionException { - if (session == null) { - throw new NoSessionException(); - } - } - - public EventRequestManager eventRequestManager() { - return vm() == null ? null : vm().eventRequestManager(); - } - - /** - * Get JDI trace mode. - */ - public int getTraceMode(int mode) { - return traceMode; - } - - /** - * Set JDI trace mode. - */ - public void setTraceMode(int mode) { - traceMode = mode; - if (session != null) { - session.setTraceMode(mode); - } - } - - /** - * Determine if VM is interrupted, i.e, present and not running. - */ - public boolean isInterrupted() /* should: throws NoSessionException */ { -// ensureActiveSession(); - return session.interrupted; - } - - /** - * Return a list of ReferenceType objects for all - * currently loaded classes and interfaces. - * Array types are not returned. - */ - public List allClasses() throws NoSessionException { - ensureActiveSession(); - return vm().allClasses(); - } - - /** - * Return a ReferenceType object for the currently - * loaded class or interface whose fully-qualified - * class name is specified, else return null if there - * is none. - * - * In general, we must return a list of types, because - * multiple class loaders could have loaded a class - * with the same fully-qualified name. - */ - public List findClassesByName(String name) throws NoSessionException { - ensureActiveSession(); - return vm().classesByName(name); - } - - /** - * Return a list of ReferenceType objects for all - * currently loaded classes and interfaces whose name - * matches the given pattern. The pattern syntax is - * open to some future revision, but currently consists - * of a fully-qualified class name in which the first - * component may optionally be a "*" character, designating - * an arbitrary prefix. - */ - public List findClassesMatchingPattern(String pattern) - throws NoSessionException { - ensureActiveSession(); - List result = new ArrayList(); //### Is default size OK? - if (pattern.startsWith("*.")) { - // Wildcard matches any leading package name. - pattern = pattern.substring(1); - for (ReferenceType type : vm().allClasses()) { - if (type.name().endsWith(pattern)) { - result.add(type); - } - } - return result; - } else { - // It's a class name. - return vm().classesByName(pattern); - } - } - - /* - * Return a list of ThreadReference objects corresponding - * to the threads that are currently active in the VM. - * A thread is removed from the list just before the - * thread terminates. - */ - - public List allThreads() throws NoSessionException { - ensureActiveSession(); - return vm().allThreads(); - } - - /* - * Return a list of ThreadGroupReference objects corresponding - * to the top-level threadgroups that are currently active in the VM. - * Note that a thread group may be empty, or contain no threads as - * descendents. - */ - - public List topLevelThreadGroups() throws NoSessionException { - ensureActiveSession(); - return vm().topLevelThreadGroups(); - } - - /* - * Return the system threadgroup. - */ - - public ThreadGroupReference systemThreadGroup() - throws NoSessionException { - ensureActiveSession(); - return vm().topLevelThreadGroups().get(0); - } - - /* - * Evaluate an expression. - */ - - public Value evaluate(final StackFrame f, String expr) - throws ParseException, - InvocationException, - InvalidTypeException, - ClassNotLoadedException, - NoSessionException, - IncompatibleThreadStateException { - ExpressionParser.GetFrame frameGetter = null; - ensureActiveSession(); - if (f != null) { - frameGetter = new ExpressionParser.GetFrame() { - @Override - public StackFrame get() /* throws IncompatibleThreadStateException */ { - return f; - } - }; - } - return ExpressionParser.evaluate(expr, vm(), frameGetter); - } - - - /* - * Start a new VM. - */ - - public void run(boolean suspended, - String vmArgs, - String className, - String args) throws VMLaunchFailureException { - - endSession(); - - //### Set a breakpoint on 'main' method. - //### Would be cleaner if we could just bring up VM already suspended. - if (suspended) { - //### Set breakpoint at 'main(java.lang.String[])'. - List argList = new ArrayList(1); - argList.add("java.lang.String[]"); - createMethodBreakpoint(className, "main", argList); - } - - String cmdLine = className + " " + args; - - startSession(new ChildSession(this, vmArgs, cmdLine, - appInput, appOutput, appError, - diagnostics)); - } - - /* - * Attach to an existing VM. - */ - public void attach(String portName) throws VMLaunchFailureException { - endSession(); - - //### Changes made here for connectors have broken the - //### the 'Session' abstraction. The 'Session.attach()' - //### method is intended to encapsulate all of the various - //### ways in which session start-up can fail. (maddox 12/18/98) - - /* - * Now that attaches and launches both go through Connectors, - * it may be worth creating a new subclass of Session for - * attach sessions. - */ - VirtualMachineManager mgr = Bootstrap.virtualMachineManager(); - AttachingConnector connector = mgr.attachingConnectors().get(0); - Map arguments = connector.defaultArguments(); - arguments.get("port").setValue(portName); - - Session newSession = internalAttach(connector, arguments); - if (newSession != null) { - startSession(newSession); - } - } - - private Session internalAttach(AttachingConnector connector, - Map arguments) { - try { - VirtualMachine vm = connector.attach(arguments); - return new Session(vm, this, diagnostics); - } catch (IOException ioe) { - diagnostics.putString("\n Unable to attach to target VM: " + - ioe.getMessage()); - } catch (IllegalConnectorArgumentsException icae) { - diagnostics.putString("\n Invalid connector arguments: " + - icae.getMessage()); - } - return null; - } - - private Session internalListen(ListeningConnector connector, - Map arguments) { - try { - VirtualMachine vm = connector.accept(arguments); - return new Session(vm, this, diagnostics); - } catch (IOException ioe) { - diagnostics.putString( - "\n Unable to accept connection to target VM: " + - ioe.getMessage()); - } catch (IllegalConnectorArgumentsException icae) { - diagnostics.putString("\n Invalid connector arguments: " + - icae.getMessage()); - } - return null; - } - - /* - * Connect via user specified arguments - * @return true on success - */ - public boolean explictStart(Connector connector, Map arguments) - throws VMLaunchFailureException { - Session newSession = null; - - endSession(); - - if (connector instanceof LaunchingConnector) { - // we were launched, use ChildSession - newSession = new ChildSession(this, (LaunchingConnector)connector, - arguments, - appInput, appOutput, appError, - diagnostics); - } else if (connector instanceof AttachingConnector) { - newSession = internalAttach((AttachingConnector)connector, - arguments); - } else if (connector instanceof ListeningConnector) { - newSession = internalListen((ListeningConnector)connector, - arguments); - } else { - diagnostics.putString("\n Unknown connector: " + connector); - } - if (newSession != null) { - startSession(newSession); - } - return newSession != null; - } - - /* - * Detach from VM. If VM was started by debugger, terminate it. - */ - public void detach() throws NoSessionException { - ensureActiveSession(); - endSession(); - } - - private void startSession(Session s) throws VMLaunchFailureException { - if (!s.attach()) { - throw new VMLaunchFailureException(); - } - session = s; - EventRequestManager em = vm().eventRequestManager(); - ClassPrepareRequest classPrepareRequest = em.createClassPrepareRequest(); - //### We must allow the deferred breakpoints to be resolved before - //### we continue executing the class. We could optimize if there - //### were no deferred breakpoints outstanding for a particular class. - //### Can we do this with JDI? - classPrepareRequest.setSuspendPolicy(EventRequest.SUSPEND_ALL); - classPrepareRequest.enable(); - ClassUnloadRequest classUnloadRequest = em.createClassUnloadRequest(); - classUnloadRequest.setSuspendPolicy(EventRequest.SUSPEND_NONE); - classUnloadRequest.enable(); - ThreadStartRequest threadStartRequest = em.createThreadStartRequest(); - threadStartRequest.setSuspendPolicy(EventRequest.SUSPEND_NONE); - threadStartRequest.enable(); - ThreadDeathRequest threadDeathRequest = em.createThreadDeathRequest(); - threadDeathRequest.setSuspendPolicy(EventRequest.SUSPEND_NONE); - threadDeathRequest.enable(); - ExceptionRequest exceptionRequest = - em.createExceptionRequest(null, false, true); - exceptionRequest.setSuspendPolicy(EventRequest.SUSPEND_ALL); - exceptionRequest.enable(); - validateThreadInfo(); - session.interrupted = true; - notifySessionStart(); - } - - void endSession() { - if (session != null) { - session.detach(); - session = null; - invalidateThreadInfo(); - notifySessionDeath(); - } - } - - /* - * Suspend all VM activity. - */ - - public void interrupt() throws NoSessionException { - ensureActiveSession(); - vm().suspend(); - //### Is it guaranteed that the interrupt has happened? - validateThreadInfo(); - session.interrupted = true; - notifyInterrupted(); - } - - /* - * Resume interrupted VM. - */ - - public void go() throws NoSessionException, VMNotInterruptedException { - ensureActiveSession(); - invalidateThreadInfo(); - session.interrupted = false; - notifyContinued(); - vm().resume(); - } - - /* - * Stepping. - */ - void clearPreviousStep(ThreadReference thread) { - /* - * A previous step may not have completed on this thread; - * if so, it gets removed here. - */ - EventRequestManager mgr = vm().eventRequestManager(); - for (StepRequest request : mgr.stepRequests()) { - if (request.thread().equals(thread)) { - mgr.deleteEventRequest(request); - break; - } - } - } - - private void generalStep(ThreadReference thread, int size, int depth) - throws NoSessionException { - ensureActiveSession(); - invalidateThreadInfo(); - session.interrupted = false; - notifyContinued(); - - clearPreviousStep(thread); - EventRequestManager reqMgr = vm().eventRequestManager(); - StepRequest request = reqMgr.createStepRequest(thread, - size, depth); - // We want just the next step event and no others - request.addCountFilter(1); - request.enable(); - vm().resume(); - } - - public void stepIntoInstruction(ThreadReference thread) - throws NoSessionException { - generalStep(thread, StepRequest.STEP_MIN, StepRequest.STEP_INTO); - } - - public void stepOverInstruction(ThreadReference thread) - throws NoSessionException { - generalStep(thread, StepRequest.STEP_MIN, StepRequest.STEP_OVER); - } - - public void stepIntoLine(ThreadReference thread) - throws NoSessionException, - AbsentInformationException { - generalStep(thread, StepRequest.STEP_LINE, StepRequest.STEP_INTO); - } - - public void stepOverLine(ThreadReference thread) - throws NoSessionException, - AbsentInformationException { - generalStep(thread, StepRequest.STEP_LINE, StepRequest.STEP_OVER); - } - - public void stepOut(ThreadReference thread) - throws NoSessionException { - generalStep(thread, StepRequest.STEP_MIN, StepRequest.STEP_OUT); - } - - /* - * Thread control. - */ - - public void suspendThread(ThreadReference thread) throws NoSessionException { - ensureActiveSession(); - thread.suspend(); - } - - public void resumeThread(ThreadReference thread) throws NoSessionException { - ensureActiveSession(); - thread.resume(); - } - - public void stopThread(ThreadReference thread) throws NoSessionException { - ensureActiveSession(); - //### Need an exception now. Which one to use? - //thread.stop(); - } - - /* - * ThreadInfo objects -- Allow query of thread status and stack. - */ - - private List threadInfoList = new LinkedList(); - //### Should be weak! (in the value, not the key) - private HashMap threadInfoMap = new HashMap(); - - public ThreadInfo threadInfo(ThreadReference thread) { - if (session == null || thread == null) { - return null; - } - ThreadInfo info = threadInfoMap.get(thread); - if (info == null) { - //### Should not hardcode initial frame count and prefetch here! - //info = new ThreadInfo(thread, 10, 10); - info = new ThreadInfo(thread); - if (session.interrupted) { - info.validate(); - } - threadInfoList.add(info); - threadInfoMap.put(thread, info); - } - return info; - } - - void validateThreadInfo() { - session.interrupted = true; - for (ThreadInfo threadInfo : threadInfoList) { - threadInfo.validate(); - } - } - - private void invalidateThreadInfo() { - if (session != null) { - session.interrupted = false; - for (ThreadInfo threadInfo : threadInfoList) { - threadInfo.invalidate(); - } - } - } - - void removeThreadInfo(ThreadReference thread) { - ThreadInfo info = threadInfoMap.get(thread); - if (info != null) { - info.invalidate(); - threadInfoMap.remove(thread); - threadInfoList.remove(info); - } - } - - /* - * Listen for Session control events. - */ - - private void notifyInterrupted() { - ArrayList l = new ArrayList(sessionListeners); - EventObject evt = new EventObject(this); - for (int i = 0; i < l.size(); i++) { - l.get(i).sessionInterrupt(evt); - } - } - - private void notifyContinued() { - ArrayList l = new ArrayList(sessionListeners); - EventObject evt = new EventObject(this); - for (int i = 0; i < l.size(); i++) { - l.get(i).sessionContinue(evt); - } - } - - private void notifySessionStart() { - ArrayList l = new ArrayList(sessionListeners); - EventObject evt = new EventObject(this); - for (int i = 0; i < l.size(); i++) { - l.get(i).sessionStart(evt); - } - } - - private void notifySessionDeath() { -/*** noop for now - ArrayList l = new ArrayList(sessionListeners); - EventObject evt = new EventObject(this); - for (int i = 0; i < l.size(); i++) { - ((SessionListener)l.get(i)).sessionDeath(evt); - } -****/ - } - - /* - * Listen for input and output requests from the application - * being debugged. These are generated only when the debuggee - * is spawned as a child of the debugger. - */ - - private Object inputLock = new Object(); - private LinkedList inputBuffer = new LinkedList(); - - private void resetInputBuffer() { - synchronized (inputLock) { - inputBuffer = new LinkedList(); - } - } - - public void sendLineToApplication(String line) { - synchronized (inputLock) { - inputBuffer.addFirst(line); - inputLock.notifyAll(); - } - } - - private InputListener appInput = new InputListener() { - @Override - public String getLine() { - // Don't allow reader to be interrupted -- catch and retry. - String line = null; - while (line == null) { - synchronized (inputLock) { - try { - while (inputBuffer.size() < 1) { - inputLock.wait(); - } - line = inputBuffer.removeLast(); - } catch (InterruptedException e) {} - } - } - // We must not be holding inputLock here, as the listener - // that we call to echo a line might call us re-entrantly - // to provide another line of input. - // Run in Swing event dispatcher thread. - final String input = line; - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - echoInputLine(input); - } - }); - return line; - } - }; - - private static String newline = System.getProperty("line.separator"); - - private void echoInputLine(String line) { - ArrayList l = new ArrayList(appEchoListeners); - for (int i = 0; i < l.size(); i++) { - OutputListener ol = l.get(i); - ol.putString(line); - ol.putString(newline); - } - } - - private OutputListener appOutput = new OutputListener() { - @Override - public void putString(String string) { - ArrayList l = new ArrayList(appEchoListeners); - for (int i = 0; i < l.size(); i++) { - l.get(i).putString(string); - } - } - }; - - private OutputListener appError = new OutputListener() { - @Override - public void putString(String string) { - ArrayList l = new ArrayList(appEchoListeners); - for (int i = 0; i < l.size(); i++) { - l.get(i).putString(string); - } - } - }; - - private OutputListener diagnostics = new OutputListener() { - @Override - public void putString(String string) { - ArrayList l = new ArrayList(diagnosticsListeners); - for (int i = 0; i < l.size(); i++) { - l.get(i).putString(string); - } - } - }; - - ///////////// Spec Request Creation/Deletion/Query /////////// - - private EventRequestSpecList specList = new EventRequestSpecList(this); - - public BreakpointSpec - createSourceLineBreakpoint(String sourceName, int line) { - return specList.createSourceLineBreakpoint(sourceName, line); - } - - public BreakpointSpec - createClassLineBreakpoint(String classPattern, int line) { - return specList.createClassLineBreakpoint(classPattern, line); - } - - public BreakpointSpec - createMethodBreakpoint(String classPattern, - String methodId, List methodArgs) { - return specList.createMethodBreakpoint(classPattern, - methodId, methodArgs); - } - - public ExceptionSpec - createExceptionIntercept(String classPattern, - boolean notifyCaught, - boolean notifyUncaught) { - return specList.createExceptionIntercept(classPattern, - notifyCaught, - notifyUncaught); - } - - public AccessWatchpointSpec - createAccessWatchpoint(String classPattern, String fieldId) { - return specList.createAccessWatchpoint(classPattern, fieldId); - } - - public ModificationWatchpointSpec - createModificationWatchpoint(String classPattern, String fieldId) { - return specList.createModificationWatchpoint(classPattern, - fieldId); - } - - public void delete(EventRequestSpec spec) { - specList.delete(spec); - } - - void resolve(ReferenceType refType) { - specList.resolve(refType); - } - - public void install(EventRequestSpec spec) { - specList.install(spec, vm()); - } - - public List eventRequestSpecs() { - return specList.eventRequestSpecs(); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/FrameIndexOutOfBoundsException.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/FrameIndexOutOfBoundsException.java deleted file mode 100644 index 57d4e2a6d9c..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/FrameIndexOutOfBoundsException.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public class FrameIndexOutOfBoundsException extends IndexOutOfBoundsException { - - private static final long serialVersionUID = -4870148107027371437L; -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/InputListener.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/InputListener.java deleted file mode 100644 index 99a37c2e9f2..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/InputListener.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public interface InputListener { - String getLine(); -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/JDIEventSource.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/JDIEventSource.java deleted file mode 100644 index 2d92094d0d5..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/JDIEventSource.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; -import com.sun.jdi.event.*; - -import com.sun.tools.example.debug.event.*; - -import javax.swing.SwingUtilities; - -/** - */ -class JDIEventSource extends Thread { - - private /*final*/ EventQueue queue; - private /*final*/ Session session; - private /*final*/ ExecutionManager runtime; - private final JDIListener firstListener = new FirstListener(); - - private boolean wantInterrupt; //### Hack - - /** - * Create event source. - */ - JDIEventSource(Session session) { - super("JDI Event Set Dispatcher"); - this.session = session; - this.runtime = session.runtime; - this.queue = session.vm.eventQueue(); - } - - @Override - public void run() { - try { - runLoop(); - } catch (Exception exc) { - //### Do something different for InterruptedException??? - // just exit - } - session.running = false; - } - - private void runLoop() throws InterruptedException { - AbstractEventSet es; - do { - EventSet jdiEventSet = queue.remove(); - es = AbstractEventSet.toSpecificEventSet(jdiEventSet); - session.interrupted = es.suspendedAll(); - dispatchEventSet(es); - } while(!(es instanceof VMDisconnectEventSet)); - } - - //### Gross foul hackery! - private void dispatchEventSet(final AbstractEventSet es) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - boolean interrupted = es.suspendedAll(); - es.notify(firstListener); - boolean wantInterrupt = JDIEventSource.this.wantInterrupt; - for (JDIListener jl : session.runtime.jdiListeners) { - es.notify(jl); - } - if (interrupted && !wantInterrupt) { - session.interrupted = false; - //### Catch here is a hack - try { - session.vm.resume(); - } catch (VMDisconnectedException ee) {} - } - if (es instanceof ThreadDeathEventSet) { - ThreadReference t = ((ThreadDeathEventSet)es).getThread(); - session.runtime.removeThreadInfo(t); - } - } - }); - } - - private void finalizeEventSet(AbstractEventSet es) { - if (session.interrupted && !wantInterrupt) { - session.interrupted = false; - //### Catch here is a hack - try { - session.vm.resume(); - } catch (VMDisconnectedException ee) {} - } - if (es instanceof ThreadDeathEventSet) { - ThreadReference t = ((ThreadDeathEventSet)es).getThread(); - session.runtime.removeThreadInfo(t); - } - } - - //### This is a Hack, deal with it - private class FirstListener implements JDIListener { - - @Override - public void accessWatchpoint(AccessWatchpointEventSet e) { - session.runtime.validateThreadInfo(); - wantInterrupt = true; - } - - @Override - public void classPrepare(ClassPrepareEventSet e) { - wantInterrupt = false; - runtime.resolve(e.getReferenceType()); - } - - @Override - public void classUnload(ClassUnloadEventSet e) { - wantInterrupt = false; - } - - @Override - public void exception(ExceptionEventSet e) { - wantInterrupt = true; - } - - @Override - public void locationTrigger(LocationTriggerEventSet e) { - session.runtime.validateThreadInfo(); - wantInterrupt = true; - } - - @Override - public void modificationWatchpoint(ModificationWatchpointEventSet e) { - session.runtime.validateThreadInfo(); - wantInterrupt = true; - } - - @Override - public void threadDeath(ThreadDeathEventSet e) { - wantInterrupt = false; - } - - @Override - public void threadStart(ThreadStartEventSet e) { - wantInterrupt = false; - } - - @Override - public void vmDeath(VMDeathEventSet e) { - //### Should have some way to notify user - //### that VM died before the session ended. - wantInterrupt = false; - } - - @Override - public void vmDisconnect(VMDisconnectEventSet e) { - //### Notify user? - wantInterrupt = false; - session.runtime.endSession(); - } - - @Override - public void vmStart(VMStartEventSet e) { - //### Do we need to do anything with it? - wantInterrupt = false; - } - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/LineBreakpointSpec.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/LineBreakpointSpec.java deleted file mode 100644 index f7d66ce2d52..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/LineBreakpointSpec.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; -import java.util.List; - -public class LineBreakpointSpec extends BreakpointSpec { - int lineNumber; - - LineBreakpointSpec(EventRequestSpecList specs, - ReferenceTypeSpec refSpec, int lineNumber) { - super(specs, refSpec); - this.lineNumber = lineNumber; - } - - /** - * The 'refType' is known to match. - */ - @Override - void resolve(ReferenceType refType) throws InvalidTypeException, - LineNotFoundException { - if (!(refType instanceof ClassType)) { - throw new InvalidTypeException(); - } - Location location = location((ClassType)refType); - setRequest(refType.virtualMachine().eventRequestManager() - .createBreakpointRequest(location)); - } - - private Location location(ClassType clazz) throws - LineNotFoundException { - Location location = null; - try { - List locs = clazz.locationsOfLine(lineNumber()); - if (locs.size() == 0) { - throw new LineNotFoundException(); - } - // TODO handle multiple locations - location = locs.get(0); - if (location.method() == null) { - throw new LineNotFoundException(); - } - } catch (AbsentInformationException e) { - /* - * TO DO: throw something more specific, or allow - * AbsentInfo exception to pass through. - */ - throw new LineNotFoundException(); - } - return location; - } - - public int lineNumber() { - return lineNumber; - } - - @Override - public int hashCode() { - return refSpec.hashCode() + lineNumber; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof LineBreakpointSpec) { - LineBreakpointSpec breakpoint = (LineBreakpointSpec)obj; - - return refSpec.equals(breakpoint.refSpec) && - (lineNumber == breakpoint.lineNumber); - } else { - return false; - } - } - - @Override - public String errorMessageFor(Exception e) { - if (e instanceof LineNotFoundException) { - return ("No code at line " + lineNumber() + " in " + refSpec); - } else if (e instanceof InvalidTypeException) { - return ("Breakpoints can be located only in classes. " + - refSpec + " is an interface or array"); - } else { - return super.errorMessageFor( e); - } - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("breakpoint "); - sb.append(refSpec.toString()); - sb.append(':'); - sb.append(lineNumber); - sb.append(" ("); - sb.append(getStatusString()); - sb.append(')'); - return sb.toString(); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/LineNotFoundException.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/LineNotFoundException.java deleted file mode 100644 index 56b4ba3fa39..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/LineNotFoundException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public class LineNotFoundException extends Exception -{ - - private static final long serialVersionUID = -5630418117861587582L; - - public LineNotFoundException() - { - super(); - } - - public LineNotFoundException(String s) - { - super(s); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/MalformedMemberNameException.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/MalformedMemberNameException.java deleted file mode 100644 index 1980893a361..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/MalformedMemberNameException.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -class MalformedMemberNameException extends Exception { - - private static final long serialVersionUID = -7726664097374844485L; - - public MalformedMemberNameException() { - super(); - } - - public MalformedMemberNameException(String s) { - super(s); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/MethodBreakpointSpec.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/MethodBreakpointSpec.java deleted file mode 100644 index b414443faf7..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/MethodBreakpointSpec.java +++ /dev/null @@ -1,346 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; -import java.util.ArrayList; -import java.util.List; - -public class MethodBreakpointSpec extends BreakpointSpec { - String methodId; - List methodArgs; - - MethodBreakpointSpec(EventRequestSpecList specs, - ReferenceTypeSpec refSpec, - String methodId, List methodArgs) { - super(specs, refSpec); - this.methodId = methodId; - this.methodArgs = methodArgs; - } - - /** - * The 'refType' is known to match. - */ - @Override - void resolve(ReferenceType refType) throws MalformedMemberNameException, - AmbiguousMethodException, - InvalidTypeException, - NoSuchMethodException, - NoSessionException { - if (!isValidMethodName(methodId)) { - throw new MalformedMemberNameException(methodId); - } - if (!(refType instanceof ClassType)) { - throw new InvalidTypeException(); - } - Location location = location((ClassType)refType); - setRequest(refType.virtualMachine().eventRequestManager() - .createBreakpointRequest(location)); - } - - private Location location(ClassType clazz) throws - AmbiguousMethodException, - NoSuchMethodException, - NoSessionException { - Method method = findMatchingMethod(clazz); - Location location = method.location(); - return location; - } - - public String methodName() { - return methodId; - } - - public List methodArgs() { - return methodArgs; - } - - @Override - public int hashCode() { - return refSpec.hashCode() + - ((methodId != null) ? methodId.hashCode() : 0) + - ((methodArgs != null) ? methodArgs.hashCode() : 0); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof MethodBreakpointSpec) { - MethodBreakpointSpec breakpoint = (MethodBreakpointSpec)obj; - - return methodId.equals(breakpoint.methodId) && - methodArgs.equals(breakpoint.methodArgs) && - refSpec.equals(breakpoint.refSpec); - } else { - return false; - } - } - - @Override - public String errorMessageFor(Exception e) { - if (e instanceof AmbiguousMethodException) { - return ("Method " + methodName() + " is overloaded; specify arguments"); - /* - * TO DO: list the methods here - */ - } else if (e instanceof NoSuchMethodException) { - return ("No method " + methodName() + " in " + refSpec); - } else if (e instanceof InvalidTypeException) { - return ("Breakpoints can be located only in classes. " + - refSpec + " is an interface or array"); - } else { - return super.errorMessageFor( e); - } - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("breakpoint "); - sb.append(refSpec.toString()); - sb.append('.'); - sb.append(methodId); - if (methodArgs != null) { - boolean first = true; - sb.append('('); - for (String name : methodArgs) { - if (!first) { - sb.append(','); - } - sb.append(name); - first = false; - } - sb.append(")"); - } - sb.append(" ("); - sb.append(getStatusString()); - sb.append(')'); - return sb.toString(); - } - - private boolean isValidMethodName(String s) { - return isJavaIdentifier(s) || - s.equals("") || - s.equals(""); - } - - /* - * Compare a method's argument types with a Vector of type names. - * Return true if each argument type has a name identical to the - * corresponding string in the vector (allowing for varargs) - * and if the number of arguments in the method matches the - * number of names passed - */ - private boolean compareArgTypes(Method method, List nameList) { - List argTypeNames = method.argumentTypeNames(); - - // If argument counts differ, we can stop here - if (argTypeNames.size() != nameList.size()) { - return false; - } - - // Compare each argument type's name - int nTypes = argTypeNames.size(); - for (int i = 0; i < nTypes; ++i) { - String comp1 = argTypeNames.get(i); - String comp2 = nameList.get(i); - if (! comp1.equals(comp2)) { - /* - * We have to handle varargs. EG, the - * method's last arg type is xxx[] - * while the nameList contains xxx... - * Note that the nameList can also contain - * xxx[] in which case we don't get here. - */ - if (i != nTypes - 1 || - !method.isVarArgs() || - !comp2.endsWith("...")) { - return false; - } - /* - * The last types differ, it is a varargs - * method and the nameList item is varargs. - * We just have to compare the type names, eg, - * make sure we don't have xxx[] for the method - * arg type and yyy... for the nameList item. - */ - int comp1Length = comp1.length(); - if (comp1Length + 1 != comp2.length()) { - // The type names are different lengths - return false; - } - // We know the two type names are the same length - if (!comp1.regionMatches(0, comp2, 0, comp1Length - 2)) { - return false; - } - // We do have xxx[] and xxx... as the last param type - return true; - } - } - - return true; - } - - private VirtualMachine vm() { - return request.virtualMachine(); - } - - /** - * Remove unneeded spaces and expand class names to fully - * qualified names, if necessary and possible. - */ - private String normalizeArgTypeName(String name) throws NoSessionException { - /* - * Separate the type name from any array modifiers, - * stripping whitespace after the name ends. - */ - int i = 0; - StringBuilder typePart = new StringBuilder(); - StringBuilder arrayPart = new StringBuilder(); - name = name.trim(); - int nameLength = name.length(); - /* - * For varargs, there can be spaces before the ... but not - * within the ... So, we will just ignore the ... - * while stripping blanks. - */ - boolean isVarArgs = name.endsWith("..."); - if (isVarArgs) { - nameLength -= 3; - } - - while (i < nameLength) { - char c = name.charAt(i); - if (Character.isWhitespace(c) || c == '[') { - break; // name is complete - } - typePart.append(c); - i++; - } - while (i < nameLength) { - char c = name.charAt(i); - if ( (c == '[') || (c == ']')) { - arrayPart.append(c); - } else if (!Character.isWhitespace(c)) { - throw new IllegalArgumentException( - "Invalid argument type name"); - - } - i++; - } - - name = typePart.toString(); - - /* - * When there's no sign of a package name already, - * try to expand the - * the name to a fully qualified class name - */ - if ((name.indexOf('.') == -1) || name.startsWith("*.")) { - try { - List refs = specs.runtime.findClassesMatchingPattern(name); - if (refs.size() > 0) { //### ambiguity??? - name = ((ReferenceType)(refs.get(0))).name(); - } - } catch (IllegalArgumentException e) { - // We'll try the name as is - } - } - name += arrayPart.toString(); - if (isVarArgs) { - name += "..."; - } - return name; - } - - /* - * Attempt an unambiguous match of the method name and - * argument specification to a method. If no arguments - * are specified, the method must not be overloaded. - * Otherwise, the argument types much match exactly - */ - private Method findMatchingMethod(ClassType clazz) - throws AmbiguousMethodException, - NoSuchMethodException, - NoSessionException { - - // Normalize the argument string once before looping below. - List argTypeNames = null; - if (methodArgs() != null) { - argTypeNames = new ArrayList(methodArgs().size()); - for (String name : methodArgs()) { - name = normalizeArgTypeName(name); - argTypeNames.add(name); - } - } - - // Check each method in the class for matches - Method firstMatch = null; // first method with matching name - Method exactMatch = null; // (only) method with same name & sig - int matchCount = 0; // > 1 implies overload - for (Method candidate : clazz.methods()) { - if (candidate.name().equals(methodName())) { - matchCount++; - - // Remember the first match in case it is the only one - if (matchCount == 1) { - firstMatch = candidate; - } - - // If argument types were specified, check against candidate - if ((argTypeNames != null) - && compareArgTypes(candidate, argTypeNames) == true) { - exactMatch = candidate; - break; - } - } - } - - // Determine method for breakpoint - Method method = null; - if (exactMatch != null) { - // Name and signature match - method = exactMatch; - } else if ((argTypeNames == null) && (matchCount > 0)) { - // At least one name matched and no arg types were specified - if (matchCount == 1) { - method = firstMatch; // Only one match; safe to use it - } else { - throw new AmbiguousMethodException(); - } - } else { - throw new NoSuchMethodException(methodName()); - } - return method; - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/MethodNotFoundException.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/MethodNotFoundException.java deleted file mode 100644 index 820c35cc61b..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/MethodNotFoundException.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public class MethodNotFoundException extends Exception -{ - private static final long serialVersionUID = -2064968107599632609L; - - public MethodNotFoundException() - { - super(); - } - - public MethodNotFoundException(String s) - { - super(s); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ModificationWatchpointSpec.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ModificationWatchpointSpec.java deleted file mode 100644 index b8f2b86e65a..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ModificationWatchpointSpec.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; - -public class ModificationWatchpointSpec extends WatchpointSpec { - - ModificationWatchpointSpec(EventRequestSpecList specs, - ReferenceTypeSpec refSpec, String fieldId) { - super(specs, refSpec, fieldId); - } - - /** - * The 'refType' is known to match. - */ - @Override - void resolve(ReferenceType refType) throws InvalidTypeException, - NoSuchFieldException { - if (!(refType instanceof ClassType)) { - throw new InvalidTypeException(); - } - Field field = refType.fieldByName(fieldId); - if (field == null) { - throw new NoSuchFieldException(fieldId); - } - setRequest(refType.virtualMachine().eventRequestManager() - .createModificationWatchpointRequest(field)); - } - - @Override - public boolean equals(Object obj) { - return (obj instanceof ModificationWatchpointSpec) && - super.equals(obj); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/NoSessionException.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/NoSessionException.java deleted file mode 100644 index 3e92e2eb167..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/NoSessionException.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public class NoSessionException extends Exception { - - private static final long serialVersionUID = -7324357828115128603L; -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/NoThreadException.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/NoThreadException.java deleted file mode 100644 index 12512094f4d..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/NoThreadException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public class NoThreadException extends Exception { - - private static final long serialVersionUID = 1846613539928921998L; - -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/OutputListener.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/OutputListener.java deleted file mode 100644 index 8bb6701595e..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/OutputListener.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public interface OutputListener { - void putString(String str); - //void putLine(String line); -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ParseException.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ParseException.java deleted file mode 100644 index 3d407985635..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ParseException.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -// dummy placeholder for javaCC-generated code. - -public class ParseException extends Exception {} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/PatternReferenceTypeSpec.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/PatternReferenceTypeSpec.java deleted file mode 100644 index fa034aea3b4..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/PatternReferenceTypeSpec.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; -import java.util.StringTokenizer; - -class PatternReferenceTypeSpec implements ReferenceTypeSpec { - final boolean isWild; - final String classId; - - PatternReferenceTypeSpec(String classId) -// throws ClassNotFoundException - { -// checkClassName(classId); - isWild = classId.startsWith("*."); - if (isWild) { - this.classId = classId.substring(1); - } else { - this.classId = classId; - } - } - - /** - * Does the specified ReferenceType match this spec. - */ - @Override - public boolean matches(ReferenceType refType) { - if (isWild) { - return refType.name().endsWith(classId); - } else { - return refType.name().equals(classId); - } - } - - @Override - public int hashCode() { - return classId.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof PatternReferenceTypeSpec) { - PatternReferenceTypeSpec spec = (PatternReferenceTypeSpec)obj; - - return classId.equals(spec.classId) && (isWild == spec.isWild); - } else { - return false; - } - } - - private void checkClassName(String className) throws ClassNotFoundException { - // Do stricter checking of class name validity on deferred - // because if the name is invalid, it will - // never match a future loaded class, and we'll be silent - // about it. - StringTokenizer tokenizer = new StringTokenizer(className, "."); - boolean first = true; - while (tokenizer.hasMoreTokens()) { - String token = tokenizer.nextToken(); - // Each dot-separated piece must be a valid identifier - // and the first token can also be "*". (Note that - // numeric class ids are not permitted. They must - // match a loaded class.) - if (!Utils.isJavaIdentifier(token) && !(first && token.equals("*"))) { - throw new ClassNotFoundException(); - } - first = false; - } - } - - @Override - public String toString() { - return isWild? "*" + classId : classId; - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ReferenceTypeSpec.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ReferenceTypeSpec.java deleted file mode 100644 index 7ad277e341f..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ReferenceTypeSpec.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; - -interface ReferenceTypeSpec { - /** - * Does the specified ReferenceType match this spec. - */ - boolean matches(ReferenceType refType); - - @Override - int hashCode(); - - @Override - boolean equals(Object obj); -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/Session.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/Session.java deleted file mode 100644 index 883834a07a1..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/Session.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.VirtualMachine; -import com.sun.jdi.VMDisconnectedException; - -/** - * Our repository of what we know about the state of one - * running VM. - */ -class Session { - - final VirtualMachine vm; - final ExecutionManager runtime; - final OutputListener diagnostics; - - boolean running = true; // Set false by JDIEventSource - boolean interrupted = false; // Set false by JDIEventSource - - private JDIEventSource eventSourceThread = null; - private int traceFlags; - private boolean dead = false; - - public Session(VirtualMachine vm, ExecutionManager runtime, - OutputListener diagnostics) { - this.vm = vm; - this.runtime = runtime; - this.diagnostics = diagnostics; - this.traceFlags = VirtualMachine.TRACE_NONE; - } - - /** - * Determine if VM is interrupted, i.e, present and not running. - */ - public boolean isInterrupted() { - return interrupted; - } - - public void setTraceMode(int traceFlags) { - this.traceFlags = traceFlags; - if (!dead) { - vm.setDebugTraceMode(traceFlags); - } - } - - public boolean attach() { - vm.setDebugTraceMode(traceFlags); - diagnostics.putString("Connected to VM"); - eventSourceThread = new JDIEventSource(this); - eventSourceThread.start(); - return true; - } - - public void detach() { - if (!dead) { - eventSourceThread.interrupt(); - eventSourceThread = null; - //### The VM may already be disconnected - //### if the debuggee did a System.exit(). - //### Exception handler here is a kludge, - //### Rather, there are many other places - //### where we need to handle this exception, - //### and initiate a detach due to an error - //### condition, e.g., connection failure. - try { - vm.dispose(); - } catch (VMDisconnectedException ee) {} - dead = true; - diagnostics.putString("Disconnected from VM"); - } - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SessionListener.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SessionListener.java deleted file mode 100644 index e13c4d70e72..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SessionListener.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import java.util.EventObject; -import java.util.EventListener; - -public interface SessionListener extends EventListener { - - void sessionStart(EventObject e); - - void sessionInterrupt(EventObject e); - void sessionContinue(EventObject e); -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SourceNameReferenceTypeSpec.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SourceNameReferenceTypeSpec.java deleted file mode 100644 index 36061bfc487..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SourceNameReferenceTypeSpec.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; - -class SourceNameReferenceTypeSpec implements ReferenceTypeSpec { - final String sourceName; - final int linenumber; - - SourceNameReferenceTypeSpec(String sourceName, int linenumber) { - this.sourceName = sourceName; - this.linenumber = linenumber; - } - - /** - * Does the specified ReferenceType match this spec. - */ - @Override - public boolean matches(ReferenceType refType) { - try { - if (refType.sourceName().equals(sourceName)) { - try { - refType.locationsOfLine(linenumber); - // if we don't throw an exception then it was found - return true; - } catch(AbsentInformationException exc) { - } catch(ObjectCollectedException exc) { - } - } - } catch(AbsentInformationException exc) { - // for sourceName(), fall through - } - return false; - } - - @Override - public int hashCode() { - return sourceName.hashCode() + linenumber; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof SourceNameReferenceTypeSpec) { - SourceNameReferenceTypeSpec spec = (SourceNameReferenceTypeSpec)obj; - - return sourceName.equals(spec.sourceName) && - (linenumber == spec.linenumber); - } else { - return false; - } - } - - @Override - public String toString() { - return sourceName + "@" + linenumber; - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SpecErrorEvent.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SpecErrorEvent.java deleted file mode 100644 index baab1291d2d..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SpecErrorEvent.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public class SpecErrorEvent extends SpecEvent { - - private static final long serialVersionUID = 8162634387866409578L; - private Exception reason; - - public SpecErrorEvent(EventRequestSpec eventRequestSpec, - Exception reason) { - super(eventRequestSpec); - this.reason = reason; - } - - public Exception getReason() { - return reason; - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SpecEvent.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SpecEvent.java deleted file mode 100644 index 7a321ef4aaa..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SpecEvent.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import java.util.EventObject; - -import com.sun.jdi.request.EventRequest; - -public class SpecEvent extends EventObject { - - private static final long serialVersionUID = 4820735456787276230L; - private EventRequestSpec eventRequestSpec; - - public SpecEvent(EventRequestSpec eventRequestSpec) { - super(eventRequestSpec.specs); - this.eventRequestSpec = eventRequestSpec; - } - - public EventRequestSpec getEventRequestSpec() { - return eventRequestSpec; - } - - public EventRequest getEventRequest() { - return eventRequestSpec.getEventRequest(); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SpecListener.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SpecListener.java deleted file mode 100644 index 2e5df596ea4..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/SpecListener.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import java.util.EventListener; - -public interface SpecListener extends EventListener { - - void breakpointSet(SpecEvent e); - void breakpointDeferred(SpecEvent e); - void breakpointDeleted(SpecEvent e); - void breakpointResolved(SpecEvent e); - void breakpointError(SpecErrorEvent e); - - void watchpointSet(SpecEvent e); - void watchpointDeferred(SpecEvent e); - void watchpointDeleted(SpecEvent e); - void watchpointResolved(SpecEvent e); - void watchpointError(SpecErrorEvent e); - - void exceptionInterceptSet(SpecEvent e); - void exceptionInterceptDeferred(SpecEvent e); - void exceptionInterceptDeleted(SpecEvent e); - void exceptionInterceptResolved(SpecEvent e); - void exceptionInterceptError(SpecErrorEvent e); -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ThreadGroupIterator.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ThreadGroupIterator.java deleted file mode 100644 index dd8b0cb3f7e..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ThreadGroupIterator.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.ThreadGroupReference; -import java.util.List; -import java.util.Stack; -import java.util.ArrayList; -import java.util.Iterator; - -/** - * Descend the tree of thread groups. - * @author Robert G. Field - */ -public class ThreadGroupIterator implements Iterator { - private final Stack> stack - = new Stack>(); - - public ThreadGroupIterator(List tgl) { - push(tgl); - } - - public ThreadGroupIterator(ThreadGroupReference tg) { - List tgl = new ArrayList(); - tgl.add(tg); - push(tgl); - } - -/* - ThreadGroupIterator() { - this(Env.vm().topLevelThreadGroups()); - } -*/ - - private Iterator top() { - return stack.peek(); - } - - /** - * The invariant in this class is that the top iterator - * on the stack has more elements. If the stack is - * empty, there is no top. This method assures - * this invariant. - */ - private void push(List tgl) { - stack.push(tgl.iterator()); - while (!stack.isEmpty() && !top().hasNext()) { - stack.pop(); - } - } - - @Override - public boolean hasNext() { - return !stack.isEmpty(); - } - - @Override - public ThreadGroupReference next() { - return nextThreadGroup(); - } - - public ThreadGroupReference nextThreadGroup() { - ThreadGroupReference tg = top().next(); - push(tg.threadGroups()); - return tg; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - -/* - static ThreadGroupReference find(String name) { - ThreadGroupIterator tgi = new ThreadGroupIterator(); - while (tgi.hasNext()) { - ThreadGroupReference tg = tgi.nextThreadGroup(); - if (tg.name().equals(name)) { - return tg; - } - } - return null; - } -*/ -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ThreadInfo.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ThreadInfo.java deleted file mode 100644 index 02626ac324f..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ThreadInfo.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.*; - -//### Should handle target VM death or connection failure cleanly. - -public class ThreadInfo { - - private ThreadReference thread; - private int status; - - private int frameCount; - - Object userObject; // User-supplied annotation. - - private boolean interrupted = false; - - private void assureInterrupted() throws VMNotInterruptedException { - if (!interrupted) { - throw new VMNotInterruptedException(); - } - } - - ThreadInfo (ThreadReference thread) { - this.thread = thread; - this.frameCount = -1; - } - - public ThreadReference thread() { - return thread; - } - - public int getStatus() throws VMNotInterruptedException { - assureInterrupted(); - update(); - return status; - } - - public int getFrameCount() throws VMNotInterruptedException { - assureInterrupted(); - update(); - return frameCount; - } - - public StackFrame getFrame(int index) throws VMNotInterruptedException { - assureInterrupted(); - update(); - try { - return thread.frame(index); - } catch (IncompatibleThreadStateException e) { - // Should not happen - interrupted = false; - throw new VMNotInterruptedException(); - } - } - - public Object getUserObject() { - return userObject; - } - - public void setUserObject(Object obj) { - userObject = obj; - } - - // Refresh upon first access after cache is cleared. - - void update() throws VMNotInterruptedException { - if (frameCount == -1) { - try { - status = thread.status(); - frameCount = thread.frameCount(); - } catch (IncompatibleThreadStateException e) { - // Should not happen - interrupted = false; - throw new VMNotInterruptedException(); - } - } - } - - // Called from 'ExecutionManager'. - - void validate() { - interrupted = true; - } - - void invalidate() { - interrupted = false; - frameCount = -1; - status = ThreadReference.THREAD_STATUS_UNKNOWN; - } - -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ThreadIterator.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ThreadIterator.java deleted file mode 100644 index b82d88e6e1e..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/ThreadIterator.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -import com.sun.jdi.ThreadGroupReference; -import com.sun.jdi.ThreadReference; -import java.util.List; -import java.util.Iterator; - -public class ThreadIterator implements Iterator { - Iterator it = null; - ThreadGroupIterator tgi; - - public ThreadIterator(ThreadGroupReference tg) { - tgi = new ThreadGroupIterator(tg); - } - - //### make this package access only? - public ThreadIterator(List tgl) { - tgi = new ThreadGroupIterator(tgl); - } - - @Override - public boolean hasNext() { - while (it == null || !it.hasNext()) { - if (!tgi.hasNext()) { - return false; // no more - } - it = tgi.nextThreadGroup().threads().iterator(); - } - return true; - } - - @Override - public ThreadReference next() { - return it.next(); - } - - public ThreadReference nextThread() { - return next(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/Utils.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/Utils.java deleted file mode 100644 index 34f1d724929..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/Utils.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; //### does it belong here? - -import com.sun.jdi.*; - -public class Utils { - - /** - * Return the thread status description. - */ - public static String getStatus(ThreadReference thr) { - int status = thr.status(); - String result; - switch (status) { - case ThreadReference.THREAD_STATUS_UNKNOWN: - result = "unknown status"; - break; - case ThreadReference.THREAD_STATUS_ZOMBIE: - result = "zombie"; - break; - case ThreadReference.THREAD_STATUS_RUNNING: - result = "running"; - break; - case ThreadReference.THREAD_STATUS_SLEEPING: - result = "sleeping"; - break; - case ThreadReference.THREAD_STATUS_MONITOR: - result = "waiting to acquire a monitor lock"; - break; - case ThreadReference.THREAD_STATUS_WAIT: - result = "waiting on a condition"; - break; - default: - result = ""; - } - if (thr.isSuspended()) { - result += " (suspended)"; - } - return result; - } - - /** - * Return a description of an object. - */ - public static String description(ObjectReference ref) { - ReferenceType clazz = ref.referenceType(); - long id = ref.uniqueID(); //### TODO use real id - if (clazz == null) { - return toHex(id); - } else { - return "(" + clazz.name() + ")" + toHex(id); - } - } - - /** - * Convert a long to a hexadecimal string. - */ - public static String toHex(long n) { - char s1[] = new char[16]; - char s2[] = new char[18]; - - // Store digits in reverse order. - int i = 0; - do { - long d = n & 0xf; - s1[i++] = (char)((d < 10) ? ('0' + d) : ('a' + d - 10)); - } while ((n >>>= 4) > 0); - - // Now reverse the array. - s2[0] = '0'; - s2[1] = 'x'; - int j = 2; - while (--i >= 0) { - s2[j++] = s1[i]; - } - return new String(s2, 0, j); - } - - /** - * Convert hexadecimal strings to longs. - */ - public static long fromHex(String hexStr) { - String str = hexStr.startsWith("0x") ? - hexStr.substring(2).toLowerCase() : hexStr.toLowerCase(); - if (hexStr.length() == 0) { - throw new NumberFormatException(); - } - - long ret = 0; - for (int i = 0; i < str.length(); i++) { - int c = str.charAt(i); - if (c >= '0' && c <= '9') { - ret = (ret * 16) + (c - '0'); - } else if (c >= 'a' && c <= 'f') { - ret = (ret * 16) + (c - 'a' + 10); - } else { - throw new NumberFormatException(); - } - } - return ret; - } - - - /* - * The next two methods are used by this class and by EventHandler - * to print consistent locations and error messages. - */ - public static String locationString(Location loc) { - return loc.declaringType().name() + - "." + loc.method().name() + "(), line=" + - loc.lineNumber(); - } - -//### UNUSED. -/************************ - private String typedName(Method method) { - // TO DO: Use method.signature() instead of method.arguments() so that - // we get sensible results for classes without debugging info - StringBuffer buf = new StringBuffer(); - buf.append(method.name()); - buf.append("("); - Iterator it = method.arguments().iterator(); - while (it.hasNext()) { - buf.append(((LocalVariable)it.next()).typeName()); - if (it.hasNext()) { - buf.append(","); - } - } - buf.append(")"); - return buf.toString(); - } -************************/ - - public static boolean isValidMethodName(String s) { - return isJavaIdentifier(s) || - s.equals("") || - s.equals(""); - } - - public static boolean isJavaIdentifier(String s) { - if (s.length() == 0) { - return false; - } - int cp = s.codePointAt(0); - if (! Character.isJavaIdentifierStart(cp)) { - return false; - } - for (int i = Character.charCount(cp); i < s.length(); i += Character.charCount(cp)) { - cp = s.codePointAt(i); - if (! Character.isJavaIdentifierPart(cp)) { - return false; - } - } - return true; - } - -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/VMLaunchFailureException.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/VMLaunchFailureException.java deleted file mode 100644 index c2429684d29..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/VMLaunchFailureException.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public class VMLaunchFailureException extends Exception { - - private static final long serialVersionUID = -2439646729274310108L; -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/VMNotInterruptedException.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/VMNotInterruptedException.java deleted file mode 100644 index 489d88086cb..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/VMNotInterruptedException.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public class VMNotInterruptedException extends Exception { - - private static final long serialVersionUID = 8111074582188765600L; -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/WatchpointSpec.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/WatchpointSpec.java deleted file mode 100644 index 367e38c7490..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/bdi/WatchpointSpec.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.bdi; - -public abstract class WatchpointSpec extends EventRequestSpec { - final String fieldId; - - WatchpointSpec(EventRequestSpecList specs, - ReferenceTypeSpec refSpec, String fieldId) { - super(specs, refSpec); - this.fieldId = fieldId; -// if (!isJavaIdentifier(fieldId)) { -// throw new MalformedMemberNameException(fieldId); -// } - } - - @Override - void notifySet(SpecListener listener, SpecEvent evt) { - listener.watchpointSet(evt); - } - - @Override - void notifyDeferred(SpecListener listener, SpecEvent evt) { - listener.watchpointDeferred(evt); - } - - @Override - void notifyResolved(SpecListener listener, SpecEvent evt) { - listener.watchpointResolved(evt); - } - - @Override - void notifyDeleted(SpecListener listener, SpecEvent evt) { - listener.watchpointDeleted(evt); - } - - @Override - void notifyError(SpecListener listener, SpecErrorEvent evt) { - listener.watchpointError(evt); - } - - @Override - public int hashCode() { - return refSpec.hashCode() + fieldId.hashCode() + - getClass().hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof WatchpointSpec) { - WatchpointSpec watchpoint = (WatchpointSpec)obj; - - return fieldId.equals(watchpoint.fieldId) && - refSpec.equals(watchpoint.refSpec) && - getClass().equals(watchpoint.getClass()); - } else { - return false; - } - } - - @Override - public String errorMessageFor(Exception e) { - if (e instanceof NoSuchFieldException) { - return ("No field " + fieldId + " in " + refSpec); - } else { - return super.errorMessageFor(e); - } - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/AbstractEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/AbstractEventSet.java deleted file mode 100644 index 0a82f15ee0a..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/AbstractEventSet.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.*; -import com.sun.jdi.event.*; -import com.sun.jdi.request.*; - -import java.util.*; - -public abstract class AbstractEventSet extends EventObject implements EventSet { - - private static final long serialVersionUID = 2772717574222076977L; - private final EventSet jdiEventSet; - final Event oneEvent; - - /** - */ - AbstractEventSet(EventSet jdiEventSet) { - super(jdiEventSet.virtualMachine()); - this.jdiEventSet = jdiEventSet; - this.oneEvent = eventIterator().nextEvent(); - } - - public static AbstractEventSet toSpecificEventSet(EventSet jdiEventSet) { - Event evt = jdiEventSet.eventIterator().nextEvent(); - if (evt instanceof LocatableEvent) { - if (evt instanceof ExceptionEvent) { - return new ExceptionEventSet(jdiEventSet); - } else if (evt instanceof WatchpointEvent) { - if (evt instanceof AccessWatchpointEvent) { - return new AccessWatchpointEventSet(jdiEventSet); - } else { - return new ModificationWatchpointEventSet(jdiEventSet); - } - } else { - return new LocationTriggerEventSet(jdiEventSet); - } - } else if (evt instanceof ClassPrepareEvent) { - return new ClassPrepareEventSet(jdiEventSet); - } else if (evt instanceof ClassUnloadEvent) { - return new ClassUnloadEventSet(jdiEventSet); - } else if (evt instanceof ThreadDeathEvent) { - return new ThreadDeathEventSet(jdiEventSet); - } else if (evt instanceof ThreadStartEvent) { - return new ThreadStartEventSet(jdiEventSet); - } else if (evt instanceof VMDeathEvent) { - return new VMDeathEventSet(jdiEventSet); - } else if (evt instanceof VMDisconnectEvent) { - return new VMDisconnectEventSet(jdiEventSet); - } else if (evt instanceof VMStartEvent) { - return new VMStartEventSet(jdiEventSet); - } else { - throw new IllegalArgumentException("Unknown event " + evt); - } - } - - public abstract void notify(JDIListener listener); - - // Implement Mirror - - @Override - public VirtualMachine virtualMachine() { - return jdiEventSet.virtualMachine(); - } - - public VirtualMachine getVirtualMachine() { - return jdiEventSet.virtualMachine(); - } - - // Implement EventSet - - /** - * Returns the policy used to suspend threads in the target VM - * for this event set. This policy is selected from the suspend - * policies for each event's request. The one that suspends the - * most threads is chosen when the event occurs in the target VM - * and that policy is returned here. See - * com.sun.jdi.request.EventRequest for the possible policy values. - * - * @return the integer suspendPolicy - */ - public int getSuspendPolicy() { - return jdiEventSet.suspendPolicy(); - } - - @Override - public void resume() { - jdiEventSet.resume(); - } - - @Override - public int suspendPolicy() { - return jdiEventSet.suspendPolicy(); - } - - public boolean suspendedAll() { - return jdiEventSet.suspendPolicy() == EventRequest.SUSPEND_ALL; - } - - public boolean suspendedEventThread() { - return jdiEventSet.suspendPolicy() == EventRequest.SUSPEND_EVENT_THREAD; - } - - public boolean suspendedNone() { - return jdiEventSet.suspendPolicy() == EventRequest.SUSPEND_NONE; - } - - /** - * Return an iterator specific to {@link Event} objects. - */ - @Override - public EventIterator eventIterator() { - return jdiEventSet.eventIterator(); - } - - - // Implement java.util.Set (by pass through) - - /** - * Returns the number of elements in this set (its cardinality). If this - * set contains more than Integer.MAX_VALUE elements, returns - * Integer.MAX_VALUE. - * - * @return the number of elements in this set (its cardinality). - */ - @Override - public int size() { - return jdiEventSet.size(); - } - - /** - * Returns true if this set contains no elements. - * - * @return true if this set contains no elements. - */ - @Override - public boolean isEmpty() { - return jdiEventSet.isEmpty(); - } - - /** - * Returns true if this set contains the specified element. More - * formally, returns true if and only if this set contains an - * element e such that (o==null ? e==null : - * o.equals(e)). - * - * @return true if this set contains the specified element. - */ - @Override - public boolean contains(Object o) { - return jdiEventSet.contains(o); - } - - /** - * Returns an iterator over the elements in this set. The elements are - * returned in no particular order (unless this set is an instance of some - * class that provides a guarantee). - * - * @return an iterator over the elements in this set. - */ - @Override - public Iterator iterator() { - return jdiEventSet.iterator(); - } - - /** - * Returns an array containing all of the elements in this set. - * Obeys the general contract of the Collection.toArray method. - * - * @return an array containing all of the elements in this set. - */ - @Override - public Object[] toArray() { - return jdiEventSet.toArray(); - } - - /** - * Returns an array containing all of the elements in this set whose - * runtime type is that of the specified array. Obeys the general - * contract of the Collection.toArray(Object[]) method. - * - * @param a the array into which the elements of this set are to - * be stored, if it is big enough { - return jdiEventSet.XXX(); - } otherwise, a new array of the - * same runtime type is allocated for this purpose. - * @return an array containing the elements of this set. - * @throws ArrayStoreException the runtime type of a is not a supertype - * of the runtime type of every element in this set. - */ - @Override - public T[] toArray(T a[]) { - return jdiEventSet.toArray(a); - } - - // Bulk Operations - - /** - * Returns true if this set contains all of the elements of the - * specified collection. If the specified collection is also a set, this - * method returns true if it is a subset of this set. - * - * @param c collection to be checked for containment in this set. - * @return true if this set contains all of the elements of the - * specified collection. - */ - @Override - public boolean containsAll(Collection c) { - return jdiEventSet.containsAll(c); - } - - - // Make the rest of Set unmodifiable - - @Override - public boolean add(Event e){ - throw new UnsupportedOperationException(); - } - @Override - public boolean remove(Object o) { - throw new UnsupportedOperationException(); - } - @Override - public boolean addAll(Collection coll) { - throw new UnsupportedOperationException(); - } - @Override - public boolean removeAll(Collection coll) { - throw new UnsupportedOperationException(); - } - @Override - public boolean retainAll(Collection coll) { - throw new UnsupportedOperationException(); - } - @Override - public void clear() { - throw new UnsupportedOperationException(); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/AccessWatchpointEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/AccessWatchpointEventSet.java deleted file mode 100644 index 10462e3bbb4..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/AccessWatchpointEventSet.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.event.*; - -public class AccessWatchpointEventSet extends WatchpointEventSet { - - private static final long serialVersionUID = -2620394219156607673L; - - AccessWatchpointEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - @Override - public void notify(JDIListener listener) { - listener.accessWatchpoint(this); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ClassPrepareEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ClassPrepareEventSet.java deleted file mode 100644 index 9010415e362..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ClassPrepareEventSet.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.*; -import com.sun.jdi.event.*; - -public class ClassPrepareEventSet extends AbstractEventSet { - - private static final long serialVersionUID = 5958493423581010491L; - - ClassPrepareEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - /** - * Returns the thread in which this event has occurred. - * - * @return a {@link ThreadReference} which mirrors the event's thread in - * the target VM. - */ - public ThreadReference getThread() { - return ((ClassPrepareEvent)oneEvent).thread(); - } - - - /** - * Returns the reference type for which this event was generated. - * - * @return a {@link ReferenceType} which mirrors the class, interface, or - * array which has been linked. - */ - public ReferenceType getReferenceType() { - return ((ClassPrepareEvent)oneEvent).referenceType(); - } - - @Override - public void notify(JDIListener listener) { - listener.classPrepare(this); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ClassUnloadEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ClassUnloadEventSet.java deleted file mode 100644 index ad57b70d059..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ClassUnloadEventSet.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.event.*; - -public class ClassUnloadEventSet extends AbstractEventSet { - - private static final long serialVersionUID = 8370341450345835866L; - - ClassUnloadEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - /** - * Returns the name of the class that has been unloaded. - */ - public String getClassName() { - return ((ClassUnloadEvent)oneEvent).className(); - } - - /** - * Returns the JNI-style signature of the class that has been unloaded. - */ - public String getClassSignature() { - return ((ClassUnloadEvent)oneEvent).classSignature(); - } - - @Override - public void notify(JDIListener listener) { - listener.classUnload(this); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ExceptionEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ExceptionEventSet.java deleted file mode 100644 index d59cce74d49..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ExceptionEventSet.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.*; -import com.sun.jdi.event.*; - -public class ExceptionEventSet extends LocatableEventSet { - - private static final long serialVersionUID = 5328140167954640711L; - - ExceptionEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - /** - * Gets the thrown exception object. The exception object is - * an instance of java.lang.Throwable or a subclass in the - * target VM. - * - * @return an {@link ObjectReference} which mirrors the thrown object in - * the target VM. - */ - public ObjectReference getException() { - return ((ExceptionEvent)oneEvent).exception(); - } - - /** - * Gets the location where the exception will be caught. An exception - * is considered to be caught if, at the point of the throw, the - * current location is dynamically enclosed in a try statement that - * handles the exception. (See the JVM specification for details). - * If there is such a try statement, the catch location is the - * first code index of the appropriate catch clause. - *

- * If there are native methods in the call stack at the time of the - * exception, there are important restrictions to note about the - * returned catch location. In such cases, - * it is not possible to predict whether an exception will be handled - * by some native method on the call stack. - * Thus, it is possible that exceptions considered uncaught - * here will, in fact, be handled by a native method and not cause - * termination of the target VM. Also, it cannot be assumed that the - * catch location returned here will ever be reached by the throwing - * thread. If there is - * a native frame between the current location and the catch location, - * the exception might be handled and cleared in that native method - * instead. - * - * @return the {@link Location} where the exception will be caught or null if - * the exception is uncaught. - */ - public Location getCatchLocation() { - return ((ExceptionEvent)oneEvent).catchLocation(); - } - - @Override - public void notify(JDIListener listener) { - listener.exception(this); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/JDIAdapter.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/JDIAdapter.java deleted file mode 100644 index 056cd0933b5..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/JDIAdapter.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -/** - * The adapter which receives JDI event sets. The methods in this - * class are empty; this class is provided as a convenience for - * easily creating listeners by extending this class and overriding - * only the methods of interest. - */ -public class JDIAdapter implements JDIListener { - - @Override - public void accessWatchpoint(AccessWatchpointEventSet e) { - } - - @Override - public void classPrepare(ClassPrepareEventSet e) { - } - - @Override - public void classUnload(ClassUnloadEventSet e) { - } - - @Override - public void exception(ExceptionEventSet e) { - } - - @Override - public void locationTrigger(LocationTriggerEventSet e) { - } - - @Override - public void modificationWatchpoint(ModificationWatchpointEventSet e) { - } - - @Override - public void threadDeath(ThreadDeathEventSet e) { - } - - @Override - public void threadStart(ThreadStartEventSet e) { - } - - @Override - public void vmDeath(VMDeathEventSet e) { - } - - @Override - public void vmDisconnect(VMDisconnectEventSet e) { - } - - @Override - public void vmStart(VMStartEventSet e) { - } - -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/JDIListener.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/JDIListener.java deleted file mode 100644 index 18a37261ee4..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/JDIListener.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import java.util.EventListener; - -public interface JDIListener extends EventListener { - void accessWatchpoint(AccessWatchpointEventSet e); - void classPrepare(ClassPrepareEventSet e); - void classUnload(ClassUnloadEventSet e); - void exception(ExceptionEventSet e); - void locationTrigger(LocationTriggerEventSet e); - void modificationWatchpoint(ModificationWatchpointEventSet e); - void threadDeath(ThreadDeathEventSet e); - void threadStart(ThreadStartEventSet e); - void vmDeath(VMDeathEventSet e); - void vmDisconnect(VMDisconnectEventSet e); - void vmStart(VMStartEventSet e); -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/LocatableEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/LocatableEventSet.java deleted file mode 100644 index 6b4f607009c..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/LocatableEventSet.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.*; -import com.sun.jdi.event.*; - -/** - * Abstract event set for events with location and thread. - */ -public abstract class LocatableEventSet extends AbstractEventSet { - - private static final long serialVersionUID = 1027131209997915620L; - - LocatableEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - /** - * Returns the {@link Location} of this mirror. Depending on context - * and on available debug information, this location will have - * varying precision. - * - * @return the {@link Location} of this mirror. - */ - public Location getLocation() { - return ((LocatableEvent)oneEvent).location(); - } - - /** - * Returns the thread in which this event has occurred. - * - * @return a {@link ThreadReference} which mirrors the event's thread in - * the target VM. - */ - public ThreadReference getThread() { - return ((LocatableEvent)oneEvent).thread(); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/LocationTriggerEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/LocationTriggerEventSet.java deleted file mode 100644 index 3d25a573883..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/LocationTriggerEventSet.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.event.*; - -public class LocationTriggerEventSet extends LocatableEventSet { - - private static final long serialVersionUID = -3674631710485872487L; - - LocationTriggerEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - @Override - public void notify(JDIListener listener) { - listener.locationTrigger(this); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ModificationWatchpointEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ModificationWatchpointEventSet.java deleted file mode 100644 index 41749efa705..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ModificationWatchpointEventSet.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.*; -import com.sun.jdi.event.*; - -public class ModificationWatchpointEventSet extends WatchpointEventSet { - - private static final long serialVersionUID = -680889300856154719L; - - ModificationWatchpointEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - /** - * Value that will be assigned to the field when the instruction - * completes. - */ - public Value getValueToBe() { - return ((ModificationWatchpointEvent)oneEvent).valueToBe(); - } - - @Override - public void notify(JDIListener listener) { - listener.modificationWatchpoint(this); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ThreadDeathEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ThreadDeathEventSet.java deleted file mode 100644 index 893ec73fa97..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ThreadDeathEventSet.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.*; -import com.sun.jdi.event.*; - -public class ThreadDeathEventSet extends AbstractEventSet { - - private static final long serialVersionUID = -8801604712308151331L; - - ThreadDeathEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - /** - * Returns the thread which is terminating. - * - * @return a {@link ThreadReference} which mirrors the event's thread in - * the target VM. - */ - public ThreadReference getThread() { - return ((ThreadDeathEvent)oneEvent).thread(); - } - - @Override - public void notify(JDIListener listener) { - listener.threadDeath(this); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ThreadStartEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ThreadStartEventSet.java deleted file mode 100644 index 657e9633c9c..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/ThreadStartEventSet.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.*; -import com.sun.jdi.event.*; - -public class ThreadStartEventSet extends AbstractEventSet { - - private static final long serialVersionUID = -3802096132294933502L; - - ThreadStartEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - /** - * Returns the thread which has started. - * - * @return a {@link ThreadReference} which mirrors the event's thread in - * the target VM. - */ - public ThreadReference getThread() { - return ((ThreadStartEvent)oneEvent).thread(); - } - - @Override - public void notify(JDIListener listener) { - listener.threadStart(this); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/VMDeathEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/VMDeathEventSet.java deleted file mode 100644 index b6f7eb31843..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/VMDeathEventSet.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.event.*; - -public class VMDeathEventSet extends AbstractEventSet { - - private static final long serialVersionUID = 1163097303940092229L; - - VMDeathEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - @Override - public void notify(JDIListener listener) { - listener.vmDeath(this); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/VMDisconnectEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/VMDisconnectEventSet.java deleted file mode 100644 index 5b7dc7953ac..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/VMDisconnectEventSet.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.event.*; - -public class VMDisconnectEventSet extends AbstractEventSet { - - private static final long serialVersionUID = 7968123152344675342L; - - VMDisconnectEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - @Override - public void notify(JDIListener listener) { - listener.vmDisconnect(this); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/VMStartEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/VMStartEventSet.java deleted file mode 100644 index f9381239fc8..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/VMStartEventSet.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.*; -import com.sun.jdi.event.*; - -public class VMStartEventSet extends AbstractEventSet { - - private static final long serialVersionUID = -3384957227835478191L; - - VMStartEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - /** - * Returns the initial thread of the VM which has started. - * - * @return a {@link ThreadReference} which mirrors the event's - * thread in the target VM. - */ - public ThreadReference getThread() { - return ((VMStartEvent)oneEvent).thread(); - } - - @Override - public void notify(JDIListener listener) { - listener.vmStart(this); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/WatchpointEventSet.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/WatchpointEventSet.java deleted file mode 100644 index 76be4acf1da..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/event/WatchpointEventSet.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 1999, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.event; - -import com.sun.jdi.*; -import com.sun.jdi.event.*; - -public abstract class WatchpointEventSet extends LocatableEventSet { - - private static final long serialVersionUID = 5606285209703845409L; - - WatchpointEventSet(EventSet jdiEventSet) { - super(jdiEventSet); - } - - /** - * Returns the field that is about to be accessed/modified. - * - * @return a {@link Field} which mirrors the field - * in the target VM. - */ - public Field getField() { - return ((WatchpointEvent)oneEvent).field(); - } - - /** - * Returns the object whose field is about to be accessed/modified. - * Return null is the access is to a static field. - * - * @return a {@link ObjectReference} which mirrors the event's - * object in the target VM. - */ - public ObjectReference getObject() { - return ((WatchpointEvent)oneEvent).object(); - } - - /** - * Current value of the field. - */ - public Value getValueCurrent() { - return ((WatchpointEvent)oneEvent).valueCurrent(); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ApplicationTool.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ApplicationTool.java deleted file mode 100644 index 717a5b9390e..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ApplicationTool.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.gui; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; - -import com.sun.tools.example.debug.bdi.*; - -public class ApplicationTool extends JPanel { - - private static final long serialVersionUID = 310966063293205714L; - - private ExecutionManager runtime; - - private TypeScript script; - - private static final String PROMPT = "Input:"; - - public ApplicationTool(Environment env) { - - super(new BorderLayout()); - - this.runtime = env.getExecutionManager(); - - this.script = new TypeScript(PROMPT, false); // No implicit echo. - this.add(script); - - script.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - runtime.sendLineToApplication(script.readln()); - } - }); - - runtime.addApplicationEchoListener(new TypeScriptOutputListener(script)); - runtime.addApplicationOutputListener(new TypeScriptOutputListener(script)); - runtime.addApplicationErrorListener(new TypeScriptOutputListener(script)); - - //### should clean up on exit! - - } - - /****** - public void setFont(Font f) { - script.setFont(f); - } - ******/ - -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ClassManager.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ClassManager.java deleted file mode 100644 index 6e347376769..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ClassManager.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.gui; - -public class ClassManager { - - // This class is provided primarily for symmetry with - // SourceManager. Currently, it does very little. - // If we add facilities in the future that require that - // class files be read outside of the VM, for example, to - // provide a disassembled view of a class for bytecode-level - // debugging, the required class file management will be done - // here. - - private SearchPath classPath; - - public ClassManager(Environment env) { - this.classPath = new SearchPath(""); - } - - public ClassManager(SearchPath classPath) { - this.classPath = classPath; - } - - /* - * Set path for access to class files. - */ - - public void setClassPath(SearchPath sp) { - classPath = sp; - } - - /* - * Get path for access to class files. - */ - - public SearchPath getClassPath() { - return classPath; - } - -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ClassTreeTool.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ClassTreeTool.java deleted file mode 100644 index 995c414854c..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ClassTreeTool.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.gui; - -import java.util.*; - -import javax.swing.*; -import javax.swing.tree.*; -import java.awt.*; -import java.awt.event.*; - -import com.sun.jdi.*; -import com.sun.tools.example.debug.event.*; -import com.sun.tools.example.debug.bdi.*; - -public class ClassTreeTool extends JPanel { - - private static final long serialVersionUID = 526178912591739259L; - - private Environment env; - - private ExecutionManager runtime; - private SourceManager sourceManager; - private ClassManager classManager; - - private JTree tree; - private DefaultTreeModel treeModel; - private ClassTreeNode root; -// private SearchPath sourcePath; - - private CommandInterpreter interpreter; - - private static String HEADING = "CLASSES"; - - public ClassTreeTool(Environment env) { - - super(new BorderLayout()); - - this.env = env; - this.runtime = env.getExecutionManager(); - this.sourceManager = env.getSourceManager(); - - this.interpreter = new CommandInterpreter(env); - - root = createClassTree(HEADING); - treeModel = new DefaultTreeModel(root); - - // Create a tree that allows one selection at a time. - - tree = new JTree(treeModel); - tree.setSelectionModel(new SingleLeafTreeSelectionModel()); - - /****** - // Listen for when the selection changes. - tree.addTreeSelectionListener(new TreeSelectionListener() { - public void valueChanged(TreeSelectionEvent e) { - ClassTreeNode node = (ClassTreeNode) - (e.getPath().getLastPathComponent()); - if (node != null) { - interpreter.executeCommand("view " + node.getReferenceTypeName()); - } - } - }); - ******/ - - MouseListener ml = new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - int selRow = tree.getRowForLocation(e.getX(), e.getY()); - TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); - if(selRow != -1) { - if(e.getClickCount() == 1) { - ClassTreeNode node = - (ClassTreeNode)selPath.getLastPathComponent(); - // If user clicks on leaf, select it, and issue 'view' command. - if (node.isLeaf()) { - tree.setSelectionPath(selPath); - interpreter.executeCommand("view " + node.getReferenceTypeName()); - } - } - } - } - }; - tree.addMouseListener(ml); - - JScrollPane treeView = new JScrollPane(tree); - add(treeView); - - // Create listener. - ClassTreeToolListener listener = new ClassTreeToolListener(); - runtime.addJDIListener(listener); - runtime.addSessionListener(listener); - - //### remove listeners on exit! - } - - private class ClassTreeToolListener extends JDIAdapter - implements JDIListener, SessionListener { - - // SessionListener - - @Override - public void sessionStart(EventObject e) { - // Get system classes and any others loaded before attaching. - try { - for (ReferenceType type : runtime.allClasses()) { - root.addClass(type); - } - } catch (VMDisconnectedException ee) { - // VM terminated unexpectedly. - } catch (NoSessionException ee) { - // Ignore. Should not happen. - } - } - - @Override - public void sessionInterrupt(EventObject e) {} - @Override - public void sessionContinue(EventObject e) {} - - // JDIListener - - @Override - public void classPrepare(ClassPrepareEventSet e) { - root.addClass(e.getReferenceType()); - } - - @Override - public void classUnload(ClassUnloadEventSet e) { - root.removeClass(e.getClassName()); - } - - @Override - public void vmDisconnect(VMDisconnectEventSet e) { - // Clear contents of this view. - root = createClassTree(HEADING); - treeModel = new DefaultTreeModel(root); - tree.setModel(treeModel); - } - } - - ClassTreeNode createClassTree(String label) { - return new ClassTreeNode(label, null); - } - - class ClassTreeNode extends DefaultMutableTreeNode { - - private String name; - private ReferenceType refTy; // null for package - - ClassTreeNode(String name, ReferenceType refTy) { - this.name = name; - this.refTy = refTy; - } - - @Override - public String toString() { - return name; - } - - public ReferenceType getReferenceType() { - return refTy; - } - - public String getReferenceTypeName() { - return refTy.name(); - } - - private boolean isPackage() { - return (refTy == null); - } - - @Override - public boolean isLeaf() { - return !isPackage(); - } - - public void addClass(ReferenceType refTy) { - addClass(refTy.name(), refTy); - } - - private void addClass(String className, ReferenceType refTy) { - if (className.equals("")) { - return; - } - int pos = className.indexOf('.'); - if (pos < 0) { - insertNode(className, refTy); - } else { - String head = className.substring(0, pos); - String tail = className.substring(pos + 1); - ClassTreeNode child = insertNode(head, null); - child.addClass(tail, refTy); - } - } - - private ClassTreeNode insertNode(String name, ReferenceType refTy) { - for (int i = 0; i < getChildCount(); i++) { - ClassTreeNode child = (ClassTreeNode)getChildAt(i); - int cmp = name.compareTo(child.toString()); - if (cmp == 0) { - // like-named node already exists - return child; - } else if (cmp < 0) { - // insert new node before the child - ClassTreeNode newChild = new ClassTreeNode(name, refTy); - treeModel.insertNodeInto(newChild, this, i); - return newChild; - } - } - // insert new node after last child - ClassTreeNode newChild = new ClassTreeNode(name, refTy); - treeModel.insertNodeInto(newChild, this, getChildCount()); - return newChild; - } - - public void removeClass(String className) { - if (className.equals("")) { - return; - } - int pos = className.indexOf('.'); - if (pos < 0) { - ClassTreeNode child = findNode(className); - if (!isPackage()) { - treeModel.removeNodeFromParent(child); - } - } else { - String head = className.substring(0, pos); - String tail = className.substring(pos + 1); - ClassTreeNode child = findNode(head); - child.removeClass(tail); - if (isPackage() && child.getChildCount() < 1) { - // Prune non-leaf nodes with no children. - treeModel.removeNodeFromParent(child); - } - } - } - - private ClassTreeNode findNode(String name) { - for (int i = 0; i < getChildCount(); i++) { - ClassTreeNode child = (ClassTreeNode)getChildAt(i); - int cmp = name.compareTo(child.toString()); - if (cmp == 0) { - return child; - } else if (cmp > 0) { - // not found, since children are sorted - return null; - } - } - return null; - } - - } - -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/CommandInterpreter.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/CommandInterpreter.java deleted file mode 100644 index fbff95b2703..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/CommandInterpreter.java +++ /dev/null @@ -1,1468 +0,0 @@ -/* - * Copyright (c) 1998, 2013, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.gui; - -import java.io.*; -import java.util.*; - -import com.sun.jdi.*; -import com.sun.tools.example.debug.bdi.*; - -public class CommandInterpreter { - - boolean echo; - - Environment env; - - private ContextManager context; - private ExecutionManager runtime; - private ClassManager classManager; - private SourceManager sourceManager; - - private OutputSink out; //### Hack! Should be local in each method used. - private String lastCommand = "help"; - - public CommandInterpreter(Environment env) { - this(env, true); - } - - public CommandInterpreter(Environment env, boolean echo) { - this.env = env; - this.echo = echo; - this.runtime = env.getExecutionManager(); - this.context = env.getContextManager(); - this.classManager = env.getClassManager(); - this.sourceManager = env.getSourceManager(); - } - - private ThreadReference[] threads = null; - - /* - * The numbering of threads is relative to the current set of threads, - * and may be affected by the creation and termination of new threads. - * Commands issued using such thread ids will only give reliable behavior - * relative to what was shown earlier in 'list' commands if the VM is interrupted. - * We need a better scheme. - */ - - private ThreadReference[] threads() throws NoSessionException { - if (threads == null) { - ThreadIterator ti = new ThreadIterator(getDefaultThreadGroup()); - List tlist = new ArrayList(); - while (ti.hasNext()) { - tlist.add(ti.nextThread()); - } - threads = tlist.toArray(new ThreadReference[tlist.size()]); - } - return threads; - } - - private ThreadReference findThread(String idToken) throws NoSessionException { - String id; - ThreadReference thread = null; - if (idToken.startsWith("t@")) { - id = idToken.substring(2); - } else { - id = idToken; - } - try { - ThreadReference[] threads = threads(); - long threadID = Long.parseLong(id, 16); - for (ThreadReference thread2 : threads) { - if (thread2.uniqueID() == threadID) { - thread = thread2; - break; - } - } - if (thread == null) { - //env.failure("No thread for id \"" + idToken + "\""); - env.failure("\"" + idToken + "\" is not a valid thread id."); - } - } catch (NumberFormatException e) { - env.error("Thread id \"" + idToken + "\" is ill-formed."); - thread = null; - } - return thread; - } - - private ThreadIterator allThreads() throws NoSessionException { - threads = null; - //### Why not use runtime.allThreads().iterator() ? - return new ThreadIterator(runtime.topLevelThreadGroups()); - } - - private ThreadIterator currentThreadGroupThreads() throws NoSessionException { - threads = null; - return new ThreadIterator(getDefaultThreadGroup()); - } - - private ThreadGroupIterator allThreadGroups() throws NoSessionException { - threads = null; - return new ThreadGroupIterator(runtime.topLevelThreadGroups()); - } - - private ThreadGroupReference defaultThreadGroup; - - private ThreadGroupReference getDefaultThreadGroup() throws NoSessionException { - if (defaultThreadGroup == null) { - defaultThreadGroup = runtime.systemThreadGroup(); - } - return defaultThreadGroup; - } - - private void setDefaultThreadGroup(ThreadGroupReference tg) { - defaultThreadGroup = tg; - } - - /* - * Command handlers. - */ - - // Command: classes - - private void commandClasses() throws NoSessionException { - OutputSink out = env.getOutputSink(); - //out.println("** classes list **"); - for (ReferenceType refType : runtime.allClasses()) { - out.println(refType.name()); - } - out.show(); - } - - - // Command: methods - - private void commandMethods(StringTokenizer t) throws NoSessionException { - if (!t.hasMoreTokens()) { - env.error("No class specified."); - return; - } - String idClass = t.nextToken(); - ReferenceType cls = findClass(idClass); - if (cls != null) { - List methods = cls.allMethods(); - OutputSink out = env.getOutputSink(); - for (int i = 0; i < methods.size(); i++) { - Method method = methods.get(i); - out.print(method.declaringType().name() + " " + - method.name() + "("); - Iterator it = method.argumentTypeNames().iterator(); - if (it.hasNext()) { - while (true) { - out.print(it.next()); - if (!it.hasNext()) { - break; - } - out.print(", "); - } - } - out.println(")"); - } - out.show(); - } else { - //### Should validate class name syntax. - env.failure("\"" + idClass + "\" is not a valid id or class name."); - } - } - - private ReferenceType findClass(String pattern) throws NoSessionException { - List results = runtime.findClassesMatchingPattern(pattern); - if (results.size() > 0) { - //### Should handle multiple results sensibly. - return results.get(0); - } - return null; - } - - // Command: threads - - private void commandThreads(StringTokenizer t) throws NoSessionException { - if (!t.hasMoreTokens()) { - OutputSink out = env.getOutputSink(); - printThreadGroup(out, getDefaultThreadGroup(), 0); - out.show(); - return; - } - String name = t.nextToken(); - ThreadGroupReference tg = findThreadGroup(name); - if (tg == null) { - env.failure(name + " is not a valid threadgroup name."); - } else { - OutputSink out = env.getOutputSink(); - printThreadGroup(out, tg, 0); - out.show(); - } - } - - private ThreadGroupReference findThreadGroup(String name) throws NoSessionException { - //### Issue: Uniqueness of thread group names is not enforced. - ThreadGroupIterator tgi = allThreadGroups(); - while (tgi.hasNext()) { - ThreadGroupReference tg = tgi.nextThreadGroup(); - if (tg.name().equals(name)) { - return tg; - } - } - return null; - } - - private int printThreadGroup(OutputSink out, ThreadGroupReference tg, int iThread) { - out.println("Group " + tg.name() + ":"); - List tlist = tg.threads(); - int maxId = 0; - int maxName = 0; - for (int i = 0 ; i < tlist.size() ; i++) { - ThreadReference thr = tlist.get(i); - int len = Utils.description(thr).length(); - if (len > maxId) { - maxId = len; - } - String name = thr.name(); - int iDot = name.lastIndexOf('.'); - if (iDot >= 0 && name.length() > iDot) { - name = name.substring(iDot + 1); - } - if (name.length() > maxName) { - maxName = name.length(); - } - } - String maxNumString = String.valueOf(iThread + tlist.size()); - int maxNumDigits = maxNumString.length(); - for (int i = 0 ; i < tlist.size() ; i++) { - ThreadReference thr = tlist.get(i); - char buf[] = new char[80]; - for (int j = 0; j < 79; j++) { - buf[j] = ' '; - } - buf[79] = '\0'; - StringBuilder sbOut = new StringBuilder(); - sbOut.append(buf); - - // Right-justify the thread number at start of output string - String numString = String.valueOf(iThread + i + 1); - sbOut.insert(maxNumDigits - numString.length(), - numString); - sbOut.insert(maxNumDigits, "."); - - int iBuf = maxNumDigits + 2; - sbOut.insert(iBuf, Utils.description(thr)); - iBuf += maxId + 1; - String name = thr.name(); - int iDot = name.lastIndexOf('.'); - if (iDot >= 0 && name.length() > iDot) { - name = name.substring(iDot + 1); - } - sbOut.insert(iBuf, name); - iBuf += maxName + 1; - sbOut.insert(iBuf, Utils.getStatus(thr)); - sbOut.setLength(79); - out.println(sbOut.toString()); - } - for (ThreadGroupReference tg0 : tg.threadGroups()) { - if (!tg.equals(tg0)) { // TODO ref mgt - iThread += printThreadGroup(out, tg0, iThread + tlist.size()); - } - } - return tlist.size(); - } - - // Command: threadgroups - - private void commandThreadGroups() throws NoSessionException { - ThreadGroupIterator it = allThreadGroups(); - int cnt = 0; - OutputSink out = env.getOutputSink(); - while (it.hasNext()) { - ThreadGroupReference tg = it.nextThreadGroup(); - ++cnt; - out.println("" + cnt + ". " + Utils.description(tg) + " " + tg.name()); - } - out.show(); - } - - // Command: thread - - private void commandThread(StringTokenizer t) throws NoSessionException { - if (!t.hasMoreTokens()) { - env.error("Thread number not specified."); - return; - } - ThreadReference thread = findThread(t.nextToken()); - if (thread != null) { - //### Should notify user. - context.setCurrentThread(thread); - } - } - - // Command: threadgroup - - private void commandThreadGroup(StringTokenizer t) throws NoSessionException { - if (!t.hasMoreTokens()) { - env.error("Threadgroup name not specified."); - return; - } - String name = t.nextToken(); - ThreadGroupReference tg = findThreadGroup(name); - if (tg == null) { - env.failure(name + " is not a valid threadgroup name."); - } else { - //### Should notify user. - setDefaultThreadGroup(tg); - } - } - - // Command: run - - private void commandRun(StringTokenizer t) throws NoSessionException { - if (doLoad(false, t)) { - env.notice("Running ..."); - } - } - - // Command: load - - private void commandLoad(StringTokenizer t) throws NoSessionException { - if (doLoad(true, t)) {} - } - - private boolean doLoad(boolean suspended, - StringTokenizer t) throws NoSessionException { - - String clname; - - if (!t.hasMoreTokens()) { - clname = context.getMainClassName(); - if (!clname.equals("")) { - // Run from prevously-set class name. - try { - String vmArgs = context.getVmArguments(); - runtime.run(suspended, - vmArgs, - clname, - context.getProgramArguments()); - return true; - } catch (VMLaunchFailureException e) { - env.failure("Attempt to launch main class \"" + clname + "\" failed."); - } - } else { - env.failure("No main class specified and no current default defined."); - } - } else { - clname = t.nextToken(); - StringBuilder str = new StringBuilder(); - // Allow VM arguments to be specified here? - while (t.hasMoreTokens()) { - String tok = t.nextToken(); - str.append(tok); - if (t.hasMoreTokens()) { - str.append(' '); - } - } - String args = str.toString(); - try { - String vmArgs = context.getVmArguments(); - runtime.run(suspended, vmArgs, clname, args); - context.setMainClassName(clname); - //context.setVmArguments(vmArgs); - context.setProgramArguments(args); - return true; - } catch (VMLaunchFailureException e) { - env.failure("Attempt to launch main class \"" + clname + "\" failed."); - } - } - return false; - } - - // Command: connect - - private void commandConnect(StringTokenizer t) { - try { - LaunchTool.queryAndLaunchVM(runtime); - } catch (VMLaunchFailureException e) { - env.failure("Attempt to connect failed."); - } - } - - // Command: attach - - private void commandAttach(StringTokenizer t) { - String portName; - if (!t.hasMoreTokens()) { - portName = context.getRemotePort(); - if (!portName.equals("")) { - try { - runtime.attach(portName); - } catch (VMLaunchFailureException e) { - env.failure("Attempt to attach to port \"" + portName + "\" failed."); - } - } else { - env.failure("No port specified and no current default defined."); - } - } else { - portName = t.nextToken(); - try { - runtime.attach(portName); - } catch (VMLaunchFailureException e) { - env.failure("Attempt to attach to port \"" + portName + "\" failed."); - } - context.setRemotePort(portName); - } - } - - // Command: detach - - private void commandDetach(StringTokenizer t) throws NoSessionException { - runtime.detach(); - } - - // Command: interrupt - - private void commandInterrupt(StringTokenizer t) throws NoSessionException { - runtime.interrupt(); - } - - // Command: suspend - - private void commandSuspend(StringTokenizer t) throws NoSessionException { - if (!t.hasMoreTokens()) { - // Suspend all threads in the current thread group. - //### Issue: help message says default is all threads. - //### Behavior here agrees with 'jdb', however. - ThreadIterator ti = currentThreadGroupThreads(); - while (ti.hasNext()) { - // TODO - don't suspend debugger threads - ti.nextThread().suspend(); - } - env.notice("All (non-system) threads suspended."); - } else { - while (t.hasMoreTokens()) { - ThreadReference thread = findThread(t.nextToken()); - if (thread != null) { - //thread.suspend(); - runtime.suspendThread(thread); - } - } - } - } - - // Command: resume - - private void commandResume(StringTokenizer t) throws NoSessionException { - if (!t.hasMoreTokens()) { - // Suspend all threads in the current thread group. - //### Issue: help message says default is all threads. - //### Behavior here agrees with 'jdb', however. - ThreadIterator ti = currentThreadGroupThreads(); - while (ti.hasNext()) { - // TODO - don't suspend debugger threads - ti.nextThread().resume(); - } - env.notice("All threads resumed."); - } else { - while (t.hasMoreTokens()) { - ThreadReference thread = findThread(t.nextToken()); - if (thread != null) { - //thread.resume(); - runtime.resumeThread(thread); - } - } - } - } - - // Command: cont - - private void commandCont() throws NoSessionException { - try { - runtime.go(); - } catch (VMNotInterruptedException e) { - //### failure? - env.notice("Target VM is already running."); - } - } - - // Command: step - - private void commandStep(StringTokenizer t) throws NoSessionException{ - ThreadReference current = context.getCurrentThread(); - if (current == null) { - env.failure("No current thread."); - return; - } - try { - if (t.hasMoreTokens() && - t.nextToken().toLowerCase().equals("up")) { - runtime.stepOut(current); - } else { - runtime.stepIntoLine(current); - } - } catch (AbsentInformationException e) { - env.failure("No linenumber information available -- " + - "Try \"stepi\" to step by instructions."); - } - } - - // Command: stepi - - private void commandStepi() throws NoSessionException { - ThreadReference current = context.getCurrentThread(); - if (current == null) { - env.failure("No current thread."); - return; - } - runtime.stepIntoInstruction(current); - } - - // Command: next - - private void commandNext() throws NoSessionException { - ThreadReference current = context.getCurrentThread(); - if (current == null) { - env.failure("No current thread."); - return; - } - try { - runtime.stepOverLine(current); - } catch (AbsentInformationException e) { - env.failure("No linenumber information available -- " + - "Try \"nexti\" to step by instructions."); - } - } - - // Command: nexti (NEW) - - private void commandNexti() throws NoSessionException { - ThreadReference current = context.getCurrentThread(); - if (current == null) { - env.failure("No current thread."); - return; - } - runtime.stepOverInstruction(current); - } - - // Command: kill - - private void commandKill(StringTokenizer t) throws NoSessionException { - //### Should change the way in which thread ids and threadgroup names - //### are distinguished. - if (!t.hasMoreTokens()) { - env.error("Usage: kill or "); - return; - } - while (t.hasMoreTokens()) { - String idToken = t.nextToken(); - ThreadReference thread = findThread(idToken); - if (thread != null) { - runtime.stopThread(thread); - env.notice("Thread " + thread.name() + " killed."); - return; - } else { - /* Check for threadgroup name, NOT skipping "system". */ - //### Should skip "system"? Classic 'jdb' does this. - //### Should deal with possible non-uniqueness of threadgroup names. - ThreadGroupIterator itg = allThreadGroups(); - while (itg.hasNext()) { - ThreadGroupReference tg = itg.nextThreadGroup(); - if (tg.name().equals(idToken)) { - ThreadIterator it = new ThreadIterator(tg); - while (it.hasNext()) { - runtime.stopThread(it.nextThread()); - } - env.notice("Threadgroup " + tg.name() + "killed."); - return; - } - } - env.failure("\"" + idToken + - "\" is not a valid threadgroup or id."); - } - } - } - - - /************* - // TODO - private void commandCatchException(StringTokenizer t) throws NoSessionException {} - // TODO - private void commandIgnoreException(StringTokenizer t) throws NoSessionException {} - *************/ - - // Command: up - - //### Print current frame after command? - - int readCount(StringTokenizer t) { - int cnt = 1; - if (t.hasMoreTokens()) { - String idToken = t.nextToken(); - try { - cnt = Integer.valueOf(idToken).intValue(); - } catch (NumberFormatException e) { - cnt = -1; - } - } - return cnt; - } - - void commandUp(StringTokenizer t) throws NoSessionException { - ThreadReference current = context.getCurrentThread(); - if (current == null) { - env.failure("No current thread."); - return; - } - int nLevels = readCount(t); - if (nLevels <= 0) { - env.error("usage: up [n frames]"); - return; - } - try { - int delta = context.moveCurrentFrameIndex(current, -nLevels); - if (delta == 0) { - env.notice("Already at top of stack."); - } else if (-delta < nLevels) { - env.notice("Moved up " + delta + " frames to top of stack."); - } - } catch (VMNotInterruptedException e) { - env.failure("Target VM must be in interrupted state."); - } - } - - private void commandDown(StringTokenizer t) throws NoSessionException { - ThreadReference current = context.getCurrentThread(); - if (current == null) { - env.failure("No current thread."); - return; - } - int nLevels = readCount(t); - if (nLevels <= 0) { - env.error("usage: down [n frames]"); - return; - } - try { - int delta = context.moveCurrentFrameIndex(current, nLevels); - if (delta == 0) { - env.notice("Already at bottom of stack."); - } else if (delta < nLevels) { - env.notice("Moved down " + delta + " frames to bottom of stack."); - } - } catch (VMNotInterruptedException e) { - env.failure("Target VM must be in interrupted state."); - } - } - - // Command: frame - - private void commandFrame(StringTokenizer t) throws NoSessionException { - ThreadReference current = context.getCurrentThread(); - if (current == null) { - env.failure("No current thread."); - return; - } - if (!t.hasMoreTokens()) { - env.error("usage: frame "); - return; - } - String idToken = t.nextToken(); - int n; - try { - n = Integer.valueOf(idToken).intValue(); - } catch (NumberFormatException e) { - n = 0; - } - if (n <= 0) { - env.error("use positive frame index"); - return; - } - try { - int delta = context.setCurrentFrameIndex(current, n); - if (delta == 0) { - env.notice("Frame unchanged."); - } else if (delta < 0) { - env.notice("Moved up " + -delta + " frames."); - } else { - env.notice("Moved down " + delta + " frames."); - } - } catch (VMNotInterruptedException e) { - env.failure("Target VM must be in interrupted state."); - } - } - - // Command: where - - //### Should we insist that VM be interrupted here? - //### There is an inconsistency between the 'where' command - //### and 'up' and 'down' in this respect. - - private void commandWhere(StringTokenizer t, boolean showPC) - throws NoSessionException { - ThreadReference current = context.getCurrentThread(); - if (!t.hasMoreTokens()) { - if (current == null) { - env.error("No thread specified."); - return; - } - dumpStack(current, showPC); - } else { - String token = t.nextToken(); - if (token.toLowerCase().equals("all")) { - ThreadIterator it = allThreads(); - while (it.hasNext()) { - ThreadReference thread = it.next(); - out.println(thread.name() + ": "); - dumpStack(thread, showPC); - } - } else { - ThreadReference thread = findThread(t.nextToken()); - //### Do we want to set current thread here? - //### Should notify user of change. - if (thread != null) { - context.setCurrentThread(thread); - } - dumpStack(thread, showPC); - } - } - } - - private void dumpStack(ThreadReference thread, boolean showPC) { - //### Check for these. - //env.failure("Thread no longer exists."); - //env.failure("Target VM must be in interrupted state."); - //env.failure("Current thread isn't suspended."); - //### Should handle extremely long stack traces sensibly for user. - List stack = null; - try { - stack = thread.frames(); - } catch (IncompatibleThreadStateException e) { - env.failure("Thread is not suspended."); - } - //### Fix this! - //### Previously mishandled cases where thread was not current. - //### Now, prints all of the stack regardless of current frame. - int frameIndex = 0; - //int frameIndex = context.getCurrentFrameIndex(); - if (stack == null) { - env.failure("Thread is not running (no stack)."); - } else { - OutputSink out = env.getOutputSink(); - int nFrames = stack.size(); - for (int i = frameIndex; i < nFrames; i++) { - StackFrame frame = stack.get(i); - Location loc = frame.location(); - Method meth = loc.method(); - out.print(" [" + (i + 1) + "] "); - out.print(meth.declaringType().name()); - out.print('.'); - out.print(meth.name()); - out.print(" ("); - if (meth.isNative()) { - out.print("native method"); - } else if (loc.lineNumber() != -1) { - try { - out.print(loc.sourceName()); - } catch (AbsentInformationException e) { - out.print(""); - } - out.print(':'); - out.print(loc.lineNumber()); - } - out.print(')'); - if (showPC) { - long pc = loc.codeIndex(); - if (pc != -1) { - out.print(", pc = " + pc); - } - } - out.println(); - } - out.show(); - } - } - - private void listEventRequests() throws NoSessionException { - // Print set breakpoints - List specs = runtime.eventRequestSpecs(); - if (specs.isEmpty()) { - env.notice("No breakpoints/watchpoints/exceptions set."); - } else { - OutputSink out = env.getOutputSink(); - out.println("Current breakpoints/watchpoints/exceptions set:"); - for (EventRequestSpec bp : specs) { - out.println("\t" + bp); - } - out.show(); - } - } - - private BreakpointSpec parseBreakpointSpec(String bptSpec) { - StringTokenizer t = new StringTokenizer(bptSpec); - BreakpointSpec bpSpec = null; -// try { - String token = t.nextToken("@:( \t\n\r"); - // We can't use hasMoreTokens here because it will cause any leading - // paren to be lost. - String rest; - try { - rest = t.nextToken("").trim(); - } catch (NoSuchElementException e) { - rest = null; - } - if ((rest != null) && rest.startsWith("@")) { - t = new StringTokenizer(rest.substring(1)); - String sourceName = token; - String lineToken = t.nextToken(); - int lineNumber = Integer.valueOf(lineToken).intValue(); - if (t.hasMoreTokens()) { - return null; - } - bpSpec = runtime.createSourceLineBreakpoint(sourceName, - lineNumber); - } else if ((rest != null) && rest.startsWith(":")) { - t = new StringTokenizer(rest.substring(1)); - String classId = token; - String lineToken = t.nextToken(); - int lineNumber = Integer.valueOf(lineToken).intValue(); - if (t.hasMoreTokens()) { - return null; - } - bpSpec = runtime.createClassLineBreakpoint(classId, lineNumber); - } else { - // Try stripping method from class.method token. - int idot = token.lastIndexOf('.'); - if ( (idot <= 0) || /* No dot or dot in first char */ - (idot >= token.length() - 1) ) { /* dot in last char */ - return null; - } - String methodName = token.substring(idot + 1); - String classId = token.substring(0, idot); - List argumentList = null; - if (rest != null) { - if (!rest.startsWith("(") || !rest.endsWith(")")) { - //### Should throw exception with error message - //out.println("Invalid method specification: " - // + methodName + rest); - return null; - } - // Trim the parens - //### What about spaces in arglist? - rest = rest.substring(1, rest.length() - 1); - argumentList = new ArrayList(); - t = new StringTokenizer(rest, ","); - while (t.hasMoreTokens()) { - argumentList.add(t.nextToken()); - } - } - bpSpec = runtime.createMethodBreakpoint(classId, - methodName, - argumentList); - } -// } catch (Exception e) { -// env.error("Exception attempting to create breakpoint: " + e); -// return null; -// } - return bpSpec; - } - - private void commandStop(StringTokenizer t) throws NoSessionException { - String token; - - if (!t.hasMoreTokens()) { - listEventRequests(); - } else { - token = t.nextToken(); - // Ignore optional "at" or "in" token. - // Allowed for backward compatibility. - if (token.equals("at") || token.equals("in")) { - if (t.hasMoreTokens()) { - token = t.nextToken(); - } else { - env.error("Missing breakpoint specification."); - return; - } - } - BreakpointSpec bpSpec = parseBreakpointSpec(token); - if (bpSpec != null) { - //### Add sanity-checks for deferred breakpoint. - runtime.install(bpSpec); - } else { - env.error("Ill-formed breakpoint specification."); - } - } - } - - private void commandClear(StringTokenizer t) throws NoSessionException { - if (!t.hasMoreTokens()) { - // Print set breakpoints - listEventRequests(); - return; - } - //### need 'clear all' - BreakpointSpec bpSpec = parseBreakpointSpec(t.nextToken()); - if (bpSpec != null) { - List specs = runtime.eventRequestSpecs(); - - if (specs.isEmpty()) { - env.notice("No breakpoints set."); - } else { - List toDelete = new ArrayList(); - for (EventRequestSpec spec : specs) { - if (spec.equals(bpSpec)) { - toDelete.add(spec); - } - } - // The request used for matching should be found - if (toDelete.size() <= 1) { - env.notice("No matching breakpoint set."); - } - for (EventRequestSpec spec : toDelete) { - runtime.delete(spec); - } - } - } else { - env.error("Ill-formed breakpoint specification."); - } - } - - // Command: list - - private void commandList(StringTokenizer t) throws NoSessionException { - ThreadReference current = context.getCurrentThread(); - if (current == null) { - env.error("No thread specified."); - return; - } - Location loc; - try { - StackFrame frame = context.getCurrentFrame(current); - if (frame == null) { - env.failure("Thread has not yet begun execution."); - return; - } - loc = frame.location(); - } catch (VMNotInterruptedException e) { - env.failure("Target VM must be in interrupted state."); - return; - } - SourceModel source = sourceManager.sourceForLocation(loc); - if (source == null) { - if (loc.method().isNative()) { - env.failure("Current method is native."); - return; - } - env.failure("No source available for " + Utils.locationString(loc) + "."); - return; - } - ReferenceType refType = loc.declaringType(); - int lineno = loc.lineNumber(); - if (t.hasMoreTokens()) { - String id = t.nextToken(); - // See if token is a line number. - try { - lineno = Integer.valueOf(id).intValue(); - } catch (NumberFormatException nfe) { - // It isn't -- see if it's a method name. - List meths = refType.methodsByName(id); - if (meths == null || meths.size() == 0) { - env.failure(id + - " is not a valid line number or " + - "method name for class " + - refType.name()); - return; - } else if (meths.size() > 1) { - env.failure(id + - " is an ambiguous method name in" + - refType.name()); - return; - } - loc = meths.get(0).location(); - lineno = loc.lineNumber(); - } - } - int startLine = (lineno > 4) ? lineno - 4 : 1; - int endLine = startLine + 9; - String sourceLine = source.sourceLine(lineno); - if (sourceLine == null) { - env.failure("" + - lineno + - " is an invalid line number for " + - refType.name()); - } else { - OutputSink out = env.getOutputSink(); - for (int i = startLine; i <= endLine; i++) { - sourceLine = source.sourceLine(i); - if (sourceLine == null) { - break; - } - out.print(i); - out.print("\t"); - if (i == lineno) { - out.print("=> "); - } else { - out.print(" "); - } - out.println(sourceLine); - } - out.show(); - } - } - - // Command: use - // Get or set the source file path list. - - private void commandUse(StringTokenizer t) { - if (!t.hasMoreTokens()) { - out.println(sourceManager.getSourcePath().asString()); - } else { - //### Should throw exception for invalid path. - //### E.g., vetoable property change. - sourceManager.setSourcePath(new SearchPath(t.nextToken())); - } - } - - // Command: sourcepath - // Get or set the source file path list. (Alternate to 'use'.) - - private void commandSourcepath(StringTokenizer t) { - if (!t.hasMoreTokens()) { - out.println(sourceManager.getSourcePath().asString()); - } else { - //### Should throw exception for invalid path. - //### E.g., vetoable property change. - sourceManager.setSourcePath(new SearchPath(t.nextToken())); - } - } - - // Command: classpath - // Get or set the class file path list. - - private void commandClasspath(StringTokenizer t) { - if (!t.hasMoreTokens()) { - out.println(classManager.getClassPath().asString()); - } else { - //### Should throw exception for invalid path. - //### E.g., vetoable property change. - classManager.setClassPath(new SearchPath(t.nextToken())); - } - } - - // Command: view - // Display source for source file or class. - - private void commandView(StringTokenizer t) throws NoSessionException { - if (!t.hasMoreTokens()) { - env.error("Argument required"); - } else { - String name = t.nextToken(); - if (name.endsWith(".java") || - name.indexOf(File.separatorChar) >= 0) { - env.viewSource(name); - } else { - //### JDI crashes taking line number for class. - /***** - ReferenceType cls = findClass(name); - if (cls != null) { - env.viewLocation(cls.location()); - } else { - env.failure("No such class"); - } - *****/ - String fileName = name.replace('.', File.separatorChar) + ".java"; - env.viewSource(fileName); - } - } - } - - // Command: locals - // Print all local variables in current stack frame. - - private void commandLocals() throws NoSessionException { - ThreadReference current = context.getCurrentThread(); - if (current == null) { - env.failure("No default thread specified: " + - "use the \"thread\" command first."); - return; - } - StackFrame frame; - try { - frame = context.getCurrentFrame(current); - if (frame == null) { - env.failure("Thread has not yet created any stack frames."); - return; - } - } catch (VMNotInterruptedException e) { - env.failure("Target VM must be in interrupted state."); - return; - } - - List vars; - try { - vars = frame.visibleVariables(); - if (vars == null || vars.size() == 0) { - env.failure("No local variables"); - return; - } - } catch (AbsentInformationException e) { - env.failure("Local variable information not available." + - " Compile with -g to generate variable information"); - return; - } - - OutputSink out = env.getOutputSink(); - out.println("Method arguments:"); - for (LocalVariable var : vars) { - if (var.isArgument()) { - printVar(out, var, frame); - } - } - out.println("Local variables:"); - for (LocalVariable var : vars) { - if (!var.isArgument()) { - printVar(out, var, frame); - } - } - out.show(); - return; - } - - /** - * Command: monitor - * Monitor an expression - */ - private void commandMonitor(StringTokenizer t) throws NoSessionException { - if (!t.hasMoreTokens()) { - env.error("Argument required"); - } else { - env.getMonitorListModel().add(t.nextToken("")); - } - } - - /** - * Command: unmonitor - * Unmonitor an expression - */ - private void commandUnmonitor(StringTokenizer t) throws NoSessionException { - if (!t.hasMoreTokens()) { - env.error("Argument required"); - } else { - env.getMonitorListModel().remove(t.nextToken("")); - } - } - - // Print a stack variable. - - private void printVar(OutputSink out, LocalVariable var, StackFrame frame) { - out.print(" " + var.name()); - if (var.isVisible(frame)) { - Value val = frame.getValue(var); - out.println(" = " + val.toString()); - } else { - out.println(" is not in scope"); - } - } - - // Command: print - // Evaluate an expression. - - private void commandPrint(StringTokenizer t, boolean dumpObject) throws NoSessionException { - if (!t.hasMoreTokens()) { - //### Probably confused if expresion contains whitespace. - env.error("No expression specified."); - return; - } - ThreadReference current = context.getCurrentThread(); - if (current == null) { - env.failure("No default thread specified: " + - "use the \"thread\" command first."); - return; - } - StackFrame frame; - try { - frame = context.getCurrentFrame(current); - if (frame == null) { - env.failure("Thread has not yet created any stack frames."); - return; - } - } catch (VMNotInterruptedException e) { - env.failure("Target VM must be in interrupted state."); - return; - } - while (t.hasMoreTokens()) { - String expr = t.nextToken(""); - Value val = null; - try { - val = runtime.evaluate(frame, expr); - } catch(Exception e) { - env.error("Exception: " + e); - //### Fix this! - } - if (val == null) { - return; // Error message already printed - } - OutputSink out = env.getOutputSink(); - if (dumpObject && (val instanceof ObjectReference) && - !(val instanceof StringReference)) { - ObjectReference obj = (ObjectReference)val; - ReferenceType refType = obj.referenceType(); - out.println(expr + " = " + val.toString() + " {"); - dump(out, obj, refType, refType); - out.println("}"); - } else { - out.println(expr + " = " + val.toString()); - } - out.show(); - } - } - - private void dump(OutputSink out, - ObjectReference obj, ReferenceType refType, - ReferenceType refTypeBase) { - for (Field field : refType.fields()) { - out.print(" "); - if (!refType.equals(refTypeBase)) { - out.print(refType.name() + "."); - } - out.print(field.name() + ": "); - Object o = obj.getValue(field); - out.println((o == null) ? "null" : o.toString()); // Bug ID 4374471 - } - if (refType instanceof ClassType) { - ClassType sup = ((ClassType)refType).superclass(); - if (sup != null) { - dump(out, obj, sup, refTypeBase); - } - } else if (refType instanceof InterfaceType) { - for (InterfaceType sup : ((InterfaceType)refType).superinterfaces()) { - dump(out, obj, sup, refTypeBase); - } - } - } - - /* - * Display help message. - */ - - private void help() { - out.println("** command list **"); - out.println("threads [threadgroup] -- list threads"); - out.println("thread -- set default thread"); - out.println("suspend [thread id(s)] -- suspend threads (default: all)"); - out.println("resume [thread id(s)] -- resume threads (default: all)"); - out.println("where [thread id] | all -- dump a thread's stack"); - out.println("wherei [thread id] | all -- dump a thread's stack, with pc info"); - out.println("threadgroups -- list threadgroups"); - out.println("threadgroup -- set current threadgroup\n"); -// out.println("print -- print value of expression"); - out.println("dump -- print all object information\n"); -// out.println("eval -- evaluate expression (same as print)"); - out.println("locals -- print all local variables in current stack frame\n"); - out.println("classes -- list currently known classes"); - out.println("methods -- list a class's methods\n"); - out.println("stop [in] .[(argument_type,...)] -- set a breakpoint in a method"); - out.println("stop [at] : -- set a breakpoint at a line"); - out.println("up [n frames] -- move up a thread's stack"); - out.println("down [n frames] -- move down a thread's stack"); - out.println("frame -- to a frame"); - out.println("clear .[(argument_type,...)] -- clear a breakpoint in a method"); - out.println("clear : -- clear a breakpoint at a line"); - out.println("clear -- list breakpoints"); - out.println("step -- execute current line"); - out.println("step up -- execute until the current method returns to its caller"); - out.println("stepi -- execute current instruction"); - out.println("next -- step one line (step OVER calls)"); - out.println("nexti -- step one instruction (step OVER calls)"); - out.println("cont -- continue execution from breakpoint\n"); -// out.println("catch -- break for the specified exception"); -// out.println("ignore -- ignore when the specified exception\n"); - out.println("view classname|filename -- display source file"); - out.println("list [line number|method] -- print source code context at line or method"); - out.println("use -- display or change the source path\n"); -//### new - out.println("sourcepath -- display or change the source path\n"); -//### new - out.println("classpath -- display or change the class path\n"); - out.println("monitor -- evaluate an expression each time the program stops\n"); - out.println("unmonitor -- delete a monitor\n"); - out.println("read -- read and execute a command file\n"); -// out.println("memory -- report memory usage"); -// out.println("gc -- free unused objects\n"); - out.println("run [args] -- start execution of a Java class"); - out.println("run -- re-execute last class run"); - out.println("load [args] -- start execution of a Java class, initially suspended"); - out.println("load -- re-execute last class run, initially suspended"); - out.println("attach -- debug existing process\n"); - out.println("detach -- detach from debuggee process\n"); - out.println("kill -- kill a thread or threadgroup\n"); - out.println("!! -- repeat last command"); - out.println("help (or ?) -- list commands"); - out.println("exit (or quit) -- exit debugger"); - } - - /* - * Execute a command. - */ - - public void executeCommand(String command) { - //### Treatment of 'out' here is dirty... - out = env.getOutputSink(); - if (echo) { - out.println(">>> " + command); - } - StringTokenizer t = new StringTokenizer(command); - try { - String cmd; - if (t.hasMoreTokens()) { - cmd = t.nextToken().toLowerCase(); - lastCommand = cmd; - } else { - cmd = lastCommand; - } - if (cmd.equals("print")) { - commandPrint(t, false); - } else if (cmd.equals("eval")) { - commandPrint(t, false); - } else if (cmd.equals("dump")) { - commandPrint(t, true); - } else if (cmd.equals("locals")) { - commandLocals(); - } else if (cmd.equals("classes")) { - commandClasses(); - } else if (cmd.equals("methods")) { - commandMethods(t); - } else if (cmd.equals("threads")) { - commandThreads(t); - } else if (cmd.equals("thread")) { - commandThread(t); - } else if (cmd.equals("suspend")) { - commandSuspend(t); - } else if (cmd.equals("resume")) { - commandResume(t); - } else if (cmd.equals("cont")) { - commandCont(); - } else if (cmd.equals("threadgroups")) { - commandThreadGroups(); - } else if (cmd.equals("threadgroup")) { - commandThreadGroup(t); - } else if (cmd.equals("run")) { - commandRun(t); - } else if (cmd.equals("load")) { - commandLoad(t); - } else if (cmd.equals("connect")) { - commandConnect(t); - } else if (cmd.equals("attach")) { - commandAttach(t); - } else if (cmd.equals("detach")) { - commandDetach(t); - } else if (cmd.equals("interrupt")) { - commandInterrupt(t); -//### Not implemented. -// } else if (cmd.equals("catch")) { -// commandCatchException(t); -//### Not implemented. -// } else if (cmd.equals("ignore")) { -// commandIgnoreException(t); - } else if (cmd.equals("step")) { - commandStep(t); - } else if (cmd.equals("stepi")) { - commandStepi(); - } else if (cmd.equals("next")) { - commandNext(); - } else if (cmd.equals("nexti")) { - commandNexti(); - } else if (cmd.equals("kill")) { - commandKill(t); - } else if (cmd.equals("where")) { - commandWhere(t, false); - } else if (cmd.equals("wherei")) { - commandWhere(t, true); - } else if (cmd.equals("up")) { - commandUp(t); - } else if (cmd.equals("down")) { - commandDown(t); - } else if (cmd.equals("frame")) { - commandFrame(t); - } else if (cmd.equals("stop")) { - commandStop(t); - } else if (cmd.equals("clear")) { - commandClear(t); - } else if (cmd.equals("list")) { - commandList(t); - } else if (cmd.equals("use")) { - commandUse(t); - } else if (cmd.equals("sourcepath")) { - commandSourcepath(t); - } else if (cmd.equals("classpath")) { - commandClasspath(t); - } else if (cmd.equals("monitor")) { - commandMonitor(t); - } else if (cmd.equals("unmonitor")) { - commandUnmonitor(t); - } else if (cmd.equals("view")) { - commandView(t); -// } else if (cmd.equals("read")) { -// readCommand(t); - } else if (cmd.equals("help") || cmd.equals("?")) { - help(); - } else if (cmd.equals("quit") || cmd.equals("exit")) { - try { - runtime.detach(); - } catch (NoSessionException e) { - // ignore - } - env.terminate(); - } else { - //### Dubious repeat-count feature inherited from 'jdb' - if (t.hasMoreTokens()) { - try { - int repeat = Integer.parseInt(cmd); - String subcom = t.nextToken(""); - while (repeat-- > 0) { - executeCommand(subcom); - } - return; - } catch (NumberFormatException exc) { - } - } - out.println("huh? Try help..."); - out.flush(); - } - } catch (NoSessionException e) { - out.println("There is no currently attached VM session."); - out.flush(); - } catch (Exception e) { - out.println("Internal exception: " + e.toString()); - out.flush(); - System.out.println("JDB internal exception: " + e.toString()); - e.printStackTrace(); - } - out.show(); - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/CommandTool.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/CommandTool.java deleted file mode 100644 index d010ec2f56b..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/CommandTool.java +++ /dev/null @@ -1,342 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.gui; - -import java.io.*; -import java.util.*; - -import javax.swing.*; -import java.awt.BorderLayout; -import java.awt.event.*; - -import com.sun.jdi.*; -import com.sun.jdi.event.*; - -import com.sun.tools.example.debug.bdi.*; -import com.sun.tools.example.debug.event.*; - -public class CommandTool extends JPanel { - - private static final long serialVersionUID = 8613516856378346415L; - - private Environment env; - - private ContextManager context; - private ExecutionManager runtime; - private SourceManager sourceManager; - - private TypeScript script; - - private static final String DEFAULT_CMD_PROMPT = "Command:"; - - public CommandTool(Environment env) { - - super(new BorderLayout()); - - this.env = env; - this.context = env.getContextManager(); - this.runtime = env.getExecutionManager(); - this.sourceManager = env.getSourceManager(); - - script = new TypeScript(DEFAULT_CMD_PROMPT, false); //no echo - this.add(script); - - final CommandInterpreter interpreter = - new CommandInterpreter(env); - - // Establish handler for incoming commands. - - script.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - interpreter.executeCommand(script.readln()); - } - }); - - // Establish ourselves as the listener for VM diagnostics. - - OutputListener diagnosticsListener = - new TypeScriptOutputListener(script, true); - runtime.addDiagnosticsListener(diagnosticsListener); - - // Establish ourselves as the shared debugger typescript. - - env.setTypeScript(new PrintWriter(new TypeScriptWriter(script))); - - // Handle VM events. - - TTYDebugListener listener = new TTYDebugListener(diagnosticsListener); - - runtime.addJDIListener(listener); - runtime.addSessionListener(listener); - runtime.addSpecListener(listener); - context.addContextListener(listener); - - //### remove listeners on exit! - - } - - private class TTYDebugListener implements - JDIListener, SessionListener, SpecListener, ContextListener { - - private OutputListener diagnostics; - - TTYDebugListener(OutputListener diagnostics) { - this.diagnostics = diagnostics; - } - - // JDIListener - - @Override - public void accessWatchpoint(AccessWatchpointEventSet e) { - setThread(e); - for (EventIterator it = e.eventIterator(); it.hasNext(); ) { - it.nextEvent(); - diagnostics.putString("Watchpoint hit: " + - locationString(e)); - } - } - - @Override - public void classPrepare(ClassPrepareEventSet e) { - if (context.getVerboseFlag()) { - String name = e.getReferenceType().name(); - diagnostics.putString("Class " + name + " loaded"); - } - } - - @Override - public void classUnload(ClassUnloadEventSet e) { - if (context.getVerboseFlag()) { - diagnostics.putString("Class " + e.getClassName() + - " unloaded."); - } - } - - @Override - public void exception(ExceptionEventSet e) { - setThread(e); - String name = e.getException().referenceType().name(); - diagnostics.putString("Exception: " + name); - } - - @Override - public void locationTrigger(LocationTriggerEventSet e) { - String locString = locationString(e); - setThread(e); - for (EventIterator it = e.eventIterator(); it.hasNext(); ) { - Event evt = it.nextEvent(); - if (evt instanceof BreakpointEvent) { - diagnostics.putString("Breakpoint hit: " + locString); - } else if (evt instanceof StepEvent) { - diagnostics.putString("Step completed: " + locString); - } else if (evt instanceof MethodEntryEvent) { - diagnostics.putString("Method entered: " + locString); - } else if (evt instanceof MethodExitEvent) { - diagnostics.putString("Method exited: " + locString); - } else { - diagnostics.putString("UNKNOWN event: " + e); - } - } - } - - @Override - public void modificationWatchpoint(ModificationWatchpointEventSet e) { - setThread(e); - for (EventIterator it = e.eventIterator(); it.hasNext(); ) { - it.nextEvent(); - diagnostics.putString("Watchpoint hit: " + - locationString(e)); - } - } - - @Override - public void threadDeath(ThreadDeathEventSet e) { - if (context.getVerboseFlag()) { - diagnostics.putString("Thread " + e.getThread() + - " ended."); - } - } - - @Override - public void threadStart(ThreadStartEventSet e) { - if (context.getVerboseFlag()) { - diagnostics.putString("Thread " + e.getThread() + - " started."); - } - } - - @Override - public void vmDeath(VMDeathEventSet e) { - script.setPrompt(DEFAULT_CMD_PROMPT); - diagnostics.putString("VM exited"); - } - - @Override - public void vmDisconnect(VMDisconnectEventSet e) { - script.setPrompt(DEFAULT_CMD_PROMPT); - diagnostics.putString("Disconnected from VM"); - } - - @Override - public void vmStart(VMStartEventSet e) { - script.setPrompt(DEFAULT_CMD_PROMPT); - diagnostics.putString("VM started"); - } - - // SessionListener - - @Override - public void sessionStart(EventObject e) {} - - @Override - public void sessionInterrupt(EventObject e) { - Thread.yield(); // fetch output - diagnostics.putString("VM interrupted by user."); - script.setPrompt(DEFAULT_CMD_PROMPT); - } - - @Override - public void sessionContinue(EventObject e) { - diagnostics.putString("Execution resumed."); - script.setPrompt(DEFAULT_CMD_PROMPT); - } - - // SpecListener - - @Override - public void breakpointSet(SpecEvent e) { - EventRequestSpec spec = e.getEventRequestSpec(); - diagnostics.putString("Breakpoint set at " + spec + "."); - } - @Override - public void breakpointDeferred(SpecEvent e) { - EventRequestSpec spec = e.getEventRequestSpec(); - diagnostics.putString("Breakpoint will be set at " + - spec + " when its class is loaded."); - } - @Override - public void breakpointDeleted(SpecEvent e) { - EventRequestSpec spec = e.getEventRequestSpec(); - diagnostics.putString("Breakpoint at " + spec.toString() + " deleted."); - } - @Override - public void breakpointResolved(SpecEvent e) { - EventRequestSpec spec = e.getEventRequestSpec(); - diagnostics.putString("Breakpoint resolved to " + spec.toString() + "."); - } - @Override - public void breakpointError(SpecErrorEvent e) { - EventRequestSpec spec = e.getEventRequestSpec(); - diagnostics.putString("Deferred breakpoint at " + - spec + " could not be resolved:" + - e.getReason()); - } - -//### Add info for watchpoints and exceptions - - @Override - public void watchpointSet(SpecEvent e) { - } - @Override - public void watchpointDeferred(SpecEvent e) { - } - @Override - public void watchpointDeleted(SpecEvent e) { - } - @Override - public void watchpointResolved(SpecEvent e) { - } - @Override - public void watchpointError(SpecErrorEvent e) { - } - - @Override - public void exceptionInterceptSet(SpecEvent e) { - } - @Override - public void exceptionInterceptDeferred(SpecEvent e) { - } - @Override - public void exceptionInterceptDeleted(SpecEvent e) { - } - @Override - public void exceptionInterceptResolved(SpecEvent e) { - } - @Override - public void exceptionInterceptError(SpecErrorEvent e) { - } - - - // ContextListener. - - // If the user selects a new current thread or frame, update prompt. - - @Override - public void currentFrameChanged(CurrentFrameChangedEvent e) { - // Update prompt only if affect thread is current. - ThreadReference thread = e.getThread(); - if (thread == context.getCurrentThread()) { - script.setPrompt(promptString(thread, e.getIndex())); - } - } - - } - - private String locationString(LocatableEventSet e) { - Location loc = e.getLocation(); - return "thread=\"" + e.getThread().name() + - "\", " + Utils.locationString(loc); - } - - private void setThread(LocatableEventSet e) { - if (!e.suspendedNone()) { - Thread.yield(); // fetch output - script.setPrompt(promptString(e.getThread(), 0)); - //### Current thread should be set elsewhere, e.g., - //### in ContextManager - //### context.setCurrentThread(thread); - } - } - - private String promptString(ThreadReference thread, int frameIndex) { - if (thread == null) { - return DEFAULT_CMD_PROMPT; - } else { - // Frame indices are presented to user as indexed from 1. - return (thread.name() + "[" + (frameIndex + 1) + "]:"); - } - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ContextListener.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ContextListener.java deleted file mode 100644 index 27143fac83a..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ContextListener.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.gui; - -public interface ContextListener { - void currentFrameChanged(CurrentFrameChangedEvent e); -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ContextManager.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ContextManager.java deleted file mode 100644 index fb2416789e8..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/ContextManager.java +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.gui; - -import java.io.*; -import java.util.*; - -import com.sun.jdi.*; -import com.sun.tools.example.debug.event.*; -import com.sun.tools.example.debug.bdi.*; - -public class ContextManager { - - private ClassManager classManager; - private ExecutionManager runtime; - - private String mainClassName; - private String vmArguments; - private String commandArguments; - private String remotePort; - - private ThreadReference currentThread; - - private boolean verbose; - - private ArrayList contextListeners = new ArrayList(); - - public ContextManager(Environment env) { - classManager = env.getClassManager(); - runtime = env.getExecutionManager(); - mainClassName = ""; - vmArguments = ""; - commandArguments = ""; - currentThread = null; - - ContextManagerListener listener = new ContextManagerListener(); - runtime.addJDIListener(listener); - runtime.addSessionListener(listener); - } - - // Program execution defaults. - - //### Should there be change listeners for these? - //### They would be needed if we expected a dialog to be - //### synchronized with command input while it was open. - - public String getMainClassName() { - return mainClassName; - } - - public void setMainClassName(String mainClassName) { - this.mainClassName = mainClassName; - } - - public String getVmArguments() { - return processClasspathDefaults(vmArguments); - } - - public void setVmArguments(String vmArguments) { - this.vmArguments = vmArguments; - } - - public String getProgramArguments() { - return commandArguments; - } - - public void setProgramArguments(String commandArguments) { - this.commandArguments = commandArguments; - } - - public String getRemotePort() { - return remotePort; - } - - public void setRemotePort(String remotePort) { - this.remotePort = remotePort; - - } - - - // Miscellaneous debugger session preferences. - - public boolean getVerboseFlag() { - return verbose; - } - - public void setVerboseFlag(boolean verbose) { - this.verbose = verbose; - } - - - // Thread focus. - - public ThreadReference getCurrentThread() { - return currentThread; - } - - public void setCurrentThread(ThreadReference t) { - if (t != currentThread) { - currentThread = t; - notifyCurrentThreadChanged(t); - } - } - - public void setCurrentThreadInvalidate(ThreadReference t) { - currentThread = t; - notifyCurrentFrameChanged(runtime.threadInfo(t), - 0, true); - } - - public void invalidateCurrentThread() { - notifyCurrentFrameChanged(null, 0, true); - } - - - // If a view is displaying the current thread, it may - // choose to indicate which frame is current in the - // sense of the command-line UI. It may also "warp" the - // selection to that frame when changed by an 'up' or 'down' - // command. Hence, a notifier is provided. - - /****** - public int getCurrentFrameIndex() { - return getCurrentFrameIndex(currentThreadInfo); - } - ******/ - - public int getCurrentFrameIndex(ThreadReference t) { - return getCurrentFrameIndex(runtime.threadInfo(t)); - } - - //### Used in StackTraceTool. - public int getCurrentFrameIndex(ThreadInfo tinfo) { - if (tinfo == null) { - return 0; - } - Integer currentFrame = (Integer)tinfo.getUserObject(); - if (currentFrame == null) { - return 0; - } else { - return currentFrame.intValue(); - } - } - - public int moveCurrentFrameIndex(ThreadReference t, int count) throws VMNotInterruptedException { - return setCurrentFrameIndex(t,count, true); - } - - public int setCurrentFrameIndex(ThreadReference t, int newIndex) throws VMNotInterruptedException { - return setCurrentFrameIndex(t, newIndex, false); - } - - public int setCurrentFrameIndex(int newIndex) throws VMNotInterruptedException { - if (currentThread == null) { - return 0; - } else { - return setCurrentFrameIndex(currentThread, newIndex, false); - } - } - - private int setCurrentFrameIndex(ThreadReference t, int x, boolean relative) throws VMNotInterruptedException { - boolean sameThread = t.equals(currentThread); - ThreadInfo tinfo = runtime.threadInfo(t); - if (tinfo == null) { - return 0; - } - int maxIndex = tinfo.getFrameCount()-1; - int oldIndex = getCurrentFrameIndex(tinfo); - int newIndex = relative? oldIndex + x : x; - if (newIndex > maxIndex) { - newIndex = maxIndex; - } else if (newIndex < 0) { - newIndex = 0; - } - if (!sameThread || newIndex != oldIndex) { // don't recurse - setCurrentFrameIndex(tinfo, newIndex); - } - return newIndex - oldIndex; - } - - private void setCurrentFrameIndex(ThreadInfo tinfo, int index) { - tinfo.setUserObject(index); - //### In fact, the value may not have changed at this point. - //### We need to signal that the user attempted to change it, - //### however, so that the selection can be "warped" to the - //### current location. - notifyCurrentFrameChanged(tinfo.thread(), index); - } - - public StackFrame getCurrentFrame() throws VMNotInterruptedException { - return getCurrentFrame(runtime.threadInfo(currentThread)); - } - - public StackFrame getCurrentFrame(ThreadReference t) throws VMNotInterruptedException { - return getCurrentFrame(runtime.threadInfo(t)); - } - - public StackFrame getCurrentFrame(ThreadInfo tinfo) throws VMNotInterruptedException { - int index = getCurrentFrameIndex(tinfo); - try { - // It is possible, though unlikely, that the VM was interrupted - // before the thread created its Java stack. - return tinfo.getFrame(index); - } catch (FrameIndexOutOfBoundsException e) { - return null; - } - } - - public void addContextListener(ContextListener cl) { - contextListeners.add(cl); - } - - public void removeContextListener(ContextListener cl) { - contextListeners.remove(cl); - } - - //### These notifiers are fired only in response to USER-INITIATED changes - //### to the current thread and current frame. When the current thread is set automatically - //### after a breakpoint hit or step completion, no event is generated. Instead, - //### interested parties are expected to listen for the BreakpointHit and StepCompleted - //### events. This convention is unclean, and I believe that it reflects a defect in - //### in the current architecture. Unfortunately, however, we cannot guarantee the - //### order in which various listeners receive a given event, and the handlers for - //### the very same events that cause automatic changes to the current thread may also - //### need to know the current thread. - - private void notifyCurrentThreadChanged(ThreadReference t) { - ThreadInfo tinfo = null; - int index = 0; - if (t != null) { - tinfo = runtime.threadInfo(t); - index = getCurrentFrameIndex(tinfo); - } - notifyCurrentFrameChanged(tinfo, index, false); - } - - private void notifyCurrentFrameChanged(ThreadReference t, int index) { - notifyCurrentFrameChanged(runtime.threadInfo(t), - index, false); - } - - private void notifyCurrentFrameChanged(ThreadInfo tinfo, int index, - boolean invalidate) { - ArrayList l = new ArrayList(contextListeners); - CurrentFrameChangedEvent evt = - new CurrentFrameChangedEvent(this, tinfo, index, invalidate); - for (int i = 0; i < l.size(); i++) { - l.get(i).currentFrameChanged(evt); - } - } - - private class ContextManagerListener extends JDIAdapter - implements SessionListener, JDIListener { - - // SessionListener - - @Override - public void sessionStart(EventObject e) { - invalidateCurrentThread(); - } - - @Override - public void sessionInterrupt(EventObject e) { - setCurrentThreadInvalidate(currentThread); - } - - @Override - public void sessionContinue(EventObject e) { - invalidateCurrentThread(); - } - - // JDIListener - - @Override - public void locationTrigger(LocationTriggerEventSet e) { - setCurrentThreadInvalidate(e.getThread()); - } - - @Override - public void exception(ExceptionEventSet e) { - setCurrentThreadInvalidate(e.getThread()); - } - - @Override - public void vmDisconnect(VMDisconnectEventSet e) { - invalidateCurrentThread(); - } - - } - - - /** - * Add a -classpath argument to the arguments passed to the exec'ed - * VM with the contents of CLASSPATH environment variable, - * if -classpath was not already specified. - * - * @param javaArgs the arguments to the VM being exec'd that - * potentially has a user specified -classpath argument. - * @return a javaArgs whose -classpath option has been added - */ - - private String processClasspathDefaults(String javaArgs) { - if (javaArgs.indexOf("-classpath ") == -1) { - StringBuilder munged = new StringBuilder(javaArgs); - SearchPath classpath = classManager.getClassPath(); - if (classpath.isEmpty()) { - String envcp = System.getProperty("env.class.path"); - if ((envcp != null) && (envcp.length() > 0)) { - munged.append(" -classpath " + envcp); - } - } else { - munged.append(" -classpath " + classpath.asString()); - } - return munged.toString(); - } else { - return javaArgs; - } - } - - private String appendPath(String path1, String path2) { - if (path1 == null || path1.length() == 0) { - return path2 == null ? "." : path2; - } else if (path2 == null || path2.length() == 0) { - return path1; - } else { - return path1 + File.pathSeparator + path2; - } - } - -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/CurrentFrameChangedEvent.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/CurrentFrameChangedEvent.java deleted file mode 100644 index b933e758f38..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/CurrentFrameChangedEvent.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.gui; - -import com.sun.jdi.*; -import com.sun.tools.example.debug.bdi.*; -import java.util.EventObject; - -public class CurrentFrameChangedEvent extends EventObject { - - private static final long serialVersionUID = 4214479486546762179L; - private ThreadInfo tinfo; - private int index; - private boolean invalidate; - - public CurrentFrameChangedEvent(Object source, ThreadInfo tinfo, - int index, boolean invalidate) { - super(source); - this.tinfo = tinfo; - this.index = index; - this.invalidate = invalidate; - } - - public ThreadReference getThread() { - return tinfo == null? null : tinfo.thread(); - } - - public ThreadInfo getThreadInfo() { - return tinfo; - } - - public int getIndex() { - return index; - } - - public boolean getInvalidate() { - return invalidate; - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/Environment.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/Environment.java deleted file mode 100644 index b06ae4d6c79..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/Environment.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.gui; - -import java.io.*; -import com.sun.jdi.*; -import com.sun.tools.example.debug.bdi.*; - -public class Environment { - - private SourceManager sourceManager; - private ClassManager classManager; - private ContextManager contextManager; - private MonitorListModel monitorListModel; - private ExecutionManager runtime; - - private PrintWriter typeScript; - - private boolean verbose; - - public Environment() { - this.classManager = new ClassManager(this); - //### Order of the next three lines is important! (FIX THIS) - this.runtime = new ExecutionManager(); - this.sourceManager = new SourceManager(this); - this.contextManager = new ContextManager(this); - this.monitorListModel = new MonitorListModel(this); - } - - // Services used by debugging tools. - - public SourceManager getSourceManager() { - return sourceManager; - } - - public ClassManager getClassManager() { - return classManager; - } - - public ContextManager getContextManager() { - return contextManager; - } - - public MonitorListModel getMonitorListModel() { - return monitorListModel; - } - - public ExecutionManager getExecutionManager() { - return runtime; - } - - //### TODO: - //### Tools should attach/detach from environment - //### via a property, which should call an 'addTool' - //### method when set to maintain a registry of - //### tools for exit-time cleanup, etc. Tool - //### class constructors should be argument-free, so - //### that they may be instantiated by bean builders. - //### Will also need 'removeTool' in case property - //### value is changed. - // - // public void addTool(Tool t); - // public void removeTool(Tool t); - - public void terminate() { - System.exit(0); - } - - // public void refresh(); // notify all tools to refresh their views - - - // public void addStatusListener(StatusListener l); - // public void removeStatusListener(StatusListener l); - - // public void addOutputListener(OutputListener l); - // public void removeOutputListener(OutputListener l); - - public void setTypeScript(PrintWriter writer) { - typeScript = writer; - } - - public void error(String message) { - if (typeScript != null) { - typeScript.println(message); - } else { - System.out.println(message); - } - } - - public void failure(String message) { - if (typeScript != null) { - typeScript.println(message); - } else { - System.out.println(message); - } - } - - public void notice(String message) { - if (typeScript != null) { - typeScript.println(message); - } else { - System.out.println(message); - } - } - - public OutputSink getOutputSink() { - return new OutputSink(typeScript); - } - - public void viewSource(String fileName) { - //### HACK ### - //### Should use listener here. - com.sun.tools.example.debug.gui.GUI.srcTool.showSourceFile(fileName); - } - - public void viewLocation(Location locn) { - //### HACK ### - //### Should use listener here. - //### Should we use sourceForLocation here? - com.sun.tools.example.debug.gui.GUI.srcTool.showSourceForLocation(locn); - } - - //### Also in 'ContextManager'. Do we need both? - - public boolean getVerboseFlag() { - return verbose; - } - - public void setVerboseFlag(boolean verbose) { - this.verbose = verbose; - } - -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/GUI.java b/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/GUI.java deleted file mode 100644 index eefbcfa7b61..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/gui/GUI.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright (c) 1998, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.debug.gui; - -import java.io.*; -import javax.swing.*; -import javax.swing.border.*; -import java.awt.*; -import java.awt.event.*; - -import com.sun.jdi.*; -import com.sun.tools.example.debug.bdi.*; - -public class GUI extends JPanel { - - private static final long serialVersionUID = 3292463234530679091L; - private CommandTool cmdTool; - private ApplicationTool appTool; - //###HACK## - //### There is currently dirty code in Environment that - //### accesses this directly. - //private SourceTool srcTool; - public static SourceTool srcTool; - - private SourceTreeTool sourceTreeTool; - private ClassTreeTool classTreeTool; - private ThreadTreeTool threadTreeTool; - private StackTraceTool stackTool; - private MonitorTool monitorTool; - - public static final String progname = "javadt"; - public static final String version = "1.0Beta"; //### FIX ME. - public static final String windowBanner = "Java(tm) platform Debug Tool"; - - private Font fixedFont = new Font("monospaced", Font.PLAIN, 10); - - private GUI(Environment env) { - setLayout(new BorderLayout()); - - setBorder(new EmptyBorder(5, 5, 5, 5)); - - add(new JDBToolBar(env), BorderLayout.NORTH); - - srcTool = new SourceTool(env); - srcTool.setPreferredSize(new java.awt.Dimension(500, 300)); - srcTool.setTextFont(fixedFont); - - stackTool = new StackTraceTool(env); - stackTool.setPreferredSize(new java.awt.Dimension(500, 100)); - - monitorTool = new MonitorTool(env); - monitorTool.setPreferredSize(new java.awt.Dimension(500, 50)); - - JSplitPane right = new JSplitPane(JSplitPane.VERTICAL_SPLIT, srcTool, - new JSplitPane(JSplitPane.VERTICAL_SPLIT, stackTool, monitorTool)); - - sourceTreeTool = new SourceTreeTool(env); - sourceTreeTool.setPreferredSize(new java.awt.Dimension(200, 450)); - - classTreeTool = new ClassTreeTool(env); - classTreeTool.setPreferredSize(new java.awt.Dimension(200, 450)); - - threadTreeTool = new ThreadTreeTool(env); - threadTreeTool.setPreferredSize(new java.awt.Dimension(200, 450)); - - JTabbedPane treePane = new JTabbedPane(SwingConstants.BOTTOM); - treePane.addTab("Source", null, sourceTreeTool); - treePane.addTab("Classes", null, classTreeTool); - treePane.addTab("Threads", null, threadTreeTool); - - JSplitPane centerTop = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treePane, right); - - cmdTool = new CommandTool(env); - cmdTool.setPreferredSize(new java.awt.Dimension(700, 150)); - - appTool = new ApplicationTool(env); - appTool.setPreferredSize(new java.awt.Dimension(700, 200)); - - JSplitPane centerBottom = new JSplitPane(JSplitPane.VERTICAL_SPLIT, cmdTool, appTool); - // centerBottom.setPreferredSize(new java.awt.Dimension(700, 350)); - - JSplitPane center = new JSplitPane(JSplitPane.VERTICAL_SPLIT, centerTop, centerBottom); - - add(center, BorderLayout.CENTER); - - - } - - private static void usage() { - String separator = File.pathSeparator; - System.out.println("Usage: " + progname + " "); - System.out.println(); - System.out.println("where options include:"); - System.out.println(" -help print out this message and exit"); - System.out.println(" -sourcepath "); - System.out.println(" list directories in which to look for source files"); - System.out.println(" -remote :"); - System.out.println(" host machine and port number of interpreter to attach to"); - System.out.println(" -dbgtrace [flags] print info for debugging " + progname); - System.out.println(); - System.out.println("options forwarded to debuggee process:"); - System.out.println(" -v -verbose[:class|gc|jni]"); - System.out.println(" turn on verbose mode"); - System.out.println(" -D= set a system property"); - System.out.println(" -classpath "); - System.out.println(" list directories in which to look for classes"); - System.out.println(" -X

Example JDI Applications

-This example download contains the source code and -documentation for three applications written using -the JavaTM Debug Interface (JDI) -of the Java Platform Debugger Architecture (JPDA). -They are provided as educational tools and as starting -points for debugger development. -

-In increasing order of complexity: -

    -
  • Trace displays traces -of program execution. It is very simple (less than 600 lines) -yet uses most of the basic JDI functionality. It is a -good starting point. -
  • Jdb is the command line debugger -distributed with the J2SE SDK. -
  • Javadt is the beginnings of -a GUI debugger. -
-

-Trace is in the trace directory. -Jdb and Javadt share a package, and are under the -debug directory. - -

Required Set-up

- -

Where is JPDA?

-New versions of the J2SE SDK have JPDA included. For -older versions JPDA must be separately downloaded. -
-
SDKs with JPDA included -
J2SE SDK v1.3 and later and J2SE SDK for Linux v1.2.2 -
SDKs requiring JPDA download -
J2SE SDK v1.2.1 and v1.2.2 for Solaris and Windows -
Other SDKs -
Check with vendor -
-

-

Set-up for J2SE SDKs with JPDA included

-Your classpath must include the JDI Library code, which is -in tools.jar in the lib directory. -This is needed for both compiling the example code and -executing it. -

-

Set-up for J2SE SDKs without JPDA - Solaris

-Download JPDA v1.0 from -http://java.sun.com/products/jpda. Follow the -Installation Instructions -found there. Pay particular attention to setting the library -path. -

-Your classpath must include the JDI Library code, which is -in jpda_home/lib/tools.jar. -This is needed for both compiling the example code and -executing it. -

-

Set-up for J2SE SDKs without JPDA - Windows

-Download JPDA v1.0 from -http://java.sun.com/products/jpda. Follow the -Installation Instructions -found there. Be sure to add: -
-        jpda_home\bin
-
-to your path. -

-Your classpath must include the JDI Library code, which is -in jpda_home\lib\tools.jar. -This is needed for both compiling the example code and -executing it. -

-


-
java-debugger@java.sun.com
-

-

-

- - - diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/doc/javadt.html b/jdk/src/demo/share/jpda/com/sun/tools/example/doc/javadt.html deleted file mode 100644 index f9d28a166bb..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/doc/javadt.html +++ /dev/null @@ -1,174 +0,0 @@ - - - Release notes for the javadt debugger - - -

Release notes for the javadt debugger

- -

-As a demonstration of the - -JavaTM Platform Debugger Architecture -we are providing source code for -a simple GUI debugging tool - javadt. -It is included as an example and demonstration of - -JDI. It is not a finished or polished debugger and is -missing many features of importance for real debugging work. -

- -

Invoking javadt

-

-javadt can be run by executing: -

-   java com.sun.tools.example.debug.gui.GUI <options>.. <class-name>
-
-where <class-name> is the name you would normally -place on the java command line. -Note: the path to the JDI Library and to -the compiled javadt class files must be on the class path -used to invoke gui.GUI. -

-For example, you can invoke the javadt debugger as follows: -

-   java com.sun.tools.example.debug.gui.GUI -classpath . Hello
-
-Note: this -classpath option controls the -class path for the Hello application. -Once the window appears, you can issue the 'run' command to begin -execution immediately. It is also -possible to give the class name in the 'run' command, in -which case it may be omitted when invoking the debugger from the -shell. -

-The classpath may also be set from within the debugger, using the -'classpath' command. Currently, other arguments to the VM must be -given on the shell command line when the debugger is initially -invoked. The most recently mentioned classpath, VM arguments, main -class name, and program arguments are retained as defaults for later -'run' and 'load' commands. (Unfortunately, at present, the debugger -will likely crash if you attempt to begin another debugging session -with another debuggee process from within the same invocation of the -debugger. You should exit to the shell and start a new debugger -process.) -

- -

Using javadt

-The javadt normally displays context related to the "current thread", -that is, the thread that most recently encountered a breakpoint, threw -an uncaught exception, or was single-stepped by the user. When -program execution is suspended on account of one of these events, a -current thread exists, and the javadt displays the following information -about it: -

-

    -
  • A stack backtrace. - -
  • The source code surrounding the line corresponding to the - instruction counter for the thread, if the source code is - available. -
-

-In addition, a tabbed pane allows the user to view one of three -additional views: -

-

    -
  • A tree of all source files available on the source path. - -
  • A tree of all loaded class files, organized hierarchically - by package. - -
  • A tree of all active threads, organized hierarchically - by thread group. -
-

-By clicking on the name of a source file, the source view can be -directed to display it. Likewise, clicking on a thread will make that -thread the current thread. These features are normally used while the -program is suspended, e.g, at a breakpoint. Upon resumption and -encountering another breakpoint, for example, the current thread will -be automatically reset and the views will be updated. The views tile -the javadt display, and are adjustable in size. -

-The javadt functionality is rather basic, thus a command-line interaction -window is also provided that allows access to functions that are not -yet exposed in the javadt. In particular, it is necessary to use the -command line in order to set breakpoints and examine variables. The -javadt debugger command interpreter implements roughly a subset of the -jdb - functionality, but adds a few commands of its own. The -'help' command lists the complete set of commands and their function. -Shortcuts for a set of the most common commands is provided on a -button-bar at the top of the display. -

-The program to be debugged may be started either as a child of the -debugger, or the debugger can be attached to an existing process, -provided that its VM is prepared to accept the connection. If the -debuggee is started by the debugger as a child, a line-oriented -interface to its standard input, output, and error streams is provided -in an application interaction pane. -

-The debugger expects to find the program source code on its -sourcepath, set with the 'use' or 'sourcepath' command. If you find -that sources are not being displayed because the sourcepath is -incorrect, you may change it at that time, and the source view will be -immediately updated. -

-The message "No current thread" is often encountered when stepping -through a program. This message does not mean that the thread or -the VM has died, merely that a current thread is undefined. This -situation can easily occur unexpectedly when the program being -stepped is waiting, eg., for input. The VM appears to be stopped, -as it would be after the successful completion of a step, but it -is considered to be "running", not "interrupted". The prompt -in the command interaction pane indicates the state by changing -to a thread name and frame number when the VM is interrupted. -When it is running, the prompt "Command:" is displayed. -

-

Source for javadt

-Full source code for javadt is included under the -debug directory of examples.jar. -Note: these directories also include the -source for jdb. -Source code for these example applications is included to provide concrete -examples for debugger developers. Example code may be used, modified -and redistributed by debugger developers providing they adhere to the -terms in the COPYRIGHT notice. -

-javadt uses the following packages (found under the -debug directory): -

-
gui -
User interface code -
bdi -
Debugger core code -
events -
Event Set code -
expr -
Expression processing code -
-

-

Building javadt

-To build the javadt classes from the -provided source files under the debug directory, -you need only to compile them. No special -options are required, aside from those which set your classpath to -include the JDI Library. -

-

-However, if you want to modify the expression parser in the file -Expr.jj, you will need the - -JavaCC parser generator. -It is available free from -Metamata -(now part of WebGain). -

-


-
java-debugger@java.sun.com
-

-

-

- - diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/doc/jdb.html b/jdk/src/demo/share/jpda/com/sun/tools/example/doc/jdb.html deleted file mode 100644 index a8232b0207d..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/doc/jdb.html +++ /dev/null @@ -1,104 +0,0 @@ - - - Release notes for the jdb debugger - - -  - - - - - -
-
-

Release notes for the jdb debugger

-
- -

-Home Page - -

-As a demonstration of the - -JavaTM Platform Debugger Architecture -we are providing source code for the jdb debugger, which was -re-written to use - -JDI. - -

-

jdb man pages

-
-jdb man pages for Windows -

-jdb man pages for Solaris -

-

-

Invoking jdb

-The jdb sample can be started by executing: -
-   java com.sun.tools.example.debug.tty.TTY <options>.. <class-name>
-
-where <class-name> is the name you would normally -place on the java command line. The -help -option provides information on options. -

-

-Note: the path to the JDI Library and to -the compiled jdb class files must be on the class path -used to invoke com.sun.tools.example.debug.tty.TTY. - -

-For more information on invoking and connecting, refer to the - -Connection and Invocation Details section of the - -JPDA documentation, -particularly the section on jdb. -

- - -

Source for jdb

-Full source code for jdb is included under the -debug directory of examples.jar. -Note: these directories also include the -source for javadt. -Source code for these example applications is included to provide concrete -examples for debugger developers. Example code may be used, modified -and redistributed by debugger developers providing they adhere to the -terms in the COPYRIGHT notice. -

-jdb uses the following packages (found under the -debug directory): -

-
tty -
Application code -
expr -
Expression processing code -
- -

-

Building jdb

-To completely rebuild the jdb classes from the -provided source files under the debug directory, -you need only to compile them. No special -options are required, aside from those which set your classpath to -include the JDI Library. -

-

-However, if you want to modify the expression parser in the file -Expr.jj, you will need the - -JavaCC parser generator. -It is available free from -Metamata -(now part of WebGain). -

-


-
java-debugger@java.sun.com
-

-

-

- - diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/doc/trace.html b/jdk/src/demo/share/jpda/com/sun/tools/example/doc/trace.html deleted file mode 100644 index 8cae84dfe1e..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/doc/trace.html +++ /dev/null @@ -1,71 +0,0 @@ - - - - trace example - - -

trace example

- -Trace runs the Java language program passed as an argument and -generates a trace of its execution. Trace is a simple command -line tool that uses the - -Java Debug Interface (JDI). Programs need -not be compiled for debugging since this information is not -used. -

-Trace can be invoked as follows: -

-        java com.sun.tools.example.trace.Trace options class args
-
-Your classpath must include the JDI Library -(see set-up), -the path to the compiled trace class files, -and the path for the application being traced. -

-Available options are: - -

-  -output filename   
-        Set destination for output trace. By default output
-        goes to the terminal.
-
-  -all                 
-        Include system classes in output.  By default
-        java.*, javax.*, sun.* and com.sun.* events are
-        not diplayed.
-
-  -fields
-        Also show assignments into fields.
-
-  -help              
-        Print a help message
-
-
-class is the program to trace. args are the arguments to class. -

- -

Source for trace

-Full source code for trace is included in the -trace directory of examples.jar. -Source code for these example applications is included to provide concrete -examples for debugger developers. Example code may be used, modified -and redistributed by debugger developers providing they adhere to the -terms in the COPYRIGHT notice. - -

-

Building trace

-To completely rebuild the trace classes from the -provided source files in the trace directory, -you need only to compile them. No special -options are required, aside from those which set your classpath to -include the JDI Library. - -

-


-
java-debugger@java.sun.com
-

-

-

- - diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/trace/EventThread.java b/jdk/src/demo/share/jpda/com/sun/tools/example/trace/EventThread.java deleted file mode 100644 index 11084df5dd2..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/trace/EventThread.java +++ /dev/null @@ -1,353 +0,0 @@ -/* - * Copyright (c) 2001, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.trace; - -import com.sun.jdi.*; -import com.sun.jdi.request.*; -import com.sun.jdi.event.*; - -import java.util.*; -import java.io.PrintWriter; - -/** - * This class processes incoming JDI events and displays them - * - * @author Robert Field - */ -public class EventThread extends Thread { - - private final VirtualMachine vm; // Running VM - private final String[] excludes; // Packages to exclude - private final PrintWriter writer; // Where output goes - - static String nextBaseIndent = ""; // Starting indent for next thread - - private boolean connected = true; // Connected to VM - private boolean vmDied = true; // VMDeath occurred - - // Maps ThreadReference to ThreadTrace instances - private Map traceMap = - new HashMap<>(); - - EventThread(VirtualMachine vm, String[] excludes, PrintWriter writer) { - super("event-handler"); - this.vm = vm; - this.excludes = excludes; - this.writer = writer; - } - - /** - * Run the event handling thread. - * As long as we are connected, get event sets off - * the queue and dispatch the events within them. - */ - @Override - public void run() { - EventQueue queue = vm.eventQueue(); - while (connected) { - try { - EventSet eventSet = queue.remove(); - EventIterator it = eventSet.eventIterator(); - while (it.hasNext()) { - handleEvent(it.nextEvent()); - } - eventSet.resume(); - } catch (InterruptedException exc) { - // Ignore - } catch (VMDisconnectedException discExc) { - handleDisconnectedException(); - break; - } - } - } - - /** - * Create the desired event requests, and enable - * them so that we will get events. - * @param excludes Class patterns for which we don't want events - * @param watchFields Do we want to watch assignments to fields - */ - void setEventRequests(boolean watchFields) { - EventRequestManager mgr = vm.eventRequestManager(); - - // want all exceptions - ExceptionRequest excReq = mgr.createExceptionRequest(null, - true, true); - // suspend so we can step - excReq.setSuspendPolicy(EventRequest.SUSPEND_ALL); - excReq.enable(); - - MethodEntryRequest menr = mgr.createMethodEntryRequest(); - for (int i=0; i 0) { - indent.append("| "); - } - - EventRequestManager mgr = vm.eventRequestManager(); - mgr.deleteEventRequest(event.request()); - } - - void threadDeathEvent(ThreadDeathEvent event) { - indent = new StringBuffer(baseIndent); - println("====== " + thread.name() + " end ======"); - } - } - - /** - * Returns the ThreadTrace instance for the specified thread, - * creating one if needed. - */ - ThreadTrace threadTrace(ThreadReference thread) { - ThreadTrace trace = traceMap.get(thread); - if (trace == null) { - trace = new ThreadTrace(thread); - traceMap.put(thread, trace); - } - return trace; - } - - /** - * Dispatch incoming events - */ - private void handleEvent(Event event) { - if (event instanceof ExceptionEvent) { - exceptionEvent((ExceptionEvent)event); - } else if (event instanceof ModificationWatchpointEvent) { - fieldWatchEvent((ModificationWatchpointEvent)event); - } else if (event instanceof MethodEntryEvent) { - methodEntryEvent((MethodEntryEvent)event); - } else if (event instanceof MethodExitEvent) { - methodExitEvent((MethodExitEvent)event); - } else if (event instanceof StepEvent) { - stepEvent((StepEvent)event); - } else if (event instanceof ThreadDeathEvent) { - threadDeathEvent((ThreadDeathEvent)event); - } else if (event instanceof ClassPrepareEvent) { - classPrepareEvent((ClassPrepareEvent)event); - } else if (event instanceof VMStartEvent) { - vmStartEvent((VMStartEvent)event); - } else if (event instanceof VMDeathEvent) { - vmDeathEvent((VMDeathEvent)event); - } else if (event instanceof VMDisconnectEvent) { - vmDisconnectEvent((VMDisconnectEvent)event); - } else { - throw new Error("Unexpected event type"); - } - } - - /*** - * A VMDisconnectedException has happened while dealing with - * another event. We need to flush the event queue, dealing only - * with exit events (VMDeath, VMDisconnect) so that we terminate - * correctly. - */ - synchronized void handleDisconnectedException() { - EventQueue queue = vm.eventQueue(); - while (connected) { - try { - EventSet eventSet = queue.remove(); - EventIterator iter = eventSet.eventIterator(); - while (iter.hasNext()) { - Event event = iter.nextEvent(); - if (event instanceof VMDeathEvent) { - vmDeathEvent((VMDeathEvent)event); - } else if (event instanceof VMDisconnectEvent) { - vmDisconnectEvent((VMDisconnectEvent)event); - } - } - eventSet.resume(); // Resume the VM - } catch (InterruptedException exc) { - // ignore - } - } - } - - private void vmStartEvent(VMStartEvent event) { - writer.println("-- VM Started --"); - } - - // Forward event for thread specific processing - private void methodEntryEvent(MethodEntryEvent event) { - threadTrace(event.thread()).methodEntryEvent(event); - } - - // Forward event for thread specific processing - private void methodExitEvent(MethodExitEvent event) { - threadTrace(event.thread()).methodExitEvent(event); - } - - // Forward event for thread specific processing - private void stepEvent(StepEvent event) { - threadTrace(event.thread()).stepEvent(event); - } - - // Forward event for thread specific processing - private void fieldWatchEvent(ModificationWatchpointEvent event) { - threadTrace(event.thread()).fieldWatchEvent(event); - } - - void threadDeathEvent(ThreadDeathEvent event) { - ThreadTrace trace = traceMap.get(event.thread()); - if (trace != null) { // only want threads we care about - trace.threadDeathEvent(event); // Forward event - } - } - - /** - * A new class has been loaded. - * Set watchpoints on each of its fields - */ - private void classPrepareEvent(ClassPrepareEvent event) { - EventRequestManager mgr = vm.eventRequestManager(); - List fields = event.referenceType().visibleFields(); - for (Field field : fields) { - ModificationWatchpointRequest req = - mgr.createModificationWatchpointRequest(field); - for (int i=0; i= 0) { - out.write(cbuf, 0, count); - } - out.flush(); - } catch(IOException exc) { - System.err.println("Child I/O Transfer - " + exc); - } - } -} diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/trace/Trace.java b/jdk/src/demo/share/jpda/com/sun/tools/example/trace/Trace.java deleted file mode 100644 index 2ce99f97a01..00000000000 --- a/jdk/src/demo/share/jpda/com/sun/tools/example/trace/Trace.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright (c) 2001, 2011, 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. - */ - -/* - * 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. - */ - - -package com.sun.tools.example.trace; - -import com.sun.jdi.VirtualMachine; -import com.sun.jdi.Bootstrap; -import com.sun.jdi.connect.*; - -import java.util.Map; -import java.util.List; - -import java.io.PrintWriter; -import java.io.FileWriter; -import java.io.IOException; - -/** - * This program traces the execution of another program. - * See "java Trace -help". - * It is a simple example of the use of the Java Debug Interface. - * - * @author Robert Field - */ -public class Trace { - - // Running remote VM - private final VirtualMachine vm; - - // Thread transferring remote error stream to our error stream - private Thread errThread = null; - - // Thread transferring remote output stream to our output stream - private Thread outThread = null; - - // Mode for tracing the Trace program (default= 0 off) - private int debugTraceMode = 0; - - // Do we want to watch assignments to fields - private boolean watchFields = false; - - // Class patterns for which we don't want events - private String[] excludes = {"java.*", "javax.*", "sun.*", - "com.sun.*"}; - - /** - * main - */ - public static void main(String[] args) { - new Trace(args); - } - - /** - * Parse the command line arguments. - * Launch target VM. - * Generate the trace. - */ - Trace(String[] args) { - PrintWriter writer = new PrintWriter(System.out); - int inx; - for (inx = 0; inx < args.length; ++inx) { - String arg = args[inx]; - if (arg.charAt(0) != '-') { - break; - } - if (arg.equals("-output")) { - try { - writer = new PrintWriter(new FileWriter(args[++inx])); - } catch (IOException exc) { - System.err.println("Cannot open output file: " + args[inx] - + " - " + exc); - System.exit(1); - } - } else if (arg.equals("-all")) { - excludes = new String[0]; - } else if (arg.equals("-fields")) { - watchFields = true; - } else if (arg.equals("-dbgtrace")) { - debugTraceMode = Integer.parseInt(args[++inx]); - } else if (arg.equals("-help")) { - usage(); - System.exit(0); - } else { - System.err.println("No option: " + arg); - usage(); - System.exit(1); - } - } - if (inx >= args.length) { - System.err.println(" missing"); - usage(); - System.exit(1); - } - StringBuilder sb = new StringBuilder(); - sb.append(args[inx]); - for (++inx; inx < args.length; ++inx) { - sb.append(' '); - sb.append(args[inx]); - } - vm = launchTarget(sb.toString()); - generateTrace(writer); - } - - - /** - * Generate the trace. - * Enable events, start thread to display events, - * start threads to forward remote error and output streams, - * resume the remote VM, wait for the final event, and shutdown. - */ - void generateTrace(PrintWriter writer) { - vm.setDebugTraceMode(debugTraceMode); - EventThread eventThread = new EventThread(vm, excludes, writer); - eventThread.setEventRequests(watchFields); - eventThread.start(); - redirectOutput(); - vm.resume(); - - // Shutdown begins when event thread terminates - try { - eventThread.join(); - errThread.join(); // Make sure output is forwarded - outThread.join(); // before we exit - } catch (InterruptedException exc) { - // we don't interrupt - } - writer.close(); - } - - /** - * Launch target VM. - * Forward target's output and error. - */ - VirtualMachine launchTarget(String mainArgs) { - LaunchingConnector connector = findLaunchingConnector(); - Map arguments = - connectorArguments(connector, mainArgs); - try { - return connector.launch(arguments); - } catch (IOException exc) { - throw new Error("Unable to launch target VM: " + exc); - } catch (IllegalConnectorArgumentsException exc) { - throw new Error("Internal error: " + exc); - } catch (VMStartException exc) { - throw new Error("Target VM failed to initialize: " + - exc.getMessage()); - } - } - - void redirectOutput() { - Process process = vm.process(); - - // Copy target's output and error to our output and error. - errThread = new StreamRedirectThread("error reader", - process.getErrorStream(), - System.err); - outThread = new StreamRedirectThread("output reader", - process.getInputStream(), - System.out); - errThread.start(); - outThread.start(); - } - - /** - * Find a com.sun.jdi.CommandLineLaunch connector - */ - LaunchingConnector findLaunchingConnector() { - List connectors = Bootstrap.virtualMachineManager().allConnectors(); - for (Connector connector : connectors) { - if (connector.name().equals("com.sun.jdi.CommandLineLaunch")) { - return (LaunchingConnector)connector; - } - } - throw new Error("No launching connector"); - } - - /** - * Return the launching connector's arguments. - */ - Map connectorArguments(LaunchingConnector connector, String mainArgs) { - Map arguments = connector.defaultArguments(); - Connector.Argument mainArg = - (Connector.Argument)arguments.get("main"); - if (mainArg == null) { - throw new Error("Bad launching connector"); - } - mainArg.setValue(mainArgs); - - if (watchFields) { - // We need a VM that supports watchpoints - Connector.Argument optionArg = - (Connector.Argument)arguments.get("options"); - if (optionArg == null) { - throw new Error("Bad launching connector"); - } - optionArg.setValue("-classic"); - } - return arguments; - } - - /** - * Print command line usage help - */ - void usage() { - System.err.println("Usage: java Trace "); - System.err.println(" are:"); - System.err.println( -" -output Output trace to "); - System.err.println( -" -all Include system classes in output"); - System.err.println( -" -help Print this help message"); - System.err.println(" is the program to trace"); - System.err.println(" are the arguments to "); - } -} diff --git a/jdk/src/demo/share/jvmti/hprof/sample.makefile.txt b/jdk/src/demo/share/jvmti/hprof/sample.makefile.txt deleted file mode 100644 index e8f84dc8577..00000000000 --- a/jdk/src/demo/share/jvmti/hprof/sample.makefile.txt +++ /dev/null @@ -1,205 +0,0 @@ -# -# Copyright (c) 2004, 2012, 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= OSNAME=solaris [OPT=true] [LIBARCH=sparc] -# gnumake JDK= OSNAME=solaris [OPT=true] [LIBARCH=sparcv9] -# gnumake JDK= OSNAME=linux [OPT=true] -# gnumake JDK= OSNAME=win32 [OPT=true] -# -######################################################################## - -# Source lists -LIBNAME=hprof -SOURCES= \ - debug_malloc.c \ - hprof_blocks.c \ - hprof_class.c \ - hprof_cpu.c \ - hprof_error.c \ - hprof_event.c \ - hprof_frame.c \ - hprof_init.c \ - hprof_io.c \ - hprof_ioname.c \ - hprof_listener.c \ - hprof_loader.c \ - hprof_monitor.c \ - hprof_object.c \ - hprof_reference.c \ - hprof_site.c \ - hprof_stack.c \ - hprof_string.c \ - hprof_table.c \ - hprof_tag.c \ - hprof_tls.c \ - hprof_trace.c \ - hprof_tracker.c \ - hprof_util.c \ - hprof_md.c - -JAVA_SOURCES=Tracker.java - -# Name of jar file that needs to be created -#JARFILE=hprof.jar - -# Solaris Sun C Compiler Version 5.5 -ifeq ($(OSNAME), solaris) - # Sun Solaris Compiler options needed - COMMON_FLAGS=-mt -KPIC - # Options that help find errors - COMMON_FLAGS+= -Xa -v -xstrconst -xc99=%none - # To make hprof logging code available - COMMON_FLAGS+= -DHPROF_LOGGING - # 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) -DNDEBUG - else - CFLAGS=-g $(COMMON_FLAGS) -DDEBUG - 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=-lsocket -lnsl -ldl -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 - # To allow access to dladdr() - COMMON_FLAGS+= -D_GNU_SOURCE - # To prevent include of procfs.h - COMMON_FLAGS+= -DLINUX - # To make sure code is reentrant - COMMON_FLAGS+= -D_REENTRANT - # To make hprof logging code available - COMMON_FLAGS+= -DHPROF_LOGGING - ifeq ($(OPT), true) - CFLAGS=-O2 $(COMMON_FLAGS) -DNDEBUG - else - CFLAGS=-g $(COMMON_FLAGS) -DDEBUG - 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= -ldl -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 - # To make hprof logging code available - COMMON_FLAGS+= -DHPROF_LOGGING - ifeq ($(OPT), true) - CFLAGS= -Ox -Op -Zi $(COMMON_FLAGS) -DNDEBUG - else - CFLAGS= -Od -Zi $(COMMON_FLAGS) -DDEBUG - endif - # Add java_crw_demo source - SOURCES += ../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=wsock32.lib winmm.lib - # Building a shared library - LINK_SHARED=link -dll -out:$@ -endif - -# Common -I options -CFLAGS += -I. -CFLAGS += -I../java_crw_demo -CFLAGS += -I$(JDK)/include -I$(JDK)/include/$(OSNAME) - -# Default rule (build both native library and jar file) -all: hprof_md.c $(LIBRARY) $(JARFILE) - -# Get platform specific hprof_md.c -hprof_md.c: - rm -f $@ - cp $(OSNAME)/hprof_md.c $@ - -# 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 - diff --git a/jdk/src/demo/share/jvmti/index.html b/jdk/src/demo/share/jvmti/index.html index b66ac8d9bfa..4b479c12468 100644 --- a/jdk/src/demo/share/jvmti/index.html +++ b/jdk/src/demo/share/jvmti/index.html @@ -54,17 +54,16 @@ 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 hprof (heap/cpu profiler) and jdwp (debugger backend) +Some agents such as the jdwp (debugger backend) are located inside the primary JDK directories and will always be found in those locations.

The agents that instrument classfiles (i.e. BCI, usually through the java_crw_demo library) -such as hprof, heapTracker, mtrace, and minst, +such as heapTracker, mtrace, and minst, also need to have the Java classes they use available in the bootclasspath. -The one used by hprof is already in the bootclasspath, and the -other agents will make attempts at automatically adding their jar file +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). @@ -150,19 +149,6 @@ This is a small agent that gets information about threads waiting on monitors. -

  • -hprof -
    -This is a large agent that does heap and cpu profiling. -This demo agent is actually built into the - -Java Runtime Environment (JRE). -It uses Bytecode Instrumentation (BCI) via the java_crw_demo library. -
    -Note: hprof is NOT a small or simple agent, the other smaller demos -should be looked at first. -
  • - diff --git a/jdk/src/java.base/share/classes/java/io/ByteArrayOutputStream.java b/jdk/src/java.base/share/classes/java/io/ByteArrayOutputStream.java index 71be2db3b47..3d199579249 100644 --- a/jdk/src/java.base/share/classes/java/io/ByteArrayOutputStream.java +++ b/jdk/src/java.base/share/classes/java/io/ByteArrayOutputStream.java @@ -93,6 +93,14 @@ public class ByteArrayOutputStream extends OutputStream { grow(minCapacity); } + /** + * The maximum size of array to allocate. + * Some VMs reserve some header words in an array. + * Attempts to allocate larger arrays may result in + * OutOfMemoryError: Requested array size exceeds VM limit + */ + private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; + /** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. @@ -105,14 +113,19 @@ public class ByteArrayOutputStream extends OutputStream { int newCapacity = oldCapacity << 1; if (newCapacity - minCapacity < 0) newCapacity = minCapacity; - if (newCapacity < 0) { - if (minCapacity < 0) // overflow - throw new OutOfMemoryError(); - newCapacity = Integer.MAX_VALUE; - } + if (newCapacity - MAX_ARRAY_SIZE > 0) + newCapacity = hugeCapacity(minCapacity); buf = Arrays.copyOf(buf, newCapacity); } + private static int hugeCapacity(int minCapacity) { + if (minCapacity < 0) // overflow + throw new OutOfMemoryError(); + return (minCapacity > MAX_ARRAY_SIZE) ? + Integer.MAX_VALUE : + MAX_ARRAY_SIZE; + } + /** * Writes the specified byte to this byte array output stream. * diff --git a/jdk/src/java.base/share/classes/java/io/FilePermission.java b/jdk/src/java.base/share/classes/java/io/FilePermission.java index 0744ea28e4a..b008d4f933a 100644 --- a/jdk/src/java.base/share/classes/java/io/FilePermission.java +++ b/jdk/src/java.base/share/classes/java/io/FilePermission.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -31,6 +31,7 @@ import java.util.List; import java.util.ArrayList; import java.util.Vector; import java.util.Collections; +import java.util.StringJoiner; import sun.security.util.SecurityConstants; /** @@ -556,39 +557,25 @@ public final class FilePermission extends Permission implements Serializable { * @return the canonical string representation of the actions. */ private static String getActions(int mask) { - StringBuilder sb = new StringBuilder(); - boolean comma = false; + StringJoiner sj = new StringJoiner(","); if ((mask & READ) == READ) { - comma = true; - sb.append("read"); + sj.add("read"); } - if ((mask & WRITE) == WRITE) { - if (comma) sb.append(','); - else comma = true; - sb.append("write"); + sj.add("write"); } - if ((mask & EXECUTE) == EXECUTE) { - if (comma) sb.append(','); - else comma = true; - sb.append("execute"); + sj.add("execute"); } - if ((mask & DELETE) == DELETE) { - if (comma) sb.append(','); - else comma = true; - sb.append("delete"); + sj.add("delete"); } - if ((mask & READLINK) == READLINK) { - if (comma) sb.append(','); - else comma = true; - sb.append("readlink"); + sj.add("readlink"); } - return sb.toString(); + return sj.toString(); } /** diff --git a/jdk/src/java.base/share/classes/java/io/ObjectOutputStream.java b/jdk/src/java.base/share/classes/java/io/ObjectOutputStream.java index 7dc6dde469f..e99e0257f31 100644 --- a/jdk/src/java.base/share/classes/java/io/ObjectOutputStream.java +++ b/jdk/src/java.base/share/classes/java/io/ObjectOutputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -32,6 +32,7 @@ import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.StringJoiner; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static java.io.ObjectStreamClass.processQueue; @@ -2465,15 +2466,11 @@ public class ObjectOutputStream * Returns a string representation of this object */ public String toString() { - StringBuilder buffer = new StringBuilder(); - if (!stack.isEmpty()) { - for(int i = stack.size(); i > 0; i-- ) { - buffer.append(stack.get(i - 1)); - if (i != 1) - buffer.append('\n'); - } + StringJoiner sj = new StringJoiner("\n"); + for (int i = stack.size() - 1; i >= 0; i--) { + sj.add(stack.get(i)); } - return buffer.toString(); + return sj.toString(); } } diff --git a/jdk/src/java.base/share/classes/java/lang/Class.java b/jdk/src/java.base/share/classes/java/lang/Class.java index 1afbf5ea710..2179ee809f5 100644 --- a/jdk/src/java.base/share/classes/java/lang/Class.java +++ b/jdk/src/java.base/share/classes/java/lang/Class.java @@ -54,6 +54,7 @@ import java.util.Set; import java.util.Map; import java.util.HashMap; import java.util.Objects; +import java.util.StringJoiner; import sun.misc.Unsafe; import sun.reflect.CallerSensitive; import sun.reflect.ConstantPool; @@ -3141,19 +3142,14 @@ public final class Class implements java.io.Serializable, private native Class[] getDeclaredClasses0(); private static String argumentTypesToString(Class[] argTypes) { - StringBuilder buf = new StringBuilder(); - buf.append("("); + StringJoiner sj = new StringJoiner(", ", "(", ")"); if (argTypes != null) { for (int i = 0; i < argTypes.length; i++) { - if (i > 0) { - buf.append(", "); - } Class c = argTypes[i]; - buf.append((c == null) ? "null" : c.getName()); + sj.add((c == null) ? "null" : c.getName()); } } - buf.append(")"); - return buf.toString(); + return sj.toString(); } /** use serialVersionUID from JDK 1.1 for interoperability */ diff --git a/jdk/src/java.base/share/classes/java/lang/invoke/MethodType.java b/jdk/src/java.base/share/classes/java/lang/invoke/MethodType.java index c26460048b0..2b20ae71935 100644 --- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodType.java +++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodType.java @@ -33,6 +33,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.StringJoiner; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; import sun.invoke.util.BytecodeDescriptor; @@ -717,15 +718,12 @@ class MethodType implements java.io.Serializable { */ @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("("); + StringJoiner sj = new StringJoiner(",", "(", + ")" + rtype.getSimpleName()); for (int i = 0; i < ptypes.length; i++) { - if (i > 0) sb.append(","); - sb.append(ptypes[i].getSimpleName()); + sj.add(ptypes[i].getSimpleName()); } - sb.append(")"); - sb.append(rtype.getSimpleName()); - return sb.toString(); + return sj.toString(); } diff --git a/jdk/src/java.base/share/classes/java/net/NetPermission.java b/jdk/src/java.base/share/classes/java/net/NetPermission.java index 9178f348723..dad3fb99f32 100644 --- a/jdk/src/java.base/share/classes/java/net/NetPermission.java +++ b/jdk/src/java.base/share/classes/java/net/NetPermission.java @@ -72,10 +72,10 @@ import java.util.StringTokenizer; * * * - * getNetworkInformation - * The ability to retrieve all information about local network interfaces. - * Malicious code can read information about network hardware such as - * MAC addresses, which could be used to construct local IPv6 addresses. + * getNetworkInformation + * The ability to retrieve all information about local network interfaces. + * Malicious code can read information about network hardware such as + * MAC addresses, which could be used to construct local IPv6 addresses. * * * @@ -98,8 +98,8 @@ import java.util.StringTokenizer; * * requestPasswordAuthentication * The ability - * to ask the authenticator registered with the system for - * a password + * to ask the authenticator registered with the system for + * a password * Malicious code may steal this password. * * @@ -116,11 +116,11 @@ import java.util.StringTokenizer; * * setDefaultAuthenticator * The ability to set the - * way authentication information is retrieved when - * a proxy or HTTP server asks for authentication + * way authentication information is retrieved when + * a proxy or HTTP server asks for authentication * Malicious - * code can set an authenticator that monitors and steals user - * authentication input as it retrieves the input from the user. + * code can set an authenticator that monitors and steals user + * authentication input as it retrieves the input from the user. * * * @@ -143,13 +143,13 @@ import java.util.StringTokenizer; * * specifyStreamHandler * The ability - * to specify a stream handler when constructing a URL + * to specify a stream handler when constructing a URL * Malicious code may create a URL with resources that it would -normally not have access to (like file:/foo/fum/), specifying a -stream handler that gets the actual bytes from someplace it does -have access to. Thus it might be able to trick the system into -creating a ProtectionDomain/CodeSource for a class even though -that class really didn't come from that location. + * normally not have access to (like file:/foo/fum/), specifying a + * stream handler that gets the actual bytes from someplace it does + * have access to. Thus it might be able to trick the system into + * creating a ProtectionDomain/CodeSource for a class even though + * that class really didn't come from that location. * * * diff --git a/jdk/src/java.base/share/classes/java/net/SocketPermission.java b/jdk/src/java.base/share/classes/java/net/SocketPermission.java index 1f3248077be..8894152512b 100644 --- a/jdk/src/java.base/share/classes/java/net/SocketPermission.java +++ b/jdk/src/java.base/share/classes/java/net/SocketPermission.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -30,6 +30,7 @@ import java.util.Vector; import java.util.List; import java.util.ArrayList; import java.util.Collections; +import java.util.StringJoiner; import java.util.StringTokenizer; import java.net.InetAddress; import java.security.Permission; @@ -1112,36 +1113,21 @@ public final class SocketPermission extends Permission * @param mask a specific integer action mask to translate into a string * @return the canonical string representation of the actions */ - private static String getActions(int mask) - { - StringBuilder sb = new StringBuilder(); - boolean comma = false; - + private static String getActions(int mask) { + StringJoiner sj = new StringJoiner(","); if ((mask & CONNECT) == CONNECT) { - comma = true; - sb.append("connect"); + sj.add("connect"); } - if ((mask & LISTEN) == LISTEN) { - if (comma) sb.append(','); - else comma = true; - sb.append("listen"); + sj.add("listen"); } - if ((mask & ACCEPT) == ACCEPT) { - if (comma) sb.append(','); - else comma = true; - sb.append("accept"); + sj.add("accept"); } - - if ((mask & RESOLVE) == RESOLVE) { - if (comma) sb.append(','); - else comma = true; - sb.append("resolve"); + sj.add("resolve"); } - - return sb.toString(); + return sj.toString(); } /** diff --git a/jdk/src/java.base/share/classes/java/net/URLClassLoader.java b/jdk/src/java.base/share/classes/java/net/URLClassLoader.java index e448a120bdc..6f4691404c3 100644 --- a/jdk/src/java.base/share/classes/java/net/URLClassLoader.java +++ b/jdk/src/java.base/share/classes/java/net/URLClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -407,6 +407,29 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { return pkg; } + // Also called by VM to define Package for classes loaded from the CDS + // archive + private void definePackageInternal(String pkgname, Manifest man, URL url) + { + if (getAndVerifyPackage(pkgname, man, url) == null) { + try { + if (man != null) { + definePackage(pkgname, man, url); + } else { + definePackage(pkgname, null, null, null, null, null, null, null); + } + } catch (IllegalArgumentException iae) { + // parallel-capable class loaders: re-verify in case of a + // race condition + if (getAndVerifyPackage(pkgname, man, url) == null) { + // Should never happen + throw new AssertionError("Cannot find package " + + pkgname); + } + } + } + } + /* * Defines a Class using the class bytes obtained from the specified * Resource. The resulting Class must be resolved before it can be @@ -420,23 +443,7 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { String pkgname = name.substring(0, i); // Check if package already loaded. Manifest man = res.getManifest(); - if (getAndVerifyPackage(pkgname, man, url) == null) { - try { - if (man != null) { - definePackage(pkgname, man, url); - } else { - definePackage(pkgname, null, null, null, null, null, null, null); - } - } catch (IllegalArgumentException iae) { - // parallel-capable class loaders: re-verify in case of a - // race condition - if (getAndVerifyPackage(pkgname, man, url) == null) { - // Should never happen - throw new AssertionError("Cannot find package " + - pkgname); - } - } - } + definePackageInternal(pkgname, man, url); } // Now read the class bytes and define the class java.nio.ByteBuffer bb = res.getByteBuffer(); diff --git a/jdk/src/java.base/share/classes/java/text/CalendarBuilder.java b/jdk/src/java.base/share/classes/java/text/CalendarBuilder.java index a8246b676ca..cb30a358ea4 100644 --- a/jdk/src/java.base/share/classes/java/text/CalendarBuilder.java +++ b/jdk/src/java.base/share/classes/java/text/CalendarBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 @@ -26,6 +26,7 @@ package java.text; import java.util.Calendar; +import java.util.StringJoiner; import static java.util.GregorianCalendar.*; /** @@ -146,19 +147,13 @@ class CalendarBuilder { } public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("CalendarBuilder:["); + StringJoiner sj = new StringJoiner(",", "CalendarBuilder:[", "]"); for (int i = 0; i < field.length; i++) { if (isSet(i)) { - sb.append(i).append('=').append(field[MAX_FIELD + i]).append(','); + sj.add(i + "=" + field[MAX_FIELD + i]); } } - int lastIndex = sb.length() - 1; - if (sb.charAt(lastIndex) == ',') { - sb.setLength(lastIndex); - } - sb.append(']'); - return sb.toString(); + return sj.toString(); } static int toISODayOfWeek(int calendarDayOfWeek) { diff --git a/jdk/src/java.base/share/classes/java/util/Locale.java b/jdk/src/java.base/share/classes/java/util/Locale.java index fbcb2f75e66..cf29686e693 100644 --- a/jdk/src/java.base/share/classes/java/util/Locale.java +++ b/jdk/src/java.base/share/classes/java/util/Locale.java @@ -2059,14 +2059,11 @@ public final class Locale implements Cloneable, Serializable { // If we have no list patterns, compose the list in a simple, // non-localized way. if (listPattern == null || listCompositionPattern == null) { - StringBuilder result = new StringBuilder(); + StringJoiner sj = new StringJoiner(","); for (int i = 0; i < stringList.length; ++i) { - if (i > 0) { - result.append(','); - } - result.append(stringList[i]); + sj.add(stringList[i]); } - return result.toString(); + return sj.toString(); } // Compose the list down to three elements if necessary diff --git a/jdk/src/java.base/share/classes/java/util/PropertyPermission.java b/jdk/src/java.base/share/classes/java/util/PropertyPermission.java index d532bddabf6..7e818a90b64 100644 --- a/jdk/src/java.base/share/classes/java/util/PropertyPermission.java +++ b/jdk/src/java.base/share/classes/java/util/PropertyPermission.java @@ -324,20 +324,16 @@ public final class PropertyPermission extends BasicPermission { * @return the canonical string representation of the actions. */ static String getActions(int mask) { - StringBuilder sb = new StringBuilder(); - boolean comma = false; - - if ((mask & READ) == READ) { - comma = true; - sb.append("read"); + switch (mask & (READ|WRITE)) { + case READ: + return SecurityConstants.PROPERTY_READ_ACTION; + case WRITE: + return SecurityConstants.PROPERTY_WRITE_ACTION; + case READ|WRITE: + return SecurityConstants.PROPERTY_RW_ACTION; + default: + return ""; } - - if ((mask & WRITE) == WRITE) { - if (comma) sb.append(','); - else comma = true; - sb.append("write"); - } - return sb.toString(); } /** diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/CompletableFuture.java b/jdk/src/java.base/share/classes/java/util/concurrent/CompletableFuture.java index 9e89169e15f..8476dcc1237 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/CompletableFuture.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/CompletableFuture.java @@ -50,7 +50,6 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; -import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.LockSupport; /** @@ -77,9 +76,9 @@ import java.util.concurrent.locks.LockSupport; *
  • All async methods without an explicit Executor * argument are performed using the {@link ForkJoinPool#commonPool()} * (unless it does not support a parallelism level of at least two, in - * which case, a new Thread is used). To simplify monitoring, - * debugging, and tracking, all generated asynchronous tasks are - * instances of the marker interface {@link + * which case, a new Thread is created to run each task). To simplify + * monitoring, debugging, and tracking, all generated asynchronous + * tasks are instances of the marker interface {@link * AsynchronousCompletionTask}.
  • * *
  • All CompletionStage methods are implemented independently of @@ -113,141 +112,1556 @@ public class CompletableFuture implements Future, CompletionStage { /* * Overview: * - * 1. Non-nullness of field result (set via CAS) indicates done. - * An AltResult is used to box null as a result, as well as to - * hold exceptions. Using a single field makes completion fast - * and simple to detect and trigger, at the expense of a lot of - * encoding and decoding that infiltrates many methods. One minor - * simplification relies on the (static) NIL (to box null results) - * being the only AltResult with a null exception field, so we - * don't usually need explicit comparisons with NIL. The CF - * exception propagation mechanics surrounding decoding rely on - * unchecked casts of decoded results really being unchecked, - * where user type errors are caught at point of use, as is - * currently the case in Java. These are highlighted by using - * SuppressWarnings-annotated temporaries. + * A CompletableFuture may have dependent completion actions, + * collected in a linked stack. It atomically completes by CASing + * a result field, and then pops off and runs those actions. This + * applies across normal vs exceptional outcomes, sync vs async + * actions, binary triggers, and various forms of completions. * - * 2. Waiters are held in a Treiber stack similar to the one used - * in FutureTask, Phaser, and SynchronousQueue. See their - * internal documentation for algorithmic details. + * Non-nullness of field result (set via CAS) indicates done. An + * AltResult is used to box null as a result, as well as to hold + * exceptions. Using a single field makes completion simple to + * detect and trigger. Encoding and decoding is straightforward + * but adds to the sprawl of trapping and associating exceptions + * with targets. Minor simplifications rely on (static) NIL (to + * box null results) being the only AltResult with a null + * exception field, so we don't usually need explicit comparisons. + * Even though some of the generics casts are unchecked (see + * SuppressWarnings annotations), they are placed to be + * appropriate even if checked. * - * 3. Completions are also kept in a list/stack, and pulled off - * and run when completion is triggered. (We could even use the - * same stack as for waiters, but would give up the potential - * parallelism obtained because woken waiters help release/run - * others -- see method postComplete). Because post-processing - * may race with direct calls, class Completion opportunistically - * extends AtomicInteger so callers can claim the action via - * compareAndSet(0, 1). The Completion.run methods are all - * written a boringly similar uniform way (that sometimes includes - * unnecessary-looking checks, kept to maintain uniformity). - * There are enough dimensions upon which they differ that - * attempts to factor commonalities while maintaining efficiency - * require more lines of code than they would save. + * Dependent actions are represented by Completion objects linked + * as Treiber stacks headed by field "stack". There are Completion + * classes for each kind of action, grouped into single-input + * (UniCompletion), two-input (BiCompletion), projected + * (BiCompletions using either (not both) of two inputs), shared + * (CoCompletion, used by the second of two sources), zero-input + * source actions, and Signallers that unblock waiters. Class + * Completion extends ForkJoinTask to enable async execution + * (adding no space overhead because we exploit its "tag" methods + * to maintain claims). It is also declared as Runnable to allow + * usage with arbitrary executors. * - * 4. The exported then/and/or methods do support a bit of - * factoring (see doThenApply etc). They must cope with the - * intrinsic races surrounding addition of a dependent action - * versus performing the action directly because the task is - * already complete. For example, a CF may not be complete upon - * entry, so a dependent completion is added, but by the time it - * is added, the target CF is complete, so must be directly - * executed. This is all done while avoiding unnecessary object - * construction in safe-bypass cases. + * Support for each kind of CompletionStage relies on a separate + * class, along with two CompletableFuture methods: + * + * * A Completion class with name X corresponding to function, + * prefaced with "Uni", "Bi", or "Or". Each class contains + * fields for source(s), actions, and dependent. They are + * boringly similar, differing from others only with respect to + * underlying functional forms. We do this so that users don't + * encounter layers of adaptors in common usages. We also + * include "Relay" classes/methods that don't correspond to user + * methods; they copy results from one stage to another. + * + * * Boolean CompletableFuture method x(...) (for example + * uniApply) takes all of the arguments needed to check that an + * action is triggerable, and then either runs the action or + * arranges its async execution by executing its Completion + * argument, if present. The method returns true if known to be + * complete. + * + * * Completion method tryFire(int mode) invokes the associated x + * method with its held arguments, and on success cleans up. + * The mode argument allows tryFire to be called twice (SYNC, + * then ASYNC); the first to screen and trap exceptions while + * arranging to execute, and the second when called from a + * task. (A few classes are not used async so take slightly + * different forms.) The claim() callback suppresses function + * invocation if already claimed by another thread. + * + * * CompletableFuture method xStage(...) is called from a public + * stage method of CompletableFuture x. It screens user + * arguments and invokes and/or creates the stage object. If + * not async and x is already complete, the action is run + * immediately. Otherwise a Completion c is created, pushed to + * x's stack (unless done), and started or triggered via + * c.tryFire. This also covers races possible if x completes + * while pushing. Classes with two inputs (for example BiApply) + * deal with races across both while pushing actions. The + * second completion is a CoCompletion pointing to the first, + * shared so that at most one performs the action. The + * multiple-arity methods allOf and anyOf do this pairwise to + * form trees of completions. + * + * Note that the generic type parameters of methods vary according + * to whether "this" is a source, dependent, or completion. + * + * Method postComplete is called upon completion unless the target + * is guaranteed not to be observable (i.e., not yet returned or + * linked). Multiple threads can call postComplete, which + * atomically pops each dependent action, and tries to trigger it + * via method tryFire, in NESTED mode. Triggering can propagate + * recursively, so NESTED mode returns its completed dependent (if + * one exists) for further processing by its caller (see method + * postFire). + * + * Blocking methods get() and join() rely on Signaller Completions + * that wake up waiting threads. The mechanics are similar to + * Treiber stack wait-nodes used in FutureTask, Phaser, and + * SynchronousQueue. See their internal documentation for + * algorithmic details. + * + * Without precautions, CompletableFutures would be prone to + * garbage accumulation as chains of Completions build up, each + * pointing back to its sources. So we null out fields as soon as + * possible (see especially method Completion.detach). The + * screening checks needed anyway harmlessly ignore null arguments + * that may have been obtained during races with threads nulling + * out fields. We also try to unlink fired Completions from + * stacks that might never be popped (see method postFire). + * Completion fields need not be declared as final or volatile + * because they are only visible to other threads upon safe + * publication. */ - // preliminaries + volatile Object result; // Either the result or boxed AltResult + volatile Completion stack; // Top of Treiber stack of dependent actions - static final class AltResult { - final Throwable ex; // null only for NIL - AltResult(Throwable ex) { this.ex = ex; } + final boolean internalComplete(Object r) { // CAS from null to r + return UNSAFE.compareAndSwapObject(this, RESULT, null, r); } + final boolean casStack(Completion cmp, Completion val) { + return UNSAFE.compareAndSwapObject(this, STACK, cmp, val); + } + + /** Returns true if successfully pushed c onto stack. */ + final boolean tryPushStack(Completion c) { + Completion h = stack; + lazySetNext(c, h); + return UNSAFE.compareAndSwapObject(this, STACK, h, c); + } + + /** Unconditionally pushes c onto stack, retrying if necessary. */ + final void pushStack(Completion c) { + do {} while (!tryPushStack(c)); + } + + /* ------------- Encoding and decoding outcomes -------------- */ + + static final class AltResult { // See above + final Throwable ex; // null only for NIL + AltResult(Throwable x) { this.ex = x; } + } + + /** The encoding of the null value. */ static final AltResult NIL = new AltResult(null); - // Fields + /** Completes with the null value, unless already completed. */ + final boolean completeNull() { + return UNSAFE.compareAndSwapObject(this, RESULT, null, + NIL); + } - volatile Object result; // Either the result or boxed AltResult - volatile WaitNode waiters; // Treiber stack of threads blocked on get() - volatile CompletionNode completions; // list (Treiber stack) of completions + /** Returns the encoding of the given non-exceptional value. */ + final Object encodeValue(T t) { + return (t == null) ? NIL : t; + } - // Basic utilities for triggering and processing completions + /** Completes with a non-exceptional result, unless already completed. */ + final boolean completeValue(T t) { + return UNSAFE.compareAndSwapObject(this, RESULT, null, + (t == null) ? NIL : t); + } /** - * Removes and signals all waiting threads and runs all completions. + * Returns the encoding of the given (non-null) exception as a + * wrapped CompletionException unless it is one already. + */ + static AltResult encodeThrowable(Throwable x) { + return new AltResult((x instanceof CompletionException) ? x : + new CompletionException(x)); + } + + /** Completes with an exceptional result, unless already completed. */ + final boolean completeThrowable(Throwable x) { + return UNSAFE.compareAndSwapObject(this, RESULT, null, + encodeThrowable(x)); + } + + /** + * Returns the encoding of the given (non-null) exception as a + * wrapped CompletionException unless it is one already. May + * return the given Object r (which must have been the result of a + * source future) if it is equivalent, i.e. if this is a simple + * relay of an existing CompletionException. + */ + static Object encodeThrowable(Throwable x, Object r) { + if (!(x instanceof CompletionException)) + x = new CompletionException(x); + else if (r instanceof AltResult && x == ((AltResult)r).ex) + return r; + return new AltResult(x); + } + + /** + * Completes with the given (non-null) exceptional result as a + * wrapped CompletionException unless it is one already, unless + * already completed. May complete with the given Object r + * (which must have been the result of a source future) if it is + * equivalent, i.e. if this is a simple propagation of an + * existing CompletionException. + */ + final boolean completeThrowable(Throwable x, Object r) { + return UNSAFE.compareAndSwapObject(this, RESULT, null, + encodeThrowable(x, r)); + } + + /** + * Returns the encoding of the given arguments: if the exception + * is non-null, encodes as AltResult. Otherwise uses the given + * value, boxed as NIL if null. + */ + Object encodeOutcome(T t, Throwable x) { + return (x == null) ? (t == null) ? NIL : t : encodeThrowable(x); + } + + /** + * Returns the encoding of a copied outcome; if exceptional, + * rewraps as a CompletionException, else returns argument. + */ + static Object encodeRelay(Object r) { + Throwable x; + return (((r instanceof AltResult) && + (x = ((AltResult)r).ex) != null && + !(x instanceof CompletionException)) ? + new AltResult(new CompletionException(x)) : r); + } + + /** + * Completes with r or a copy of r, unless already completed. + * If exceptional, r is first coerced to a CompletionException. + */ + final boolean completeRelay(Object r) { + return UNSAFE.compareAndSwapObject(this, RESULT, null, + encodeRelay(r)); + } + + /** + * Reports result using Future.get conventions. + */ + private static T reportGet(Object r) + throws InterruptedException, ExecutionException { + if (r == null) // by convention below, null means interrupted + throw new InterruptedException(); + if (r instanceof AltResult) { + Throwable x, cause; + if ((x = ((AltResult)r).ex) == null) + return null; + if (x instanceof CancellationException) + throw (CancellationException)x; + if ((x instanceof CompletionException) && + (cause = x.getCause()) != null) + x = cause; + throw new ExecutionException(x); + } + @SuppressWarnings("unchecked") T t = (T) r; + return t; + } + + /** + * Decodes outcome to return result or throw unchecked exception. + */ + private static T reportJoin(Object r) { + if (r instanceof AltResult) { + Throwable x; + if ((x = ((AltResult)r).ex) == null) + return null; + if (x instanceof CancellationException) + throw (CancellationException)x; + if (x instanceof CompletionException) + throw (CompletionException)x; + throw new CompletionException(x); + } + @SuppressWarnings("unchecked") T t = (T) r; + return t; + } + + /* ------------- Async task preliminaries -------------- */ + + /** + * A marker interface identifying asynchronous tasks produced by + * {@code async} methods. This may be useful for monitoring, + * debugging, and tracking asynchronous activities. + * + * @since 1.8 + */ + public static interface AsynchronousCompletionTask { + } + + private static final boolean useCommonPool = + (ForkJoinPool.getCommonPoolParallelism() > 1); + + /** + * Default executor -- ForkJoinPool.commonPool() unless it cannot + * support parallelism. + */ + private static final Executor asyncPool = useCommonPool ? + ForkJoinPool.commonPool() : new ThreadPerTaskExecutor(); + + /** Fallback if ForkJoinPool.commonPool() cannot support parallelism */ + static final class ThreadPerTaskExecutor implements Executor { + public void execute(Runnable r) { new Thread(r).start(); } + } + + /** + * Null-checks user executor argument, and translates uses of + * commonPool to asyncPool in case parallelism disabled. + */ + static Executor screenExecutor(Executor e) { + if (!useCommonPool && e == ForkJoinPool.commonPool()) + return asyncPool; + if (e == null) throw new NullPointerException(); + return e; + } + + // Modes for Completion.tryFire. Signedness matters. + static final int SYNC = 0; + static final int ASYNC = 1; + static final int NESTED = -1; + + /* ------------- Base Completion classes and operations -------------- */ + + @SuppressWarnings("serial") + abstract static class Completion extends ForkJoinTask + implements Runnable, AsynchronousCompletionTask { + volatile Completion next; // Treiber stack link + + /** + * Performs completion action if triggered, returning a + * dependent that may need propagation, if one exists. + * + * @param mode SYNC, ASYNC, or NESTED + */ + abstract CompletableFuture tryFire(int mode); + + /** Returns true if possibly still triggerable. Used by cleanStack. */ + abstract boolean isLive(); + + public final void run() { tryFire(ASYNC); } + public final boolean exec() { tryFire(ASYNC); return true; } + public final Void getRawResult() { return null; } + public final void setRawResult(Void v) {} + } + + static void lazySetNext(Completion c, Completion next) { + UNSAFE.putOrderedObject(c, NEXT, next); + } + + /** + * Pops and tries to trigger all reachable dependents. Call only + * when known to be done. */ final void postComplete() { - WaitNode q; Thread t; - while ((q = waiters) != null) { - if (UNSAFE.compareAndSwapObject(this, WAITERS, q, q.next) && - (t = q.thread) != null) { - q.thread = null; - LockSupport.unpark(t); + /* + * On each step, variable f holds current dependents to pop + * and run. It is extended along only one path at a time, + * pushing others to avoid unbounded recursion. + */ + CompletableFuture f = this; Completion h; + while ((h = f.stack) != null || + (f != this && (h = (f = this).stack) != null)) { + CompletableFuture d; Completion t; + if (f.casStack(h, t = h.next)) { + if (t != null) { + if (f != this) { + pushStack(h); + continue; + } + h.next = null; // detach + } + f = (d = h.tryFire(NESTED)) == null ? this : d; } } + } - CompletionNode h; Completion c; - while ((h = completions) != null) { - if (UNSAFE.compareAndSwapObject(this, COMPLETIONS, h, h.next) && - (c = h.completion) != null) - c.run(); + /** Traverses stack and unlinks dead Completions. */ + final void cleanStack() { + for (Completion p = null, q = stack; q != null;) { + Completion s = q.next; + if (q.isLive()) { + p = q; + q = s; + } + else if (p == null) { + casStack(q, s); + q = stack; + } + else { + p.next = s; + if (p.isLive()) + q = s; + else { + p = null; // restart + q = stack; + } + } + } + } + + /* ------------- One-input Completions -------------- */ + + /** A Completion with a source, dependent, and executor. */ + @SuppressWarnings("serial") + abstract static class UniCompletion extends Completion { + Executor executor; // executor to use (null if none) + CompletableFuture dep; // the dependent to complete + CompletableFuture src; // source for action + + UniCompletion(Executor executor, CompletableFuture dep, + CompletableFuture src) { + this.executor = executor; this.dep = dep; this.src = src; + } + + /** + * Returns true if action can be run. Call only when known to + * be triggerable. Uses FJ tag bit to ensure that only one + * thread claims ownership. If async, starts as task -- a + * later call to tryFire will run action. + */ + final boolean claim() { + Executor e = executor; + if (compareAndSetForkJoinTaskTag((short)0, (short)1)) { + if (e == null) + return true; + executor = null; // disable + e.execute(this); + } + return false; + } + + final boolean isLive() { return dep != null; } + } + + /** Pushes the given completion (if it exists) unless done. */ + final void push(UniCompletion c) { + if (c != null) { + while (result == null && !tryPushStack(c)) + lazySetNext(c, null); // clear on failure } } /** - * Triggers completion with the encoding of the given arguments: - * if the exception is non-null, encodes it as a wrapped - * CompletionException unless it is one already. Otherwise uses - * the given result, boxed as NIL if null. + * Post-processing by dependent after successful UniCompletion + * tryFire. Tries to clean stack of source a, and then either runs + * postComplete or returns this to caller, depending on mode. */ - final void internalComplete(T v, Throwable ex) { + final CompletableFuture postFire(CompletableFuture a, int mode) { + if (a != null && a.stack != null) { + if (mode < 0 || a.result == null) + a.cleanStack(); + else + a.postComplete(); + } + if (result != null && stack != null) { + if (mode < 0) + return this; + else + postComplete(); + } + return null; + } + + @SuppressWarnings("serial") + static final class UniApply extends UniCompletion { + Function fn; + UniApply(Executor executor, CompletableFuture dep, + CompletableFuture src, + Function fn) { + super(executor, dep, src); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; CompletableFuture a; + if ((d = dep) == null || + !d.uniApply(a = src, fn, mode > 0 ? null : this)) + return null; + dep = null; src = null; fn = null; + return d.postFire(a, mode); + } + } + + final boolean uniApply(CompletableFuture a, + Function f, + UniApply c) { + Object r; Throwable x; + if (a == null || (r = a.result) == null || f == null) + return false; + tryComplete: if (result == null) { + if (r instanceof AltResult) { + if ((x = ((AltResult)r).ex) != null) { + completeThrowable(x, r); + break tryComplete; + } + r = null; + } + try { + if (c != null && !c.claim()) + return false; + @SuppressWarnings("unchecked") S s = (S) r; + completeValue(f.apply(s)); + } catch (Throwable ex) { + completeThrowable(ex); + } + } + return true; + } + + private CompletableFuture uniApplyStage( + Executor e, Function f) { + if (f == null) throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + if (e != null || !d.uniApply(this, f, null)) { + UniApply c = new UniApply(e, d, this, f); + push(c); + c.tryFire(SYNC); + } + return d; + } + + @SuppressWarnings("serial") + static final class UniAccept extends UniCompletion { + Consumer fn; + UniAccept(Executor executor, CompletableFuture dep, + CompletableFuture src, Consumer fn) { + super(executor, dep, src); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; CompletableFuture a; + if ((d = dep) == null || + !d.uniAccept(a = src, fn, mode > 0 ? null : this)) + return null; + dep = null; src = null; fn = null; + return d.postFire(a, mode); + } + } + + final boolean uniAccept(CompletableFuture a, + Consumer f, UniAccept c) { + Object r; Throwable x; + if (a == null || (r = a.result) == null || f == null) + return false; + tryComplete: if (result == null) { + if (r instanceof AltResult) { + if ((x = ((AltResult)r).ex) != null) { + completeThrowable(x, r); + break tryComplete; + } + r = null; + } + try { + if (c != null && !c.claim()) + return false; + @SuppressWarnings("unchecked") S s = (S) r; + f.accept(s); + completeNull(); + } catch (Throwable ex) { + completeThrowable(ex); + } + } + return true; + } + + private CompletableFuture uniAcceptStage(Executor e, + Consumer f) { + if (f == null) throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + if (e != null || !d.uniAccept(this, f, null)) { + UniAccept c = new UniAccept(e, d, this, f); + push(c); + c.tryFire(SYNC); + } + return d; + } + + @SuppressWarnings("serial") + static final class UniRun extends UniCompletion { + Runnable fn; + UniRun(Executor executor, CompletableFuture dep, + CompletableFuture src, Runnable fn) { + super(executor, dep, src); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; CompletableFuture a; + if ((d = dep) == null || + !d.uniRun(a = src, fn, mode > 0 ? null : this)) + return null; + dep = null; src = null; fn = null; + return d.postFire(a, mode); + } + } + + final boolean uniRun(CompletableFuture a, Runnable f, UniRun c) { + Object r; Throwable x; + if (a == null || (r = a.result) == null || f == null) + return false; + if (result == null) { + if (r instanceof AltResult && (x = ((AltResult)r).ex) != null) + completeThrowable(x, r); + else + try { + if (c != null && !c.claim()) + return false; + f.run(); + completeNull(); + } catch (Throwable ex) { + completeThrowable(ex); + } + } + return true; + } + + private CompletableFuture uniRunStage(Executor e, Runnable f) { + if (f == null) throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + if (e != null || !d.uniRun(this, f, null)) { + UniRun c = new UniRun(e, d, this, f); + push(c); + c.tryFire(SYNC); + } + return d; + } + + @SuppressWarnings("serial") + static final class UniWhenComplete extends UniCompletion { + BiConsumer fn; + UniWhenComplete(Executor executor, CompletableFuture dep, + CompletableFuture src, + BiConsumer fn) { + super(executor, dep, src); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; CompletableFuture a; + if ((d = dep) == null || + !d.uniWhenComplete(a = src, fn, mode > 0 ? null : this)) + return null; + dep = null; src = null; fn = null; + return d.postFire(a, mode); + } + } + + final boolean uniWhenComplete(CompletableFuture a, + BiConsumer f, + UniWhenComplete c) { + Object r; T t; Throwable x = null; + if (a == null || (r = a.result) == null || f == null) + return false; + if (result == null) { + try { + if (c != null && !c.claim()) + return false; + if (r instanceof AltResult) { + x = ((AltResult)r).ex; + t = null; + } else { + @SuppressWarnings("unchecked") T tr = (T) r; + t = tr; + } + f.accept(t, x); + if (x == null) { + internalComplete(r); + return true; + } + } catch (Throwable ex) { + if (x == null) + x = ex; + } + completeThrowable(x, r); + } + return true; + } + + private CompletableFuture uniWhenCompleteStage( + Executor e, BiConsumer f) { + if (f == null) throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + if (e != null || !d.uniWhenComplete(this, f, null)) { + UniWhenComplete c = new UniWhenComplete(e, d, this, f); + push(c); + c.tryFire(SYNC); + } + return d; + } + + @SuppressWarnings("serial") + static final class UniHandle extends UniCompletion { + BiFunction fn; + UniHandle(Executor executor, CompletableFuture dep, + CompletableFuture src, + BiFunction fn) { + super(executor, dep, src); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; CompletableFuture a; + if ((d = dep) == null || + !d.uniHandle(a = src, fn, mode > 0 ? null : this)) + return null; + dep = null; src = null; fn = null; + return d.postFire(a, mode); + } + } + + final boolean uniHandle(CompletableFuture a, + BiFunction f, + UniHandle c) { + Object r; S s; Throwable x; + if (a == null || (r = a.result) == null || f == null) + return false; + if (result == null) { + try { + if (c != null && !c.claim()) + return false; + if (r instanceof AltResult) { + x = ((AltResult)r).ex; + s = null; + } else { + x = null; + @SuppressWarnings("unchecked") S ss = (S) r; + s = ss; + } + completeValue(f.apply(s, x)); + } catch (Throwable ex) { + completeThrowable(ex); + } + } + return true; + } + + private CompletableFuture uniHandleStage( + Executor e, BiFunction f) { + if (f == null) throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + if (e != null || !d.uniHandle(this, f, null)) { + UniHandle c = new UniHandle(e, d, this, f); + push(c); + c.tryFire(SYNC); + } + return d; + } + + @SuppressWarnings("serial") + static final class UniExceptionally extends UniCompletion { + Function fn; + UniExceptionally(CompletableFuture dep, CompletableFuture src, + Function fn) { + super(null, dep, src); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { // never ASYNC + // assert mode != ASYNC; + CompletableFuture d; CompletableFuture a; + if ((d = dep) == null || !d.uniExceptionally(a = src, fn, this)) + return null; + dep = null; src = null; fn = null; + return d.postFire(a, mode); + } + } + + final boolean uniExceptionally(CompletableFuture a, + Function f, + UniExceptionally c) { + Object r; Throwable x; + if (a == null || (r = a.result) == null || f == null) + return false; + if (result == null) { + try { + if (r instanceof AltResult && (x = ((AltResult)r).ex) != null) { + if (c != null && !c.claim()) + return false; + completeValue(f.apply(x)); + } else + internalComplete(r); + } catch (Throwable ex) { + completeThrowable(ex); + } + } + return true; + } + + private CompletableFuture uniExceptionallyStage( + Function f) { + if (f == null) throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + if (!d.uniExceptionally(this, f, null)) { + UniExceptionally c = new UniExceptionally(d, this, f); + push(c); + c.tryFire(SYNC); + } + return d; + } + + @SuppressWarnings("serial") + static final class UniRelay extends UniCompletion { // for Compose + UniRelay(CompletableFuture dep, CompletableFuture src) { + super(null, dep, src); + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; CompletableFuture a; + if ((d = dep) == null || !d.uniRelay(a = src)) + return null; + src = null; dep = null; + return d.postFire(a, mode); + } + } + + final boolean uniRelay(CompletableFuture a) { + Object r; + if (a == null || (r = a.result) == null) + return false; + if (result == null) // no need to claim + completeRelay(r); + return true; + } + + @SuppressWarnings("serial") + static final class UniCompose extends UniCompletion { + Function> fn; + UniCompose(Executor executor, CompletableFuture dep, + CompletableFuture src, + Function> fn) { + super(executor, dep, src); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; CompletableFuture a; + if ((d = dep) == null || + !d.uniCompose(a = src, fn, mode > 0 ? null : this)) + return null; + dep = null; src = null; fn = null; + return d.postFire(a, mode); + } + } + + final boolean uniCompose( + CompletableFuture a, + Function> f, + UniCompose c) { + Object r; Throwable x; + if (a == null || (r = a.result) == null || f == null) + return false; + tryComplete: if (result == null) { + if (r instanceof AltResult) { + if ((x = ((AltResult)r).ex) != null) { + completeThrowable(x, r); + break tryComplete; + } + r = null; + } + try { + if (c != null && !c.claim()) + return false; + @SuppressWarnings("unchecked") S s = (S) r; + CompletableFuture g = f.apply(s).toCompletableFuture(); + if (g.result == null || !uniRelay(g)) { + UniRelay copy = new UniRelay(this, g); + g.push(copy); + copy.tryFire(SYNC); + if (result == null) + return false; + } + } catch (Throwable ex) { + completeThrowable(ex); + } + } + return true; + } + + private CompletableFuture uniComposeStage( + Executor e, Function> f) { + if (f == null) throw new NullPointerException(); + Object r; Throwable x; + if (e == null && (r = result) != null) { + // try to return function result directly + if (r instanceof AltResult) { + if ((x = ((AltResult)r).ex) != null) { + return new CompletableFuture(encodeThrowable(x, r)); + } + r = null; + } + try { + @SuppressWarnings("unchecked") T t = (T) r; + return f.apply(t).toCompletableFuture(); + } catch (Throwable ex) { + return new CompletableFuture(encodeThrowable(ex)); + } + } + CompletableFuture d = new CompletableFuture(); + UniCompose c = new UniCompose(e, d, this, f); + push(c); + c.tryFire(SYNC); + return d; + } + + /* ------------- Two-input Completions -------------- */ + + /** A Completion for an action with two sources */ + @SuppressWarnings("serial") + abstract static class BiCompletion extends UniCompletion { + CompletableFuture snd; // second source for action + BiCompletion(Executor executor, CompletableFuture dep, + CompletableFuture src, CompletableFuture snd) { + super(executor, dep, src); this.snd = snd; + } + } + + /** A Completion delegating to a BiCompletion */ + @SuppressWarnings("serial") + static final class CoCompletion extends Completion { + BiCompletion base; + CoCompletion(BiCompletion base) { this.base = base; } + final CompletableFuture tryFire(int mode) { + BiCompletion c; CompletableFuture d; + if ((c = base) == null || (d = c.tryFire(mode)) == null) + return null; + base = null; // detach + return d; + } + final boolean isLive() { + BiCompletion c; + return (c = base) != null && c.dep != null; + } + } + + /** Pushes completion to this and b unless both done. */ + final void bipush(CompletableFuture b, BiCompletion c) { + if (c != null) { + Object r; + while ((r = result) == null && !tryPushStack(c)) + lazySetNext(c, null); // clear on failure + if (b != null && b != this && b.result == null) { + Completion q = (r != null) ? c : new CoCompletion(c); + while (b.result == null && !b.tryPushStack(q)) + lazySetNext(q, null); // clear on failure + } + } + } + + /** Post-processing after successful BiCompletion tryFire. */ + final CompletableFuture postFire(CompletableFuture a, + CompletableFuture b, int mode) { + if (b != null && b.stack != null) { // clean second source + if (mode < 0 || b.result == null) + b.cleanStack(); + else + b.postComplete(); + } + return postFire(a, mode); + } + + @SuppressWarnings("serial") + static final class BiApply extends BiCompletion { + BiFunction fn; + BiApply(Executor executor, CompletableFuture dep, + CompletableFuture src, CompletableFuture snd, + BiFunction fn) { + super(executor, dep, src, snd); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; + CompletableFuture a; + CompletableFuture b; + if ((d = dep) == null || + !d.biApply(a = src, b = snd, fn, mode > 0 ? null : this)) + return null; + dep = null; src = null; snd = null; fn = null; + return d.postFire(a, b, mode); + } + } + + final boolean biApply(CompletableFuture a, + CompletableFuture b, + BiFunction f, + BiApply c) { + Object r, s; Throwable x; + if (a == null || (r = a.result) == null || + b == null || (s = b.result) == null || f == null) + return false; + tryComplete: if (result == null) { + if (r instanceof AltResult) { + if ((x = ((AltResult)r).ex) != null) { + completeThrowable(x, r); + break tryComplete; + } + r = null; + } + if (s instanceof AltResult) { + if ((x = ((AltResult)s).ex) != null) { + completeThrowable(x, s); + break tryComplete; + } + s = null; + } + try { + if (c != null && !c.claim()) + return false; + @SuppressWarnings("unchecked") R rr = (R) r; + @SuppressWarnings("unchecked") S ss = (S) s; + completeValue(f.apply(rr, ss)); + } catch (Throwable ex) { + completeThrowable(ex); + } + } + return true; + } + + private CompletableFuture biApplyStage( + Executor e, CompletionStage o, + BiFunction f) { + CompletableFuture b; + if (f == null || (b = o.toCompletableFuture()) == null) + throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + if (e != null || !d.biApply(this, b, f, null)) { + BiApply c = new BiApply(e, d, this, b, f); + bipush(b, c); + c.tryFire(SYNC); + } + return d; + } + + @SuppressWarnings("serial") + static final class BiAccept extends BiCompletion { + BiConsumer fn; + BiAccept(Executor executor, CompletableFuture dep, + CompletableFuture src, CompletableFuture snd, + BiConsumer fn) { + super(executor, dep, src, snd); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; + CompletableFuture a; + CompletableFuture b; + if ((d = dep) == null || + !d.biAccept(a = src, b = snd, fn, mode > 0 ? null : this)) + return null; + dep = null; src = null; snd = null; fn = null; + return d.postFire(a, b, mode); + } + } + + final boolean biAccept(CompletableFuture a, + CompletableFuture b, + BiConsumer f, + BiAccept c) { + Object r, s; Throwable x; + if (a == null || (r = a.result) == null || + b == null || (s = b.result) == null || f == null) + return false; + tryComplete: if (result == null) { + if (r instanceof AltResult) { + if ((x = ((AltResult)r).ex) != null) { + completeThrowable(x, r); + break tryComplete; + } + r = null; + } + if (s instanceof AltResult) { + if ((x = ((AltResult)s).ex) != null) { + completeThrowable(x, s); + break tryComplete; + } + s = null; + } + try { + if (c != null && !c.claim()) + return false; + @SuppressWarnings("unchecked") R rr = (R) r; + @SuppressWarnings("unchecked") S ss = (S) s; + f.accept(rr, ss); + completeNull(); + } catch (Throwable ex) { + completeThrowable(ex); + } + } + return true; + } + + private CompletableFuture biAcceptStage( + Executor e, CompletionStage o, + BiConsumer f) { + CompletableFuture b; + if (f == null || (b = o.toCompletableFuture()) == null) + throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + if (e != null || !d.biAccept(this, b, f, null)) { + BiAccept c = new BiAccept(e, d, this, b, f); + bipush(b, c); + c.tryFire(SYNC); + } + return d; + } + + @SuppressWarnings("serial") + static final class BiRun extends BiCompletion { + Runnable fn; + BiRun(Executor executor, CompletableFuture dep, + CompletableFuture src, + CompletableFuture snd, + Runnable fn) { + super(executor, dep, src, snd); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; + CompletableFuture a; + CompletableFuture b; + if ((d = dep) == null || + !d.biRun(a = src, b = snd, fn, mode > 0 ? null : this)) + return null; + dep = null; src = null; snd = null; fn = null; + return d.postFire(a, b, mode); + } + } + + final boolean biRun(CompletableFuture a, CompletableFuture b, + Runnable f, BiRun c) { + Object r, s; Throwable x; + if (a == null || (r = a.result) == null || + b == null || (s = b.result) == null || f == null) + return false; + if (result == null) { + if (r instanceof AltResult && (x = ((AltResult)r).ex) != null) + completeThrowable(x, r); + else if (s instanceof AltResult && (x = ((AltResult)s).ex) != null) + completeThrowable(x, s); + else + try { + if (c != null && !c.claim()) + return false; + f.run(); + completeNull(); + } catch (Throwable ex) { + completeThrowable(ex); + } + } + return true; + } + + private CompletableFuture biRunStage(Executor e, CompletionStage o, + Runnable f) { + CompletableFuture b; + if (f == null || (b = o.toCompletableFuture()) == null) + throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + if (e != null || !d.biRun(this, b, f, null)) { + BiRun c = new BiRun<>(e, d, this, b, f); + bipush(b, c); + c.tryFire(SYNC); + } + return d; + } + + @SuppressWarnings("serial") + static final class BiRelay extends BiCompletion { // for And + BiRelay(CompletableFuture dep, + CompletableFuture src, + CompletableFuture snd) { + super(null, dep, src, snd); + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; + CompletableFuture a; + CompletableFuture b; + if ((d = dep) == null || !d.biRelay(a = src, b = snd)) + return null; + src = null; snd = null; dep = null; + return d.postFire(a, b, mode); + } + } + + boolean biRelay(CompletableFuture a, CompletableFuture b) { + Object r, s; Throwable x; + if (a == null || (r = a.result) == null || + b == null || (s = b.result) == null) + return false; + if (result == null) { + if (r instanceof AltResult && (x = ((AltResult)r).ex) != null) + completeThrowable(x, r); + else if (s instanceof AltResult && (x = ((AltResult)s).ex) != null) + completeThrowable(x, s); + else + completeNull(); + } + return true; + } + + /** Recursively constructs a tree of completions. */ + static CompletableFuture andTree(CompletableFuture[] cfs, + int lo, int hi) { + CompletableFuture d = new CompletableFuture(); + if (lo > hi) // empty + d.result = NIL; + else { + CompletableFuture a, b; + int mid = (lo + hi) >>> 1; + if ((a = (lo == mid ? cfs[lo] : + andTree(cfs, lo, mid))) == null || + (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] : + andTree(cfs, mid+1, hi))) == null) + throw new NullPointerException(); + if (!d.biRelay(a, b)) { + BiRelay c = new BiRelay<>(d, a, b); + a.bipush(b, c); + c.tryFire(SYNC); + } + } + return d; + } + + /* ------------- Projected (Ored) BiCompletions -------------- */ + + /** Pushes completion to this and b unless either done. */ + final void orpush(CompletableFuture b, BiCompletion c) { + if (c != null) { + while ((b == null || b.result == null) && result == null) { + if (tryPushStack(c)) { + if (b != null && b != this && b.result == null) { + Completion q = new CoCompletion(c); + while (result == null && b.result == null && + !b.tryPushStack(q)) + lazySetNext(q, null); // clear on failure + } + break; + } + lazySetNext(c, null); // clear on failure + } + } + } + + @SuppressWarnings("serial") + static final class OrApply extends BiCompletion { + Function fn; + OrApply(Executor executor, CompletableFuture dep, + CompletableFuture src, + CompletableFuture snd, + Function fn) { + super(executor, dep, src, snd); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; + CompletableFuture a; + CompletableFuture b; + if ((d = dep) == null || + !d.orApply(a = src, b = snd, fn, mode > 0 ? null : this)) + return null; + dep = null; src = null; snd = null; fn = null; + return d.postFire(a, b, mode); + } + } + + final boolean orApply(CompletableFuture a, + CompletableFuture b, + Function f, + OrApply c) { + Object r; Throwable x; + if (a == null || b == null || + ((r = a.result) == null && (r = b.result) == null) || f == null) + return false; + tryComplete: if (result == null) { + try { + if (c != null && !c.claim()) + return false; + if (r instanceof AltResult) { + if ((x = ((AltResult)r).ex) != null) { + completeThrowable(x, r); + break tryComplete; + } + r = null; + } + @SuppressWarnings("unchecked") R rr = (R) r; + completeValue(f.apply(rr)); + } catch (Throwable ex) { + completeThrowable(ex); + } + } + return true; + } + + private CompletableFuture orApplyStage( + Executor e, CompletionStage o, + Function f) { + CompletableFuture b; + if (f == null || (b = o.toCompletableFuture()) == null) + throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + if (e != null || !d.orApply(this, b, f, null)) { + OrApply c = new OrApply(e, d, this, b, f); + orpush(b, c); + c.tryFire(SYNC); + } + return d; + } + + @SuppressWarnings("serial") + static final class OrAccept extends BiCompletion { + Consumer fn; + OrAccept(Executor executor, CompletableFuture dep, + CompletableFuture src, + CompletableFuture snd, + Consumer fn) { + super(executor, dep, src, snd); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; + CompletableFuture a; + CompletableFuture b; + if ((d = dep) == null || + !d.orAccept(a = src, b = snd, fn, mode > 0 ? null : this)) + return null; + dep = null; src = null; snd = null; fn = null; + return d.postFire(a, b, mode); + } + } + + final boolean orAccept(CompletableFuture a, + CompletableFuture b, + Consumer f, + OrAccept c) { + Object r; Throwable x; + if (a == null || b == null || + ((r = a.result) == null && (r = b.result) == null) || f == null) + return false; + tryComplete: if (result == null) { + try { + if (c != null && !c.claim()) + return false; + if (r instanceof AltResult) { + if ((x = ((AltResult)r).ex) != null) { + completeThrowable(x, r); + break tryComplete; + } + r = null; + } + @SuppressWarnings("unchecked") R rr = (R) r; + f.accept(rr); + completeNull(); + } catch (Throwable ex) { + completeThrowable(ex); + } + } + return true; + } + + private CompletableFuture orAcceptStage( + Executor e, CompletionStage o, Consumer f) { + CompletableFuture b; + if (f == null || (b = o.toCompletableFuture()) == null) + throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + if (e != null || !d.orAccept(this, b, f, null)) { + OrAccept c = new OrAccept(e, d, this, b, f); + orpush(b, c); + c.tryFire(SYNC); + } + return d; + } + + @SuppressWarnings("serial") + static final class OrRun extends BiCompletion { + Runnable fn; + OrRun(Executor executor, CompletableFuture dep, + CompletableFuture src, + CompletableFuture snd, + Runnable fn) { + super(executor, dep, src, snd); this.fn = fn; + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; + CompletableFuture a; + CompletableFuture b; + if ((d = dep) == null || + !d.orRun(a = src, b = snd, fn, mode > 0 ? null : this)) + return null; + dep = null; src = null; snd = null; fn = null; + return d.postFire(a, b, mode); + } + } + + final boolean orRun(CompletableFuture a, CompletableFuture b, + Runnable f, OrRun c) { + Object r; Throwable x; + if (a == null || b == null || + ((r = a.result) == null && (r = b.result) == null) || f == null) + return false; + if (result == null) { + try { + if (c != null && !c.claim()) + return false; + if (r instanceof AltResult && (x = ((AltResult)r).ex) != null) + completeThrowable(x, r); + else { + f.run(); + completeNull(); + } + } catch (Throwable ex) { + completeThrowable(ex); + } + } + return true; + } + + private CompletableFuture orRunStage(Executor e, CompletionStage o, + Runnable f) { + CompletableFuture b; + if (f == null || (b = o.toCompletableFuture()) == null) + throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + if (e != null || !d.orRun(this, b, f, null)) { + OrRun c = new OrRun<>(e, d, this, b, f); + orpush(b, c); + c.tryFire(SYNC); + } + return d; + } + + @SuppressWarnings("serial") + static final class OrRelay extends BiCompletion { // for Or + OrRelay(CompletableFuture dep, CompletableFuture src, + CompletableFuture snd) { + super(null, dep, src, snd); + } + final CompletableFuture tryFire(int mode) { + CompletableFuture d; + CompletableFuture a; + CompletableFuture b; + if ((d = dep) == null || !d.orRelay(a = src, b = snd)) + return null; + src = null; snd = null; dep = null; + return d.postFire(a, b, mode); + } + } + + final boolean orRelay(CompletableFuture a, CompletableFuture b) { + Object r; + if (a == null || b == null || + ((r = a.result) == null && (r = b.result) == null)) + return false; if (result == null) - UNSAFE.compareAndSwapObject - (this, RESULT, null, - (ex == null) ? (v == null) ? NIL : v : - new AltResult((ex instanceof CompletionException) ? ex : - new CompletionException(ex))); - postComplete(); // help out even if not triggered + completeRelay(r); + return true; } - /** - * If triggered, helps release and/or process completions. - */ - final void helpPostComplete() { - if (result != null) - postComplete(); + /** Recursively constructs a tree of completions. */ + static CompletableFuture orTree(CompletableFuture[] cfs, + int lo, int hi) { + CompletableFuture d = new CompletableFuture(); + if (lo <= hi) { + CompletableFuture a, b; + int mid = (lo + hi) >>> 1; + if ((a = (lo == mid ? cfs[lo] : + orTree(cfs, lo, mid))) == null || + (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] : + orTree(cfs, mid+1, hi))) == null) + throw new NullPointerException(); + if (!d.orRelay(a, b)) { + OrRelay c = new OrRelay<>(d, a, b); + a.orpush(b, c); + c.tryFire(SYNC); + } + } + return d; } - /* ------------- waiting for completions -------------- */ + /* ------------- Zero-input Async forms -------------- */ - /** Number of processors, for spin control */ - static final int NCPU = Runtime.getRuntime().availableProcessors(); + @SuppressWarnings("serial") + static final class AsyncSupply extends ForkJoinTask + implements Runnable, AsynchronousCompletionTask { + CompletableFuture dep; Supplier fn; + AsyncSupply(CompletableFuture dep, Supplier fn) { + this.dep = dep; this.fn = fn; + } + + public final Void getRawResult() { return null; } + public final void setRawResult(Void v) {} + public final boolean exec() { run(); return true; } + + public void run() { + CompletableFuture d; Supplier f; + if ((d = dep) != null && (f = fn) != null) { + dep = null; fn = null; + if (d.result == null) { + try { + d.completeValue(f.get()); + } catch (Throwable ex) { + d.completeThrowable(ex); + } + } + d.postComplete(); + } + } + } + + static CompletableFuture asyncSupplyStage(Executor e, + Supplier f) { + if (f == null) throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + e.execute(new AsyncSupply(d, f)); + return d; + } + + @SuppressWarnings("serial") + static final class AsyncRun extends ForkJoinTask + implements Runnable, AsynchronousCompletionTask { + CompletableFuture dep; Runnable fn; + AsyncRun(CompletableFuture dep, Runnable fn) { + this.dep = dep; this.fn = fn; + } + + public final Void getRawResult() { return null; } + public final void setRawResult(Void v) {} + public final boolean exec() { run(); return true; } + + public void run() { + CompletableFuture d; Runnable f; + if ((d = dep) != null && (f = fn) != null) { + dep = null; fn = null; + if (d.result == null) { + try { + f.run(); + d.completeNull(); + } catch (Throwable ex) { + d.completeThrowable(ex); + } + } + d.postComplete(); + } + } + } + + static CompletableFuture asyncRunStage(Executor e, Runnable f) { + if (f == null) throw new NullPointerException(); + CompletableFuture d = new CompletableFuture(); + e.execute(new AsyncRun(d, f)); + return d; + } + + /* ------------- Signallers -------------- */ /** - * Heuristic spin value for waitingGet() before blocking on - * multiprocessors + * Completion for recording and releasing a waiting thread. This + * class implements ManagedBlocker to avoid starvation when + * blocking actions pile up in ForkJoinPools. */ - static final int SPINS = (NCPU > 1) ? 1 << 8 : 0; - - /** - * Linked nodes to record waiting threads in a Treiber stack. See - * other classes such as Phaser and SynchronousQueue for more - * detailed explanation. This class implements ManagedBlocker to - * avoid starvation when blocking actions pile up in - * ForkJoinPools. - */ - static final class WaitNode implements ForkJoinPool.ManagedBlocker { - long nanos; // wait time if timed - final long deadline; // non-zero if timed + @SuppressWarnings("serial") + static final class Signaller extends Completion + implements ForkJoinPool.ManagedBlocker { + long nanos; // wait time if timed + final long deadline; // non-zero if timed volatile int interruptControl; // > 0: interruptible, < 0: interrupted volatile Thread thread; - volatile WaitNode next; - WaitNode(boolean interruptible, long nanos, long deadline) { + + Signaller(boolean interruptible, long nanos, long deadline) { this.thread = Thread.currentThread(); this.interruptControl = interruptible ? 1 : 0; this.nanos = nanos; this.deadline = deadline; } + final CompletableFuture tryFire(int ignore) { + Thread w; // no need to atomically claim + if ((w = thread) != null) { + thread = null; + LockSupport.unpark(w); + } + return null; + } public boolean isReleasable() { if (thread == null) return true; @@ -273,6 +1687,7 @@ public class CompletableFuture implements Future, CompletionStage { LockSupport.parkNanos(this, nanos); return isReleasable(); } + final boolean isLive() { return thread != null; } } /** @@ -280,1832 +1695,89 @@ public class CompletableFuture implements Future, CompletionStage { * interrupted. */ private Object waitingGet(boolean interruptible) { - WaitNode q = null; + Signaller q = null; boolean queued = false; - int spins = SPINS; - for (Object r;;) { - if ((r = result) != null) { - if (q != null) { // suppress unpark - q.thread = null; - if (q.interruptControl < 0) { - if (interruptible) { - removeWaiter(q); - return null; - } - Thread.currentThread().interrupt(); - } - } - postComplete(); // help release others - return r; - } + int spins = -1; + Object r; + while ((r = result) == null) { + if (spins < 0) + spins = (Runtime.getRuntime().availableProcessors() > 1) ? + 1 << 8 : 0; // Use brief spin-wait on multiprocessors else if (spins > 0) { - int rnd = ThreadLocalRandom.nextSecondarySeed(); - if (rnd == 0) - rnd = ThreadLocalRandom.current().nextInt(); - if (rnd >= 0) + if (ThreadLocalRandom.nextSecondarySeed() >= 0) --spins; } else if (q == null) - q = new WaitNode(interruptible, 0L, 0L); + q = new Signaller(interruptible, 0L, 0L); else if (!queued) - queued = UNSAFE.compareAndSwapObject(this, WAITERS, - q.next = waiters, q); + queued = tryPushStack(q); else if (interruptible && q.interruptControl < 0) { - removeWaiter(q); + q.thread = null; + cleanStack(); return null; } else if (q.thread != null && result == null) { try { ForkJoinPool.managedBlock(q); - } catch (InterruptedException ex) { + } catch (InterruptedException ie) { q.interruptControl = -1; } } } + if (q != null) { + q.thread = null; + if (q.interruptControl < 0) { + if (interruptible) + r = null; // report interruption + else + Thread.currentThread().interrupt(); + } + } + postComplete(); + return r; } /** - * Awaits completion or aborts on interrupt or timeout. - * - * @param nanos time to wait - * @return raw result + * Returns raw result after waiting, or null if interrupted, or + * throws TimeoutException on timeout. */ - private Object timedAwaitDone(long nanos) - throws InterruptedException, TimeoutException { - WaitNode q = null; + private Object timedGet(long nanos) throws TimeoutException { + if (Thread.interrupted()) + return null; + if (nanos <= 0L) + throw new TimeoutException(); + long d = System.nanoTime() + nanos; + Signaller q = new Signaller(true, nanos, d == 0L ? 1L : d); // avoid 0 boolean queued = false; - for (Object r;;) { - if ((r = result) != null) { - if (q != null) { - q.thread = null; - if (q.interruptControl < 0) { - removeWaiter(q); - throw new InterruptedException(); - } - } - postComplete(); - return r; - } - else if (q == null) { - if (nanos <= 0L) - throw new TimeoutException(); - long d = System.nanoTime() + nanos; - q = new WaitNode(true, nanos, d == 0L ? 1L : d); // avoid 0 - } - else if (!queued) - queued = UNSAFE.compareAndSwapObject(this, WAITERS, - q.next = waiters, q); - else if (q.interruptControl < 0) { - removeWaiter(q); - throw new InterruptedException(); - } - else if (q.nanos <= 0L) { - if (result == null) { - removeWaiter(q); - throw new TimeoutException(); - } + Object r; + // We intentionally don't spin here (as waitingGet does) because + // the call to nanoTime() above acts much like a spin. + while ((r = result) == null) { + if (!queued) + queued = tryPushStack(q); + else if (q.interruptControl < 0 || q.nanos <= 0L) { + q.thread = null; + cleanStack(); + if (q.interruptControl < 0) + return null; + throw new TimeoutException(); } else if (q.thread != null && result == null) { try { ForkJoinPool.managedBlock(q); - } catch (InterruptedException ex) { + } catch (InterruptedException ie) { q.interruptControl = -1; } } } + if (q.interruptControl < 0) + r = null; + q.thread = null; + postComplete(); + return r; } - /** - * Tries to unlink a timed-out or interrupted wait node to avoid - * accumulating garbage. Internal nodes are simply unspliced - * without CAS since it is harmless if they are traversed anyway - * by releasers. To avoid effects of unsplicing from already - * removed nodes, the list is retraversed in case of an apparent - * race. This is slow when there are a lot of nodes, but we don't - * expect lists to be long enough to outweigh higher-overhead - * schemes. - */ - private void removeWaiter(WaitNode node) { - if (node != null) { - node.thread = null; - retry: - for (;;) { // restart on removeWaiter race - for (WaitNode pred = null, q = waiters, s; q != null; q = s) { - s = q.next; - if (q.thread != null) - pred = q; - else if (pred != null) { - pred.next = s; - if (pred.thread == null) // check for race - continue retry; - } - else if (!UNSAFE.compareAndSwapObject(this, WAITERS, q, s)) - continue retry; - } - break; - } - } - } - - /* ------------- Async tasks -------------- */ - - /** - * A marker interface identifying asynchronous tasks produced by - * {@code async} methods. This may be useful for monitoring, - * debugging, and tracking asynchronous activities. - * - * @since 1.8 - */ - public static interface AsynchronousCompletionTask { - } - - /** Base class can act as either FJ or plain Runnable */ - @SuppressWarnings("serial") - abstract static class Async extends ForkJoinTask - implements Runnable, AsynchronousCompletionTask { - public final Void getRawResult() { return null; } - public final void setRawResult(Void v) { } - public final void run() { exec(); } - } - - /** - * Starts the given async task using the given executor, unless - * the executor is ForkJoinPool.commonPool and it has been - * disabled, in which case starts a new thread. - */ - static void execAsync(Executor e, Async r) { - if (e == ForkJoinPool.commonPool() && - ForkJoinPool.getCommonPoolParallelism() <= 1) - new Thread(r).start(); - else - e.execute(r); - } - - static final class AsyncRun extends Async { - final Runnable fn; - final CompletableFuture dst; - AsyncRun(Runnable fn, CompletableFuture dst) { - this.fn = fn; this.dst = dst; - } - public final boolean exec() { - CompletableFuture d; Throwable ex; - if ((d = this.dst) != null && d.result == null) { - try { - fn.run(); - ex = null; - } catch (Throwable rex) { - ex = rex; - } - d.internalComplete(null, ex); - } - return true; - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class AsyncSupply extends Async { - final Supplier fn; - final CompletableFuture dst; - AsyncSupply(Supplier fn, CompletableFuture dst) { - this.fn = fn; this.dst = dst; - } - public final boolean exec() { - CompletableFuture d; U u; Throwable ex; - if ((d = this.dst) != null && d.result == null) { - try { - u = fn.get(); - ex = null; - } catch (Throwable rex) { - ex = rex; - u = null; - } - d.internalComplete(u, ex); - } - return true; - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class AsyncApply extends Async { - final T arg; - final Function fn; - final CompletableFuture dst; - AsyncApply(T arg, Function fn, - CompletableFuture dst) { - this.arg = arg; this.fn = fn; this.dst = dst; - } - public final boolean exec() { - CompletableFuture d; U u; Throwable ex; - if ((d = this.dst) != null && d.result == null) { - try { - u = fn.apply(arg); - ex = null; - } catch (Throwable rex) { - ex = rex; - u = null; - } - d.internalComplete(u, ex); - } - return true; - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class AsyncCombine extends Async { - final T arg1; - final U arg2; - final BiFunction fn; - final CompletableFuture dst; - AsyncCombine(T arg1, U arg2, - BiFunction fn, - CompletableFuture dst) { - this.arg1 = arg1; this.arg2 = arg2; this.fn = fn; this.dst = dst; - } - public final boolean exec() { - CompletableFuture d; V v; Throwable ex; - if ((d = this.dst) != null && d.result == null) { - try { - v = fn.apply(arg1, arg2); - ex = null; - } catch (Throwable rex) { - ex = rex; - v = null; - } - d.internalComplete(v, ex); - } - return true; - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class AsyncAccept extends Async { - final T arg; - final Consumer fn; - final CompletableFuture dst; - AsyncAccept(T arg, Consumer fn, - CompletableFuture dst) { - this.arg = arg; this.fn = fn; this.dst = dst; - } - public final boolean exec() { - CompletableFuture d; Throwable ex; - if ((d = this.dst) != null && d.result == null) { - try { - fn.accept(arg); - ex = null; - } catch (Throwable rex) { - ex = rex; - } - d.internalComplete(null, ex); - } - return true; - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class AsyncAcceptBoth extends Async { - final T arg1; - final U arg2; - final BiConsumer fn; - final CompletableFuture dst; - AsyncAcceptBoth(T arg1, U arg2, - BiConsumer fn, - CompletableFuture dst) { - this.arg1 = arg1; this.arg2 = arg2; this.fn = fn; this.dst = dst; - } - public final boolean exec() { - CompletableFuture d; Throwable ex; - if ((d = this.dst) != null && d.result == null) { - try { - fn.accept(arg1, arg2); - ex = null; - } catch (Throwable rex) { - ex = rex; - } - d.internalComplete(null, ex); - } - return true; - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class AsyncCompose extends Async { - final T arg; - final Function> fn; - final CompletableFuture dst; - AsyncCompose(T arg, - Function> fn, - CompletableFuture dst) { - this.arg = arg; this.fn = fn; this.dst = dst; - } - public final boolean exec() { - CompletableFuture d, fr; U u; Throwable ex; - if ((d = this.dst) != null && d.result == null) { - try { - CompletionStage cs = fn.apply(arg); - fr = (cs == null) ? null : cs.toCompletableFuture(); - ex = (fr == null) ? new NullPointerException() : null; - } catch (Throwable rex) { - ex = rex; - fr = null; - } - if (ex != null) - u = null; - else { - Object r = fr.result; - if (r == null) - r = fr.waitingGet(false); - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - u = null; - } - else { - @SuppressWarnings("unchecked") U ur = (U) r; - u = ur; - } - } - d.internalComplete(u, ex); - } - return true; - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class AsyncWhenComplete extends Async { - final T arg1; - final Throwable arg2; - final BiConsumer fn; - final CompletableFuture dst; - AsyncWhenComplete(T arg1, Throwable arg2, - BiConsumer fn, - CompletableFuture dst) { - this.arg1 = arg1; this.arg2 = arg2; this.fn = fn; this.dst = dst; - } - public final boolean exec() { - CompletableFuture d; - if ((d = this.dst) != null && d.result == null) { - Throwable ex = arg2; - try { - fn.accept(arg1, ex); - } catch (Throwable rex) { - if (ex == null) - ex = rex; - } - d.internalComplete(arg1, ex); - } - return true; - } - private static final long serialVersionUID = 5232453952276885070L; - } - - /* ------------- Completions -------------- */ - - /** - * Simple linked list nodes to record completions, used in - * basically the same way as WaitNodes. (We separate nodes from - * the Completions themselves mainly because for the And and Or - * methods, the same Completion object resides in two lists.) - */ - static final class CompletionNode { - final Completion completion; - volatile CompletionNode next; - CompletionNode(Completion completion) { this.completion = completion; } - } - - // Opportunistically subclass AtomicInteger to use compareAndSet to claim. - @SuppressWarnings("serial") - abstract static class Completion extends AtomicInteger implements Runnable { - } - - static final class ThenApply extends Completion { - final CompletableFuture src; - final Function fn; - final CompletableFuture dst; - final Executor executor; - ThenApply(CompletableFuture src, - Function fn, - CompletableFuture dst, - Executor executor) { - this.src = src; this.fn = fn; this.dst = dst; - this.executor = executor; - } - public final void run() { - final CompletableFuture a; - final Function fn; - final CompletableFuture dst; - Object r; T t; Throwable ex; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (a = this.src) != null && - (r = a.result) != null && - compareAndSet(0, 1)) { - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - Executor e = executor; - U u = null; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncApply(t, fn, dst)); - else - u = fn.apply(t); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(u, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class ThenAccept extends Completion { - final CompletableFuture src; - final Consumer fn; - final CompletableFuture dst; - final Executor executor; - ThenAccept(CompletableFuture src, - Consumer fn, - CompletableFuture dst, - Executor executor) { - this.src = src; this.fn = fn; this.dst = dst; - this.executor = executor; - } - public final void run() { - final CompletableFuture a; - final Consumer fn; - final CompletableFuture dst; - Object r; T t; Throwable ex; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (a = this.src) != null && - (r = a.result) != null && - compareAndSet(0, 1)) { - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - Executor e = executor; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncAccept(t, fn, dst)); - else - fn.accept(t); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(null, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class ThenRun extends Completion { - final CompletableFuture src; - final Runnable fn; - final CompletableFuture dst; - final Executor executor; - ThenRun(CompletableFuture src, - Runnable fn, - CompletableFuture dst, - Executor executor) { - this.src = src; this.fn = fn; this.dst = dst; - this.executor = executor; - } - public final void run() { - final CompletableFuture a; - final Runnable fn; - final CompletableFuture dst; - Object r; Throwable ex; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (a = this.src) != null && - (r = a.result) != null && - compareAndSet(0, 1)) { - if (r instanceof AltResult) - ex = ((AltResult)r).ex; - else - ex = null; - Executor e = executor; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncRun(fn, dst)); - else - fn.run(); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(null, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class ThenCombine extends Completion { - final CompletableFuture src; - final CompletableFuture snd; - final BiFunction fn; - final CompletableFuture dst; - final Executor executor; - ThenCombine(CompletableFuture src, - CompletableFuture snd, - BiFunction fn, - CompletableFuture dst, - Executor executor) { - this.src = src; this.snd = snd; - this.fn = fn; this.dst = dst; - this.executor = executor; - } - public final void run() { - final CompletableFuture a; - final CompletableFuture b; - final BiFunction fn; - final CompletableFuture dst; - Object r, s; T t; U u; Throwable ex; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (a = this.src) != null && - (r = a.result) != null && - (b = this.snd) != null && - (s = b.result) != null && - compareAndSet(0, 1)) { - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - if (ex != null) - u = null; - else if (s instanceof AltResult) { - ex = ((AltResult)s).ex; - u = null; - } - else { - @SuppressWarnings("unchecked") U us = (U) s; - u = us; - } - Executor e = executor; - V v = null; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncCombine(t, u, fn, dst)); - else - v = fn.apply(t, u); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(v, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class ThenAcceptBoth extends Completion { - final CompletableFuture src; - final CompletableFuture snd; - final BiConsumer fn; - final CompletableFuture dst; - final Executor executor; - ThenAcceptBoth(CompletableFuture src, - CompletableFuture snd, - BiConsumer fn, - CompletableFuture dst, - Executor executor) { - this.src = src; this.snd = snd; - this.fn = fn; this.dst = dst; - this.executor = executor; - } - public final void run() { - final CompletableFuture a; - final CompletableFuture b; - final BiConsumer fn; - final CompletableFuture dst; - Object r, s; T t; U u; Throwable ex; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (a = this.src) != null && - (r = a.result) != null && - (b = this.snd) != null && - (s = b.result) != null && - compareAndSet(0, 1)) { - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - if (ex != null) - u = null; - else if (s instanceof AltResult) { - ex = ((AltResult)s).ex; - u = null; - } - else { - @SuppressWarnings("unchecked") U us = (U) s; - u = us; - } - Executor e = executor; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncAcceptBoth(t, u, fn, dst)); - else - fn.accept(t, u); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(null, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class RunAfterBoth extends Completion { - final CompletableFuture src; - final CompletableFuture snd; - final Runnable fn; - final CompletableFuture dst; - final Executor executor; - RunAfterBoth(CompletableFuture src, - CompletableFuture snd, - Runnable fn, - CompletableFuture dst, - Executor executor) { - this.src = src; this.snd = snd; - this.fn = fn; this.dst = dst; - this.executor = executor; - } - public final void run() { - final CompletableFuture a; - final CompletableFuture b; - final Runnable fn; - final CompletableFuture dst; - Object r, s; Throwable ex; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (a = this.src) != null && - (r = a.result) != null && - (b = this.snd) != null && - (s = b.result) != null && - compareAndSet(0, 1)) { - if (r instanceof AltResult) - ex = ((AltResult)r).ex; - else - ex = null; - if (ex == null && (s instanceof AltResult)) - ex = ((AltResult)s).ex; - Executor e = executor; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncRun(fn, dst)); - else - fn.run(); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(null, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class AndCompletion extends Completion { - final CompletableFuture src; - final CompletableFuture snd; - final CompletableFuture dst; - AndCompletion(CompletableFuture src, - CompletableFuture snd, - CompletableFuture dst) { - this.src = src; this.snd = snd; this.dst = dst; - } - public final void run() { - final CompletableFuture a; - final CompletableFuture b; - final CompletableFuture dst; - Object r, s; Throwable ex; - if ((dst = this.dst) != null && - (a = this.src) != null && - (r = a.result) != null && - (b = this.snd) != null && - (s = b.result) != null && - compareAndSet(0, 1)) { - if (r instanceof AltResult) - ex = ((AltResult)r).ex; - else - ex = null; - if (ex == null && (s instanceof AltResult)) - ex = ((AltResult)s).ex; - dst.internalComplete(null, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class ApplyToEither extends Completion { - final CompletableFuture src; - final CompletableFuture snd; - final Function fn; - final CompletableFuture dst; - final Executor executor; - ApplyToEither(CompletableFuture src, - CompletableFuture snd, - Function fn, - CompletableFuture dst, - Executor executor) { - this.src = src; this.snd = snd; - this.fn = fn; this.dst = dst; - this.executor = executor; - } - public final void run() { - final CompletableFuture a; - final CompletableFuture b; - final Function fn; - final CompletableFuture dst; - Object r; T t; Throwable ex; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (((a = this.src) != null && (r = a.result) != null) || - ((b = this.snd) != null && (r = b.result) != null)) && - compareAndSet(0, 1)) { - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - Executor e = executor; - U u = null; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncApply(t, fn, dst)); - else - u = fn.apply(t); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(u, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class AcceptEither extends Completion { - final CompletableFuture src; - final CompletableFuture snd; - final Consumer fn; - final CompletableFuture dst; - final Executor executor; - AcceptEither(CompletableFuture src, - CompletableFuture snd, - Consumer fn, - CompletableFuture dst, - Executor executor) { - this.src = src; this.snd = snd; - this.fn = fn; this.dst = dst; - this.executor = executor; - } - public final void run() { - final CompletableFuture a; - final CompletableFuture b; - final Consumer fn; - final CompletableFuture dst; - Object r; T t; Throwable ex; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (((a = this.src) != null && (r = a.result) != null) || - ((b = this.snd) != null && (r = b.result) != null)) && - compareAndSet(0, 1)) { - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - Executor e = executor; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncAccept(t, fn, dst)); - else - fn.accept(t); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(null, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class RunAfterEither extends Completion { - final CompletableFuture src; - final CompletableFuture snd; - final Runnable fn; - final CompletableFuture dst; - final Executor executor; - RunAfterEither(CompletableFuture src, - CompletableFuture snd, - Runnable fn, - CompletableFuture dst, - Executor executor) { - this.src = src; this.snd = snd; - this.fn = fn; this.dst = dst; - this.executor = executor; - } - public final void run() { - final CompletableFuture a; - final CompletableFuture b; - final Runnable fn; - final CompletableFuture dst; - Object r; Throwable ex; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (((a = this.src) != null && (r = a.result) != null) || - ((b = this.snd) != null && (r = b.result) != null)) && - compareAndSet(0, 1)) { - if (r instanceof AltResult) - ex = ((AltResult)r).ex; - else - ex = null; - Executor e = executor; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncRun(fn, dst)); - else - fn.run(); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(null, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class OrCompletion extends Completion { - final CompletableFuture src; - final CompletableFuture snd; - final CompletableFuture dst; - OrCompletion(CompletableFuture src, - CompletableFuture snd, - CompletableFuture dst) { - this.src = src; this.snd = snd; this.dst = dst; - } - public final void run() { - final CompletableFuture a; - final CompletableFuture b; - final CompletableFuture dst; - Object r, t; Throwable ex; - if ((dst = this.dst) != null && - (((a = this.src) != null && (r = a.result) != null) || - ((b = this.snd) != null && (r = b.result) != null)) && - compareAndSet(0, 1)) { - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - t = r; - } - dst.internalComplete(t, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class ExceptionCompletion extends Completion { - final CompletableFuture src; - final Function fn; - final CompletableFuture dst; - ExceptionCompletion(CompletableFuture src, - Function fn, - CompletableFuture dst) { - this.src = src; this.fn = fn; this.dst = dst; - } - public final void run() { - final CompletableFuture a; - final Function fn; - final CompletableFuture dst; - Object r; T t = null; Throwable ex, dx = null; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (a = this.src) != null && - (r = a.result) != null && - compareAndSet(0, 1)) { - if ((r instanceof AltResult) && - (ex = ((AltResult)r).ex) != null) { - try { - t = fn.apply(ex); - } catch (Throwable rex) { - dx = rex; - } - } - else { - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - dst.internalComplete(t, dx); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class WhenCompleteCompletion extends Completion { - final CompletableFuture src; - final BiConsumer fn; - final CompletableFuture dst; - final Executor executor; - WhenCompleteCompletion(CompletableFuture src, - BiConsumer fn, - CompletableFuture dst, - Executor executor) { - this.src = src; this.fn = fn; this.dst = dst; - this.executor = executor; - } - public final void run() { - final CompletableFuture a; - final BiConsumer fn; - final CompletableFuture dst; - Object r; T t; Throwable ex; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (a = this.src) != null && - (r = a.result) != null && - compareAndSet(0, 1)) { - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - Executor e = executor; - Throwable dx = null; - try { - if (e != null) - execAsync(e, new AsyncWhenComplete(t, ex, fn, dst)); - else - fn.accept(t, ex); - } catch (Throwable rex) { - dx = rex; - } - if (e == null || dx != null) - dst.internalComplete(t, ex != null ? ex : dx); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class ThenCopy extends Completion { - final CompletableFuture src; - final CompletableFuture dst; - ThenCopy(CompletableFuture src, - CompletableFuture dst) { - this.src = src; this.dst = dst; - } - public final void run() { - final CompletableFuture a; - final CompletableFuture dst; - Object r; T t; Throwable ex; - if ((dst = this.dst) != null && - (a = this.src) != null && - (r = a.result) != null && - compareAndSet(0, 1)) { - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - dst.internalComplete(t, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - // version of ThenCopy for CompletableFuture dst - static final class ThenPropagate extends Completion { - final CompletableFuture src; - final CompletableFuture dst; - ThenPropagate(CompletableFuture src, - CompletableFuture dst) { - this.src = src; this.dst = dst; - } - public final void run() { - final CompletableFuture a; - final CompletableFuture dst; - Object r; Throwable ex; - if ((dst = this.dst) != null && - (a = this.src) != null && - (r = a.result) != null && - compareAndSet(0, 1)) { - if (r instanceof AltResult) - ex = ((AltResult)r).ex; - else - ex = null; - dst.internalComplete(null, ex); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class HandleCompletion extends Completion { - final CompletableFuture src; - final BiFunction fn; - final CompletableFuture dst; - final Executor executor; - HandleCompletion(CompletableFuture src, - BiFunction fn, - CompletableFuture dst, - Executor executor) { - this.src = src; this.fn = fn; this.dst = dst; - this.executor = executor; - } - public final void run() { - final CompletableFuture a; - final BiFunction fn; - final CompletableFuture dst; - Object r; T t; Throwable ex; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (a = this.src) != null && - (r = a.result) != null && - compareAndSet(0, 1)) { - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - Executor e = executor; - U u = null; - Throwable dx = null; - try { - if (e != null) - execAsync(e, new AsyncCombine(t, ex, fn, dst)); - else - u = fn.apply(t, ex); - } catch (Throwable rex) { - dx = rex; - } - if (e == null || dx != null) - dst.internalComplete(u, dx); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - static final class ThenCompose extends Completion { - final CompletableFuture src; - final Function> fn; - final CompletableFuture dst; - final Executor executor; - ThenCompose(CompletableFuture src, - Function> fn, - CompletableFuture dst, - Executor executor) { - this.src = src; this.fn = fn; this.dst = dst; - this.executor = executor; - } - public final void run() { - final CompletableFuture a; - final Function> fn; - final CompletableFuture dst; - Object r; T t; Throwable ex; Executor e; - if ((dst = this.dst) != null && - (fn = this.fn) != null && - (a = this.src) != null && - (r = a.result) != null && - compareAndSet(0, 1)) { - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - CompletableFuture c = null; - U u = null; - boolean complete = false; - if (ex == null) { - if ((e = executor) != null) - execAsync(e, new AsyncCompose(t, fn, dst)); - else { - try { - CompletionStage cs = fn.apply(t); - c = (cs == null) ? null : cs.toCompletableFuture(); - if (c == null) - ex = new NullPointerException(); - } catch (Throwable rex) { - ex = rex; - } - } - } - if (c != null) { - ThenCopy d = null; - Object s; - if ((s = c.result) == null) { - CompletionNode p = new CompletionNode - (d = new ThenCopy(c, dst)); - while ((s = c.result) == null) { - if (UNSAFE.compareAndSwapObject - (c, COMPLETIONS, p.next = c.completions, p)) - break; - } - } - if (s != null && (d == null || d.compareAndSet(0, 1))) { - complete = true; - if (s instanceof AltResult) { - ex = ((AltResult)s).ex; // no rewrap - u = null; - } - else { - @SuppressWarnings("unchecked") U us = (U) s; - u = us; - } - } - } - if (complete || ex != null) - dst.internalComplete(u, ex); - if (c != null) - c.helpPostComplete(); - } - } - private static final long serialVersionUID = 5232453952276885070L; - } - - // Implementations of stage methods with (plain, async, Executor) forms - - private CompletableFuture doThenApply - (Function fn, - Executor e) { - if (fn == null) throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - ThenApply d = null; - Object r; - if ((r = result) == null) { - CompletionNode p = new CompletionNode - (d = new ThenApply(this, fn, dst, e)); - while ((r = result) == null) { - if (UNSAFE.compareAndSwapObject - (this, COMPLETIONS, p.next = completions, p)) - break; - } - } - if (r != null && (d == null || d.compareAndSet(0, 1))) { - T t; Throwable ex; - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - U u = null; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncApply(t, fn, dst)); - else - u = fn.apply(t); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(u, ex); - } - helpPostComplete(); - return dst; - } - - private CompletableFuture doThenAccept(Consumer fn, - Executor e) { - if (fn == null) throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - ThenAccept d = null; - Object r; - if ((r = result) == null) { - CompletionNode p = new CompletionNode - (d = new ThenAccept(this, fn, dst, e)); - while ((r = result) == null) { - if (UNSAFE.compareAndSwapObject - (this, COMPLETIONS, p.next = completions, p)) - break; - } - } - if (r != null && (d == null || d.compareAndSet(0, 1))) { - T t; Throwable ex; - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncAccept(t, fn, dst)); - else - fn.accept(t); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(null, ex); - } - helpPostComplete(); - return dst; - } - - private CompletableFuture doThenRun(Runnable action, - Executor e) { - if (action == null) throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - ThenRun d = null; - Object r; - if ((r = result) == null) { - CompletionNode p = new CompletionNode - (d = new ThenRun(this, action, dst, e)); - while ((r = result) == null) { - if (UNSAFE.compareAndSwapObject - (this, COMPLETIONS, p.next = completions, p)) - break; - } - } - if (r != null && (d == null || d.compareAndSet(0, 1))) { - Throwable ex; - if (r instanceof AltResult) - ex = ((AltResult)r).ex; - else - ex = null; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncRun(action, dst)); - else - action.run(); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(null, ex); - } - helpPostComplete(); - return dst; - } - - private CompletableFuture doThenCombine - (CompletableFuture other, - BiFunction fn, - Executor e) { - if (other == null || fn == null) throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - ThenCombine d = null; - Object r, s = null; - if ((r = result) == null || (s = other.result) == null) { - d = new ThenCombine(this, other, fn, dst, e); - CompletionNode q = null, p = new CompletionNode(d); - while ((r == null && (r = result) == null) || - (s == null && (s = other.result) == null)) { - if (q != null) { - if (s != null || - UNSAFE.compareAndSwapObject - (other, COMPLETIONS, q.next = other.completions, q)) - break; - } - else if (r != null || - UNSAFE.compareAndSwapObject - (this, COMPLETIONS, p.next = completions, p)) { - if (s != null) - break; - q = new CompletionNode(d); - } - } - } - if (r != null && s != null && (d == null || d.compareAndSet(0, 1))) { - T t; U u; Throwable ex; - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - if (ex != null) - u = null; - else if (s instanceof AltResult) { - ex = ((AltResult)s).ex; - u = null; - } - else { - @SuppressWarnings("unchecked") U us = (U) s; - u = us; - } - V v = null; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncCombine(t, u, fn, dst)); - else - v = fn.apply(t, u); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(v, ex); - } - helpPostComplete(); - other.helpPostComplete(); - return dst; - } - - private CompletableFuture doThenAcceptBoth - (CompletableFuture other, - BiConsumer fn, - Executor e) { - if (other == null || fn == null) throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - ThenAcceptBoth d = null; - Object r, s = null; - if ((r = result) == null || (s = other.result) == null) { - d = new ThenAcceptBoth(this, other, fn, dst, e); - CompletionNode q = null, p = new CompletionNode(d); - while ((r == null && (r = result) == null) || - (s == null && (s = other.result) == null)) { - if (q != null) { - if (s != null || - UNSAFE.compareAndSwapObject - (other, COMPLETIONS, q.next = other.completions, q)) - break; - } - else if (r != null || - UNSAFE.compareAndSwapObject - (this, COMPLETIONS, p.next = completions, p)) { - if (s != null) - break; - q = new CompletionNode(d); - } - } - } - if (r != null && s != null && (d == null || d.compareAndSet(0, 1))) { - T t; U u; Throwable ex; - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - if (ex != null) - u = null; - else if (s instanceof AltResult) { - ex = ((AltResult)s).ex; - u = null; - } - else { - @SuppressWarnings("unchecked") U us = (U) s; - u = us; - } - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncAcceptBoth(t, u, fn, dst)); - else - fn.accept(t, u); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(null, ex); - } - helpPostComplete(); - other.helpPostComplete(); - return dst; - } - - private CompletableFuture doRunAfterBoth(CompletableFuture other, - Runnable action, - Executor e) { - if (other == null || action == null) throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - RunAfterBoth d = null; - Object r, s = null; - if ((r = result) == null || (s = other.result) == null) { - d = new RunAfterBoth(this, other, action, dst, e); - CompletionNode q = null, p = new CompletionNode(d); - while ((r == null && (r = result) == null) || - (s == null && (s = other.result) == null)) { - if (q != null) { - if (s != null || - UNSAFE.compareAndSwapObject - (other, COMPLETIONS, q.next = other.completions, q)) - break; - } - else if (r != null || - UNSAFE.compareAndSwapObject - (this, COMPLETIONS, p.next = completions, p)) { - if (s != null) - break; - q = new CompletionNode(d); - } - } - } - if (r != null && s != null && (d == null || d.compareAndSet(0, 1))) { - Throwable ex; - if (r instanceof AltResult) - ex = ((AltResult)r).ex; - else - ex = null; - if (ex == null && (s instanceof AltResult)) - ex = ((AltResult)s).ex; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncRun(action, dst)); - else - action.run(); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(null, ex); - } - helpPostComplete(); - other.helpPostComplete(); - return dst; - } - - private CompletableFuture doApplyToEither - (CompletableFuture other, - Function fn, - Executor e) { - if (other == null || fn == null) throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - ApplyToEither d = null; - Object r; - if ((r = result) == null && (r = other.result) == null) { - d = new ApplyToEither(this, other, fn, dst, e); - CompletionNode q = null, p = new CompletionNode(d); - while ((r = result) == null && (r = other.result) == null) { - if (q != null) { - if (UNSAFE.compareAndSwapObject - (other, COMPLETIONS, q.next = other.completions, q)) - break; - } - else if (UNSAFE.compareAndSwapObject - (this, COMPLETIONS, p.next = completions, p)) - q = new CompletionNode(d); - } - } - if (r != null && (d == null || d.compareAndSet(0, 1))) { - T t; Throwable ex; - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - U u = null; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncApply(t, fn, dst)); - else - u = fn.apply(t); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(u, ex); - } - helpPostComplete(); - other.helpPostComplete(); - return dst; - } - - private CompletableFuture doAcceptEither - (CompletableFuture other, - Consumer fn, - Executor e) { - if (other == null || fn == null) throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - AcceptEither d = null; - Object r; - if ((r = result) == null && (r = other.result) == null) { - d = new AcceptEither(this, other, fn, dst, e); - CompletionNode q = null, p = new CompletionNode(d); - while ((r = result) == null && (r = other.result) == null) { - if (q != null) { - if (UNSAFE.compareAndSwapObject - (other, COMPLETIONS, q.next = other.completions, q)) - break; - } - else if (UNSAFE.compareAndSwapObject - (this, COMPLETIONS, p.next = completions, p)) - q = new CompletionNode(d); - } - } - if (r != null && (d == null || d.compareAndSet(0, 1))) { - T t; Throwable ex; - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncAccept(t, fn, dst)); - else - fn.accept(t); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(null, ex); - } - helpPostComplete(); - other.helpPostComplete(); - return dst; - } - - private CompletableFuture doRunAfterEither - (CompletableFuture other, - Runnable action, - Executor e) { - if (other == null || action == null) throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - RunAfterEither d = null; - Object r; - if ((r = result) == null && (r = other.result) == null) { - d = new RunAfterEither(this, other, action, dst, e); - CompletionNode q = null, p = new CompletionNode(d); - while ((r = result) == null && (r = other.result) == null) { - if (q != null) { - if (UNSAFE.compareAndSwapObject - (other, COMPLETIONS, q.next = other.completions, q)) - break; - } - else if (UNSAFE.compareAndSwapObject - (this, COMPLETIONS, p.next = completions, p)) - q = new CompletionNode(d); - } - } - if (r != null && (d == null || d.compareAndSet(0, 1))) { - Throwable ex; - if (r instanceof AltResult) - ex = ((AltResult)r).ex; - else - ex = null; - if (ex == null) { - try { - if (e != null) - execAsync(e, new AsyncRun(action, dst)); - else - action.run(); - } catch (Throwable rex) { - ex = rex; - } - } - if (e == null || ex != null) - dst.internalComplete(null, ex); - } - helpPostComplete(); - other.helpPostComplete(); - return dst; - } - - private CompletableFuture doThenCompose - (Function> fn, - Executor e) { - if (fn == null) throw new NullPointerException(); - CompletableFuture dst = null; - ThenCompose d = null; - Object r; - if ((r = result) == null) { - dst = new CompletableFuture(); - CompletionNode p = new CompletionNode - (d = new ThenCompose(this, fn, dst, e)); - while ((r = result) == null) { - if (UNSAFE.compareAndSwapObject - (this, COMPLETIONS, p.next = completions, p)) - break; - } - } - if (r != null && (d == null || d.compareAndSet(0, 1))) { - T t; Throwable ex; - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - if (ex == null) { - if (e != null) { - if (dst == null) - dst = new CompletableFuture(); - execAsync(e, new AsyncCompose(t, fn, dst)); - } - else { - try { - CompletionStage cs = fn.apply(t); - if (cs == null || - (dst = cs.toCompletableFuture()) == null) - ex = new NullPointerException(); - } catch (Throwable rex) { - ex = rex; - } - } - } - if (dst == null) - dst = new CompletableFuture(); - if (ex != null) - dst.internalComplete(null, ex); - } - helpPostComplete(); - dst.helpPostComplete(); - return dst; - } - - private CompletableFuture doWhenComplete - (BiConsumer fn, - Executor e) { - if (fn == null) throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - WhenCompleteCompletion d = null; - Object r; - if ((r = result) == null) { - CompletionNode p = - new CompletionNode(d = new WhenCompleteCompletion - (this, fn, dst, e)); - while ((r = result) == null) { - if (UNSAFE.compareAndSwapObject(this, COMPLETIONS, - p.next = completions, p)) - break; - } - } - if (r != null && (d == null || d.compareAndSet(0, 1))) { - T t; Throwable ex; - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - Throwable dx = null; - try { - if (e != null) - execAsync(e, new AsyncWhenComplete(t, ex, fn, dst)); - else - fn.accept(t, ex); - } catch (Throwable rex) { - dx = rex; - } - if (e == null || dx != null) - dst.internalComplete(t, ex != null ? ex : dx); - } - helpPostComplete(); - return dst; - } - - private CompletableFuture doHandle - (BiFunction fn, - Executor e) { - if (fn == null) throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - HandleCompletion d = null; - Object r; - if ((r = result) == null) { - CompletionNode p = - new CompletionNode(d = new HandleCompletion - (this, fn, dst, e)); - while ((r = result) == null) { - if (UNSAFE.compareAndSwapObject(this, COMPLETIONS, - p.next = completions, p)) - break; - } - } - if (r != null && (d == null || d.compareAndSet(0, 1))) { - T t; Throwable ex; - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - U u = null; - Throwable dx = null; - try { - if (e != null) - execAsync(e, new AsyncCombine(t, ex, fn, dst)); - else { - u = fn.apply(t, ex); - dx = null; - } - } catch (Throwable rex) { - dx = rex; - u = null; - } - if (e == null || dx != null) - dst.internalComplete(u, dx); - } - helpPostComplete(); - return dst; - } - - - // public methods + /* ------------- public methods -------------- */ /** * Creates a new incomplete CompletableFuture. @@ -2113,6 +1785,13 @@ public class CompletableFuture implements Future, CompletionStage { public CompletableFuture() { } + /** + * Creates a new complete CompletableFuture with given encoded result. + */ + private CompletableFuture(Object r) { + this.result = r; + } + /** * Returns a new CompletableFuture that is asynchronously completed * by a task running in the {@link ForkJoinPool#commonPool()} with @@ -2124,10 +1803,7 @@ public class CompletableFuture implements Future, CompletionStage { * @return the new CompletableFuture */ public static CompletableFuture supplyAsync(Supplier supplier) { - if (supplier == null) throw new NullPointerException(); - CompletableFuture f = new CompletableFuture(); - execAsync(ForkJoinPool.commonPool(), new AsyncSupply(supplier, f)); - return f; + return asyncSupplyStage(asyncPool, supplier); } /** @@ -2143,11 +1819,7 @@ public class CompletableFuture implements Future, CompletionStage { */ public static CompletableFuture supplyAsync(Supplier supplier, Executor executor) { - if (executor == null || supplier == null) - throw new NullPointerException(); - CompletableFuture f = new CompletableFuture(); - execAsync(executor, new AsyncSupply(supplier, f)); - return f; + return asyncSupplyStage(screenExecutor(executor), supplier); } /** @@ -2160,10 +1832,7 @@ public class CompletableFuture implements Future, CompletionStage { * @return the new CompletableFuture */ public static CompletableFuture runAsync(Runnable runnable) { - if (runnable == null) throw new NullPointerException(); - CompletableFuture f = new CompletableFuture(); - execAsync(ForkJoinPool.commonPool(), new AsyncRun(runnable, f)); - return f; + return asyncRunStage(asyncPool, runnable); } /** @@ -2178,11 +1847,7 @@ public class CompletableFuture implements Future, CompletionStage { */ public static CompletableFuture runAsync(Runnable runnable, Executor executor) { - if (executor == null || runnable == null) - throw new NullPointerException(); - CompletableFuture f = new CompletableFuture(); - execAsync(executor, new AsyncRun(runnable, f)); - return f; + return asyncRunStage(screenExecutor(executor), runnable); } /** @@ -2194,9 +1859,7 @@ public class CompletableFuture implements Future, CompletionStage { * @return the completed CompletableFuture */ public static CompletableFuture completedFuture(U value) { - CompletableFuture f = new CompletableFuture(); - f.result = (value == null) ? NIL : value; - return f; + return new CompletableFuture((value == null) ? NIL : value); } /** @@ -2220,21 +1883,8 @@ public class CompletableFuture implements Future, CompletionStage { * while waiting */ public T get() throws InterruptedException, ExecutionException { - Object r; Throwable ex, cause; - if ((r = result) == null && (r = waitingGet(true)) == null) - throw new InterruptedException(); - if (!(r instanceof AltResult)) { - @SuppressWarnings("unchecked") T tr = (T) r; - return tr; - } - if ((ex = ((AltResult)r).ex) == null) - return null; - if (ex instanceof CancellationException) - throw (CancellationException)ex; - if ((ex instanceof CompletionException) && - (cause = ex.getCause()) != null) - ex = cause; - throw new ExecutionException(ex); + Object r; + return reportGet((r = result) == null ? waitingGet(true) : r); } /** @@ -2252,24 +1902,9 @@ public class CompletableFuture implements Future, CompletionStage { */ public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { - Object r; Throwable ex, cause; + Object r; long nanos = unit.toNanos(timeout); - if (Thread.interrupted()) - throw new InterruptedException(); - if ((r = result) == null) - r = timedAwaitDone(nanos); - if (!(r instanceof AltResult)) { - @SuppressWarnings("unchecked") T tr = (T) r; - return tr; - } - if ((ex = ((AltResult)r).ex) == null) - return null; - if (ex instanceof CancellationException) - throw (CancellationException)ex; - if ((ex instanceof CompletionException) && - (cause = ex.getCause()) != null) - ex = cause; - throw new ExecutionException(ex); + return reportGet((r = result) == null ? timedGet(nanos) : r); } /** @@ -2287,20 +1922,8 @@ public class CompletableFuture implements Future, CompletionStage { * exceptionally or a completion computation threw an exception */ public T join() { - Object r; Throwable ex; - if ((r = result) == null) - r = waitingGet(false); - if (!(r instanceof AltResult)) { - @SuppressWarnings("unchecked") T tr = (T) r; - return tr; - } - if ((ex = ((AltResult)r).ex) == null) - return null; - if (ex instanceof CancellationException) - throw (CancellationException)ex; - if (ex instanceof CompletionException) - throw (CompletionException)ex; - throw new CompletionException(ex); + Object r; + return reportJoin((r = result) == null ? waitingGet(false) : r); } /** @@ -2314,20 +1937,8 @@ public class CompletableFuture implements Future, CompletionStage { * exceptionally or a completion computation threw an exception */ public T getNow(T valueIfAbsent) { - Object r; Throwable ex; - if ((r = result) == null) - return valueIfAbsent; - if (!(r instanceof AltResult)) { - @SuppressWarnings("unchecked") T tr = (T) r; - return tr; - } - if ((ex = ((AltResult)r).ex) == null) - return null; - if (ex instanceof CancellationException) - throw (CancellationException)ex; - if (ex instanceof CompletionException) - throw (CompletionException)ex; - throw new CompletionException(ex); + Object r; + return ((r = result) == null) ? valueIfAbsent : reportJoin(r); } /** @@ -2339,9 +1950,7 @@ public class CompletableFuture implements Future, CompletionStage { * to transition to a completed state, else {@code false} */ public boolean complete(T value) { - boolean triggered = result == null && - UNSAFE.compareAndSwapObject(this, RESULT, null, - value == null ? NIL : value); + boolean triggered = completeValue(value); postComplete(); return triggered; } @@ -2356,244 +1965,200 @@ public class CompletableFuture implements Future, CompletionStage { */ public boolean completeExceptionally(Throwable ex) { if (ex == null) throw new NullPointerException(); - boolean triggered = result == null && - UNSAFE.compareAndSwapObject(this, RESULT, null, new AltResult(ex)); + boolean triggered = internalComplete(new AltResult(ex)); postComplete(); return triggered; } - // CompletionStage methods - - public CompletableFuture thenApply - (Function fn) { - return doThenApply(fn, null); + public CompletableFuture thenApply( + Function fn) { + return uniApplyStage(null, fn); } - public CompletableFuture thenApplyAsync - (Function fn) { - return doThenApply(fn, ForkJoinPool.commonPool()); + public CompletableFuture thenApplyAsync( + Function fn) { + return uniApplyStage(asyncPool, fn); } - public CompletableFuture thenApplyAsync - (Function fn, - Executor executor) { - if (executor == null) throw new NullPointerException(); - return doThenApply(fn, executor); + public CompletableFuture thenApplyAsync( + Function fn, Executor executor) { + return uniApplyStage(screenExecutor(executor), fn); } - public CompletableFuture thenAccept - (Consumer action) { - return doThenAccept(action, null); + public CompletableFuture thenAccept(Consumer action) { + return uniAcceptStage(null, action); } - public CompletableFuture thenAcceptAsync - (Consumer action) { - return doThenAccept(action, ForkJoinPool.commonPool()); + public CompletableFuture thenAcceptAsync(Consumer action) { + return uniAcceptStage(asyncPool, action); } - public CompletableFuture thenAcceptAsync - (Consumer action, - Executor executor) { - if (executor == null) throw new NullPointerException(); - return doThenAccept(action, executor); + public CompletableFuture thenAcceptAsync(Consumer action, + Executor executor) { + return uniAcceptStage(screenExecutor(executor), action); } - public CompletableFuture thenRun - (Runnable action) { - return doThenRun(action, null); + public CompletableFuture thenRun(Runnable action) { + return uniRunStage(null, action); } - public CompletableFuture thenRunAsync - (Runnable action) { - return doThenRun(action, ForkJoinPool.commonPool()); + public CompletableFuture thenRunAsync(Runnable action) { + return uniRunStage(asyncPool, action); } - public CompletableFuture thenRunAsync - (Runnable action, - Executor executor) { - if (executor == null) throw new NullPointerException(); - return doThenRun(action, executor); + public CompletableFuture thenRunAsync(Runnable action, + Executor executor) { + return uniRunStage(screenExecutor(executor), action); } - public CompletableFuture thenCombine - (CompletionStage other, - BiFunction fn) { - return doThenCombine(other.toCompletableFuture(), fn, null); + public CompletableFuture thenCombine( + CompletionStage other, + BiFunction fn) { + return biApplyStage(null, other, fn); } - public CompletableFuture thenCombineAsync - (CompletionStage other, - BiFunction fn) { - return doThenCombine(other.toCompletableFuture(), fn, - ForkJoinPool.commonPool()); + public CompletableFuture thenCombineAsync( + CompletionStage other, + BiFunction fn) { + return biApplyStage(asyncPool, other, fn); } - public CompletableFuture thenCombineAsync - (CompletionStage other, - BiFunction fn, - Executor executor) { - if (executor == null) throw new NullPointerException(); - return doThenCombine(other.toCompletableFuture(), fn, executor); + public CompletableFuture thenCombineAsync( + CompletionStage other, + BiFunction fn, Executor executor) { + return biApplyStage(screenExecutor(executor), other, fn); } - public CompletableFuture thenAcceptBoth - (CompletionStage other, - BiConsumer action) { - return doThenAcceptBoth(other.toCompletableFuture(), action, null); + public CompletableFuture thenAcceptBoth( + CompletionStage other, + BiConsumer action) { + return biAcceptStage(null, other, action); } - public CompletableFuture thenAcceptBothAsync - (CompletionStage other, - BiConsumer action) { - return doThenAcceptBoth(other.toCompletableFuture(), action, - ForkJoinPool.commonPool()); + public CompletableFuture thenAcceptBothAsync( + CompletionStage other, + BiConsumer action) { + return biAcceptStage(asyncPool, other, action); } - public CompletableFuture thenAcceptBothAsync - (CompletionStage other, - BiConsumer action, - Executor executor) { - if (executor == null) throw new NullPointerException(); - return doThenAcceptBoth(other.toCompletableFuture(), action, executor); + public CompletableFuture thenAcceptBothAsync( + CompletionStage other, + BiConsumer action, Executor executor) { + return biAcceptStage(screenExecutor(executor), other, action); } - public CompletableFuture runAfterBoth - (CompletionStage other, - Runnable action) { - return doRunAfterBoth(other.toCompletableFuture(), action, null); + public CompletableFuture runAfterBoth(CompletionStage other, + Runnable action) { + return biRunStage(null, other, action); } - public CompletableFuture runAfterBothAsync - (CompletionStage other, - Runnable action) { - return doRunAfterBoth(other.toCompletableFuture(), action, - ForkJoinPool.commonPool()); + public CompletableFuture runAfterBothAsync(CompletionStage other, + Runnable action) { + return biRunStage(asyncPool, other, action); } - public CompletableFuture runAfterBothAsync - (CompletionStage other, - Runnable action, - Executor executor) { - if (executor == null) throw new NullPointerException(); - return doRunAfterBoth(other.toCompletableFuture(), action, executor); + public CompletableFuture runAfterBothAsync(CompletionStage other, + Runnable action, + Executor executor) { + return biRunStage(screenExecutor(executor), other, action); } - - public CompletableFuture applyToEither - (CompletionStage other, - Function fn) { - return doApplyToEither(other.toCompletableFuture(), fn, null); + public CompletableFuture applyToEither( + CompletionStage other, Function fn) { + return orApplyStage(null, other, fn); } - public CompletableFuture applyToEitherAsync - (CompletionStage other, - Function fn) { - return doApplyToEither(other.toCompletableFuture(), fn, - ForkJoinPool.commonPool()); + public CompletableFuture applyToEitherAsync( + CompletionStage other, Function fn) { + return orApplyStage(asyncPool, other, fn); } - public CompletableFuture applyToEitherAsync - (CompletionStage other, - Function fn, - Executor executor) { - if (executor == null) throw new NullPointerException(); - return doApplyToEither(other.toCompletableFuture(), fn, executor); + public CompletableFuture applyToEitherAsync( + CompletionStage other, Function fn, + Executor executor) { + return orApplyStage(screenExecutor(executor), other, fn); } - public CompletableFuture acceptEither - (CompletionStage other, - Consumer action) { - return doAcceptEither(other.toCompletableFuture(), action, null); + public CompletableFuture acceptEither( + CompletionStage other, Consumer action) { + return orAcceptStage(null, other, action); } - public CompletableFuture acceptEitherAsync - (CompletionStage other, - Consumer action) { - return doAcceptEither(other.toCompletableFuture(), action, - ForkJoinPool.commonPool()); + public CompletableFuture acceptEitherAsync( + CompletionStage other, Consumer action) { + return orAcceptStage(asyncPool, other, action); } - public CompletableFuture acceptEitherAsync - (CompletionStage other, - Consumer action, - Executor executor) { - if (executor == null) throw new NullPointerException(); - return doAcceptEither(other.toCompletableFuture(), action, executor); + public CompletableFuture acceptEitherAsync( + CompletionStage other, Consumer action, + Executor executor) { + return orAcceptStage(screenExecutor(executor), other, action); } public CompletableFuture runAfterEither(CompletionStage other, Runnable action) { - return doRunAfterEither(other.toCompletableFuture(), action, null); + return orRunStage(null, other, action); } - public CompletableFuture runAfterEitherAsync - (CompletionStage other, - Runnable action) { - return doRunAfterEither(other.toCompletableFuture(), action, - ForkJoinPool.commonPool()); + public CompletableFuture runAfterEitherAsync(CompletionStage other, + Runnable action) { + return orRunStage(asyncPool, other, action); } - public CompletableFuture runAfterEitherAsync - (CompletionStage other, - Runnable action, - Executor executor) { - if (executor == null) throw new NullPointerException(); - return doRunAfterEither(other.toCompletableFuture(), action, executor); + public CompletableFuture runAfterEitherAsync(CompletionStage other, + Runnable action, + Executor executor) { + return orRunStage(screenExecutor(executor), other, action); } - public CompletableFuture thenCompose - (Function> fn) { - return doThenCompose(fn, null); + public CompletableFuture thenCompose( + Function> fn) { + return uniComposeStage(null, fn); } - public CompletableFuture thenComposeAsync - (Function> fn) { - return doThenCompose(fn, ForkJoinPool.commonPool()); + public CompletableFuture thenComposeAsync( + Function> fn) { + return uniComposeStage(asyncPool, fn); } - public CompletableFuture thenComposeAsync - (Function> fn, - Executor executor) { - if (executor == null) throw new NullPointerException(); - return doThenCompose(fn, executor); + public CompletableFuture thenComposeAsync( + Function> fn, + Executor executor) { + return uniComposeStage(screenExecutor(executor), fn); } - public CompletableFuture whenComplete - (BiConsumer action) { - return doWhenComplete(action, null); + public CompletableFuture whenComplete( + BiConsumer action) { + return uniWhenCompleteStage(null, action); } - public CompletableFuture whenCompleteAsync - (BiConsumer action) { - return doWhenComplete(action, ForkJoinPool.commonPool()); + public CompletableFuture whenCompleteAsync( + BiConsumer action) { + return uniWhenCompleteStage(asyncPool, action); } - public CompletableFuture whenCompleteAsync - (BiConsumer action, - Executor executor) { - if (executor == null) throw new NullPointerException(); - return doWhenComplete(action, executor); + public CompletableFuture whenCompleteAsync( + BiConsumer action, Executor executor) { + return uniWhenCompleteStage(screenExecutor(executor), action); } - public CompletableFuture handle - (BiFunction fn) { - return doHandle(fn, null); + public CompletableFuture handle( + BiFunction fn) { + return uniHandleStage(null, fn); } - public CompletableFuture handleAsync - (BiFunction fn) { - return doHandle(fn, ForkJoinPool.commonPool()); + public CompletableFuture handleAsync( + BiFunction fn) { + return uniHandleStage(asyncPool, fn); } - public CompletableFuture handleAsync - (BiFunction fn, - Executor executor) { - if (executor == null) throw new NullPointerException(); - return doHandle(fn, executor); + public CompletableFuture handleAsync( + BiFunction fn, Executor executor) { + return uniHandleStage(screenExecutor(executor), fn); } /** - * Returns this CompletableFuture + * Returns this CompletableFuture. * * @return this CompletableFuture */ @@ -2618,52 +2183,13 @@ public class CompletableFuture implements Future, CompletionStage { * exceptionally * @return the new CompletableFuture */ - public CompletableFuture exceptionally - (Function fn) { - if (fn == null) throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - ExceptionCompletion d = null; - Object r; - if ((r = result) == null) { - CompletionNode p = - new CompletionNode(d = new ExceptionCompletion - (this, fn, dst)); - while ((r = result) == null) { - if (UNSAFE.compareAndSwapObject(this, COMPLETIONS, - p.next = completions, p)) - break; - } - } - if (r != null && (d == null || d.compareAndSet(0, 1))) { - T t = null; Throwable ex, dx = null; - if (r instanceof AltResult) { - if ((ex = ((AltResult)r).ex) != null) { - try { - t = fn.apply(ex); - } catch (Throwable rex) { - dx = rex; - } - } - } - else { - @SuppressWarnings("unchecked") T tr = (T) r; - t = tr; - } - dst.internalComplete(t, dx); - } - helpPostComplete(); - return dst; + public CompletableFuture exceptionally( + Function fn) { + return uniExceptionallyStage(fn); } /* ------------- Arbitrary-arity constructions -------------- */ - /* - * The basic plan of attack is to recursively form binary - * completion trees of elements. This can be overkill for small - * sets, but scales nicely. The And/All vs Or/Any forms use the - * same idea, but details differ. - */ - /** * Returns a new CompletableFuture that is completed when all of * the given CompletableFutures complete. If any of the given @@ -2688,82 +2214,7 @@ public class CompletableFuture implements Future, CompletionStage { * {@code null} */ public static CompletableFuture allOf(CompletableFuture... cfs) { - int len = cfs.length; // Directly handle empty and singleton cases - if (len > 1) - return allTree(cfs, 0, len - 1); - else { - CompletableFuture dst = new CompletableFuture(); - CompletableFuture f; - if (len == 0) - dst.result = NIL; - else if ((f = cfs[0]) == null) - throw new NullPointerException(); - else { - ThenPropagate d = null; - CompletionNode p = null; - Object r; - while ((r = f.result) == null) { - if (d == null) - d = new ThenPropagate(f, dst); - else if (p == null) - p = new CompletionNode(d); - else if (UNSAFE.compareAndSwapObject - (f, COMPLETIONS, p.next = f.completions, p)) - break; - } - if (r != null && (d == null || d.compareAndSet(0, 1))) - dst.internalComplete(null, (r instanceof AltResult) ? - ((AltResult)r).ex : null); - f.helpPostComplete(); - } - return dst; - } - } - - /** - * Recursively constructs an And'ed tree of CompletableFutures. - * Called only when array known to have at least two elements. - */ - private static CompletableFuture allTree(CompletableFuture[] cfs, - int lo, int hi) { - CompletableFuture fst, snd; - int mid = (lo + hi) >>> 1; - if ((fst = (lo == mid ? cfs[lo] : allTree(cfs, lo, mid))) == null || - (snd = (hi == mid+1 ? cfs[hi] : allTree(cfs, mid+1, hi))) == null) - throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - AndCompletion d = null; - CompletionNode p = null, q = null; - Object r = null, s = null; - while ((r = fst.result) == null || (s = snd.result) == null) { - if (d == null) - d = new AndCompletion(fst, snd, dst); - else if (p == null) - p = new CompletionNode(d); - else if (q == null) { - if (UNSAFE.compareAndSwapObject - (fst, COMPLETIONS, p.next = fst.completions, p)) - q = new CompletionNode(d); - } - else if (UNSAFE.compareAndSwapObject - (snd, COMPLETIONS, q.next = snd.completions, q)) - break; - } - if ((r != null || (r = fst.result) != null) && - (s != null || (s = snd.result) != null) && - (d == null || d.compareAndSet(0, 1))) { - Throwable ex; - if (r instanceof AltResult) - ex = ((AltResult)r).ex; - else - ex = null; - if (ex == null && (s instanceof AltResult)) - ex = ((AltResult)s).ex; - dst.internalComplete(null, ex); - } - fst.helpPostComplete(); - snd.helpPostComplete(); - return dst; + return andTree(cfs, 0, cfs.length - 1); } /** @@ -2782,92 +2233,7 @@ public class CompletableFuture implements Future, CompletionStage { * {@code null} */ public static CompletableFuture anyOf(CompletableFuture... cfs) { - int len = cfs.length; // Same idea as allOf - if (len > 1) - return anyTree(cfs, 0, len - 1); - else { - CompletableFuture dst = new CompletableFuture(); - CompletableFuture f; - if (len == 0) - ; // skip - else if ((f = cfs[0]) == null) - throw new NullPointerException(); - else { - ThenCopy d = null; - CompletionNode p = null; - Object r; - while ((r = f.result) == null) { - if (d == null) - d = new ThenCopy(f, dst); - else if (p == null) - p = new CompletionNode(d); - else if (UNSAFE.compareAndSwapObject - (f, COMPLETIONS, p.next = f.completions, p)) - break; - } - if (r != null && (d == null || d.compareAndSet(0, 1))) { - Throwable ex; Object t; - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - t = r; - } - dst.internalComplete(t, ex); - } - f.helpPostComplete(); - } - return dst; - } - } - - /** - * Recursively constructs an Or'ed tree of CompletableFutures. - */ - private static CompletableFuture anyTree(CompletableFuture[] cfs, - int lo, int hi) { - CompletableFuture fst, snd; - int mid = (lo + hi) >>> 1; - if ((fst = (lo == mid ? cfs[lo] : anyTree(cfs, lo, mid))) == null || - (snd = (hi == mid+1 ? cfs[hi] : anyTree(cfs, mid+1, hi))) == null) - throw new NullPointerException(); - CompletableFuture dst = new CompletableFuture(); - OrCompletion d = null; - CompletionNode p = null, q = null; - Object r; - while ((r = fst.result) == null && (r = snd.result) == null) { - if (d == null) - d = new OrCompletion(fst, snd, dst); - else if (p == null) - p = new CompletionNode(d); - else if (q == null) { - if (UNSAFE.compareAndSwapObject - (fst, COMPLETIONS, p.next = fst.completions, p)) - q = new CompletionNode(d); - } - else if (UNSAFE.compareAndSwapObject - (snd, COMPLETIONS, q.next = snd.completions, q)) - break; - } - if ((r != null || (r = fst.result) != null || - (r = snd.result) != null) && - (d == null || d.compareAndSet(0, 1))) { - Throwable ex; Object t; - if (r instanceof AltResult) { - ex = ((AltResult)r).ex; - t = null; - } - else { - ex = null; - t = r; - } - dst.internalComplete(t, ex); - } - fst.helpPostComplete(); - snd.helpPostComplete(); - return dst; + return orTree(cfs, 0, cfs.length - 1); } /* ------------- Control and status methods -------------- */ @@ -2887,8 +2253,7 @@ public class CompletableFuture implements Future, CompletionStage { */ public boolean cancel(boolean mayInterruptIfRunning) { boolean cancelled = (result == null) && - UNSAFE.compareAndSwapObject - (this, RESULT, null, new AltResult(new CancellationException())); + internalComplete(new AltResult(new CancellationException())); postComplete(); return cancelled || isCancelled(); } @@ -2940,11 +2305,12 @@ public class CompletableFuture implements Future, CompletionStage { * Forcibly causes subsequent invocations of method {@link #get()} * and related methods to throw the given exception, whether or * not already completed. This method is designed for use only in - * recovery actions, and even in such situations may result in - * ongoing dependent completions using established versus + * error recovery actions, and even in such situations may result + * in ongoing dependent completions using established versus * overwritten outcomes. * * @param ex the exception + * @throws NullPointerException if the exception is null */ public void obtrudeException(Throwable ex) { if (ex == null) throw new NullPointerException(); @@ -2962,7 +2328,7 @@ public class CompletableFuture implements Future, CompletionStage { */ public int getNumberOfDependents() { int count = 0; - for (CompletionNode p = completions; p != null; p = p.next) + for (Completion p = stack; p != null; p = p.next) ++count; return count; } @@ -2993,20 +2359,19 @@ public class CompletableFuture implements Future, CompletionStage { // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long RESULT; - private static final long WAITERS; - private static final long COMPLETIONS; + private static final long STACK; + private static final long NEXT; static { try { - UNSAFE = sun.misc.Unsafe.getUnsafe(); + final sun.misc.Unsafe u; + UNSAFE = u = sun.misc.Unsafe.getUnsafe(); Class k = CompletableFuture.class; - RESULT = UNSAFE.objectFieldOffset - (k.getDeclaredField("result")); - WAITERS = UNSAFE.objectFieldOffset - (k.getDeclaredField("waiters")); - COMPLETIONS = UNSAFE.objectFieldOffset - (k.getDeclaredField("completions")); - } catch (Exception e) { - throw new Error(e); + RESULT = u.objectFieldOffset(k.getDeclaredField("result")); + STACK = u.objectFieldOffset(k.getDeclaredField("stack")); + NEXT = u.objectFieldOffset + (Completion.class.getDeclaredField("next")); + } catch (Exception x) { + throw new Error(x); } } } diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/CompletionStage.java b/jdk/src/java.base/share/classes/java/util/concurrent/CompletionStage.java index 6de60980cff..304ede5db50 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/CompletionStage.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/CompletionStage.java @@ -407,7 +407,7 @@ public interface CompletionStage { /** * Returns a new CompletionStage that, when this and the other * given stage complete normally, executes the given action using - * the supplied executor + * the supplied executor. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. @@ -569,7 +569,7 @@ public interface CompletionStage { /** * Returns a new CompletionStage that, when either this or the * other given stage complete normally, executes the given action - * using supplied executor. + * using the supplied executor. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. @@ -649,10 +649,15 @@ public interface CompletionStage { (Function fn); /** - * Returns a new CompletionStage with the same result or exception - * as this stage, and when this stage completes, executes the - * given action with the result (or {@code null} if none) and the - * exception (or {@code null} if none) of this stage. + * Returns a new CompletionStage with the same result or exception as + * this stage, that executes the given action when this stage completes. + * + *

    When this stage is complete, the given action is invoked with the + * result (or {@code null} if none) and the exception (or {@code null} + * if none) of this stage as arguments. The returned stage is completed + * when the action returns. If the supplied action itself encounters an + * exception, then the returned stage exceptionally completes with this + * exception unless this stage also completed exceptionally. * * @param action the action to perform * @return the new CompletionStage @@ -661,12 +666,16 @@ public interface CompletionStage { (BiConsumer action); /** - * Returns a new CompletionStage with the same result or exception - * as this stage, and when this stage completes, executes the - * given action executes the given action using this stage's - * default asynchronous execution facility, with the result (or - * {@code null} if none) and the exception (or {@code null} if - * none) of this stage as arguments. + * Returns a new CompletionStage with the same result or exception as + * this stage, that executes the given action using this stage's + * default asynchronous execution facility when this stage completes. + * + *

    When this stage is complete, the given action is invoked with the + * result (or {@code null} if none) and the exception (or {@code null} + * if none) of this stage as arguments. The returned stage is completed + * when the action returns. If the supplied action itself encounters an + * exception, then the returned stage exceptionally completes with this + * exception unless this stage also completed exceptionally. * * @param action the action to perform * @return the new CompletionStage @@ -675,11 +684,16 @@ public interface CompletionStage { (BiConsumer action); /** - * Returns a new CompletionStage with the same result or exception - * as this stage, and when this stage completes, executes using - * the supplied Executor, the given action with the result (or - * {@code null} if none) and the exception (or {@code null} if - * none) of this stage as arguments. + * Returns a new CompletionStage with the same result or exception as + * this stage, that executes the given action using the supplied + * Executor when this stage completes. + * + *

    When this stage is complete, the given action is invoked with the + * result (or {@code null} if none) and the exception (or {@code null} + * if none) of this stage as arguments. The returned stage is completed + * when the action returns. If the supplied action itself encounters an + * exception, then the returned stage exceptionally completes with this + * exception unless this stage also completed exceptionally. * * @param action the action to perform * @param executor the executor to use for asynchronous execution @@ -693,9 +707,11 @@ public interface CompletionStage { * Returns a new CompletionStage that, when this stage completes * either normally or exceptionally, is executed with this stage's * result and exception as arguments to the supplied function. - * The given function is invoked with the result (or {@code null} - * if none) and the exception (or {@code null} if none) of this - * stage when complete as arguments. + * + *

    When this stage is complete, the given function is invoked + * with the result (or {@code null} if none) and the exception (or + * {@code null} if none) of this stage as arguments, and the + * function's result is used to complete the returned stage. * * @param fn the function to use to compute the value of the * returned CompletionStage @@ -710,9 +726,11 @@ public interface CompletionStage { * either normally or exceptionally, is executed using this stage's * default asynchronous execution facility, with this stage's * result and exception as arguments to the supplied function. - * The given function is invoked with the result (or {@code null} - * if none) and the exception (or {@code null} if none) of this - * stage when complete as arguments. + * + *

    When this stage is complete, the given function is invoked + * with the result (or {@code null} if none) and the exception (or + * {@code null} if none) of this stage as arguments, and the + * function's result is used to complete the returned stage. * * @param fn the function to use to compute the value of the * returned CompletionStage @@ -726,10 +744,12 @@ public interface CompletionStage { * Returns a new CompletionStage that, when this stage completes * either normally or exceptionally, is executed using the * supplied executor, with this stage's result and exception as - * arguments to the supplied function. The given function is - * invoked with the result (or {@code null} if none) and the - * exception (or {@code null} if none) of this stage when complete - * as arguments. + * arguments to the supplied function. + * + *

    When this stage is complete, the given function is invoked + * with the result (or {@code null} if none) and the exception (or + * {@code null} if none) of this stage as arguments, and the + * function's result is used to complete the returned stage. * * @param fn the function to use to compute the value of the * returned CompletionStage diff --git a/jdk/src/java.base/share/classes/sun/net/www/MimeEntry.java b/jdk/src/java.base/share/classes/sun/net/www/MimeEntry.java index 7a7bcce453c..f96953a42d4 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/MimeEntry.java +++ b/jdk/src/java.base/share/classes/sun/net/www/MimeEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1994, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1994, 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 @@ -26,6 +26,7 @@ package sun.net.www; import java.net.URL; import java.io.*; +import java.util.StringJoiner; import java.util.StringTokenizer; public class MimeEntry implements Cloneable { @@ -281,52 +282,34 @@ public class MimeEntry implements Cloneable { } public synchronized String toProperty() { - StringBuilder sb = new StringBuilder(); - - String separator = "; "; - boolean needSeparator = false; + StringJoiner sj = new StringJoiner("; "); int action = getAction(); if (action != MimeEntry.UNKNOWN) { - sb.append("action=" + actionKeywords[action]); - needSeparator = true; + sj.add("action=" + actionKeywords[action]); } String command = getLaunchString(); if (command != null && command.length() > 0) { - if (needSeparator) { - sb.append(separator); - } - sb.append("application=" + command); - needSeparator = true; + sj.add("application=" + command); } - if (getImageFileName() != null) { - if (needSeparator) { - sb.append(separator); - } - sb.append("icon=" + getImageFileName()); - needSeparator = true; + String image = getImageFileName(); + if (image != null) { + sj.add("icon=" + image); } String extensions = getExtensionsAsList(); if (extensions.length() > 0) { - if (needSeparator) { - sb.append(separator); - } - sb.append("file_extensions=" + extensions); - needSeparator = true; + sj.add("file_extensions=" + extensions); } String description = getDescription(); if (description != null && !description.equals(getType())) { - if (needSeparator) { - sb.append(separator); - } - sb.append("description=" + description); + sj.add("description=" + description); } - return sb.toString(); + return sj.toString(); } public String toString() { diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java index 781f772c1ab..f4ade7e3dfd 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -64,6 +64,7 @@ import java.util.Iterator; import java.util.HashSet; import java.util.HashMap; import java.util.Set; +import java.util.StringJoiner; import sun.net.*; import sun.net.www.*; import sun.net.www.http.HttpClient; @@ -1386,16 +1387,11 @@ public class HttpURLConnection extends java.net.HttpURLConnection { } List l = entry.getValue(); if (l != null && !l.isEmpty()) { - StringBuilder cookieValue = new StringBuilder(); + StringJoiner cookieValue = new StringJoiner("; "); for (String value : l) { - cookieValue.append(value).append("; "); - } - // strip off the trailing '; ' - try { - requests.add(key, cookieValue.substring(0, cookieValue.length() - 2)); - } catch (StringIndexOutOfBoundsException ignored) { - // no-op + cookieValue.add(value); } + requests.add(key, cookieValue.toString()); } } } @@ -2870,20 +2866,14 @@ public class HttpURLConnection extends java.net.HttpURLConnection { sun.misc.JavaNetHttpCookieAccess access = sun.misc.SharedSecrets.getJavaNetHttpCookieAccess(); - StringBuilder retValue = new StringBuilder(); + StringJoiner retValue = new StringJoiner(","); // RFC 2965, comma separated List cookies = access.parse(value); - boolean multipleCookies = false; for (HttpCookie cookie : cookies) { // skip HttpOnly cookies - if (cookie.isHttpOnly()) - continue; - if (multipleCookies) - retValue.append(','); // RFC 2965, comma separated - retValue.append(access.header(cookie)); - multipleCookies = true; + if (!cookie.isHttpOnly()) + retValue.add(access.header(cookie)); } - - return retValue.length() == 0 ? "" : retValue.toString(); + return retValue.toString(); } return value; diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java index 1ec1700ea67..c3067c044e0 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/https/HttpsURLConnectionImpl.java @@ -501,7 +501,8 @@ public class HttpsURLConnectionImpl } public boolean equals(Object obj) { - return delegate.equals(obj); + return this == obj || ((obj instanceof HttpsURLConnectionImpl) && + delegate.equals(((HttpsURLConnectionImpl)obj).delegate)); } public int hashCode() { diff --git a/jdk/src/java.base/share/classes/sun/util/locale/BaseLocale.java b/jdk/src/java.base/share/classes/sun/util/locale/BaseLocale.java index 6eee5829095..137fd82f7dd 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/BaseLocale.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/BaseLocale.java @@ -32,6 +32,7 @@ package sun.util.locale; +import java.util.StringJoiner; public final class BaseLocale { @@ -120,33 +121,20 @@ public final class BaseLocale { @Override public String toString() { - StringBuilder buf = new StringBuilder(); + StringJoiner sj = new StringJoiner(", "); if (language.length() > 0) { - buf.append("language="); - buf.append(language); + sj.add("language=" + language); } if (script.length() > 0) { - if (buf.length() > 0) { - buf.append(", "); - } - buf.append("script="); - buf.append(script); + sj.add("script=" + script); } if (region.length() > 0) { - if (buf.length() > 0) { - buf.append(", "); - } - buf.append("region="); - buf.append(region); + sj.add("region=" + region); } if (variant.length() > 0) { - if (buf.length() > 0) { - buf.append(", "); - } - buf.append("variant="); - buf.append(variant); + sj.add("variant=" + variant); } - return buf.toString(); + return sj.toString(); } @Override diff --git a/jdk/src/java.base/share/classes/sun/util/locale/LanguageTag.java b/jdk/src/java.base/share/classes/sun/util/locale/LanguageTag.java index 2247398c400..3fd7f7dbe5e 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/LanguageTag.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/LanguageTag.java @@ -37,6 +37,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.StringJoiner; public class LanguageTag { // @@ -473,21 +474,18 @@ public class LanguageTag { } if (!varitr.isDone()) { // ill-formed variant subtags - StringBuilder buf = new StringBuilder(); + StringJoiner sj = new StringJoiner(SEP); while (!varitr.isDone()) { String prvv = varitr.current(); if (!isPrivateuseSubtag(prvv)) { // cannot use private use subtag - truncated break; } - if (buf.length() > 0) { - buf.append(SEP); - } - buf.append(prvv); + sj.add(prvv); varitr.next(); } - if (buf.length() > 0) { - privuseVar = buf.toString(); + if (sj.length() > 0) { + privuseVar = sj.toString(); } } } diff --git a/jdk/src/java.base/share/classes/sun/util/locale/UnicodeLocaleExtension.java b/jdk/src/java.base/share/classes/sun/util/locale/UnicodeLocaleExtension.java index cc5a5685cd0..51a723aea25 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/UnicodeLocaleExtension.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/UnicodeLocaleExtension.java @@ -1,6 +1,6 @@ /* - * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 @@ -38,6 +38,7 @@ import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; +import java.util.StringJoiner; public class UnicodeLocaleExtension extends Extension { public static final char SINGLETON = 'u'; @@ -70,20 +71,20 @@ public class UnicodeLocaleExtension extends Extension { } if (!this.attributes.isEmpty() || !this.keywords.isEmpty()) { - StringBuilder sb = new StringBuilder(); + StringJoiner sj = new StringJoiner(LanguageTag.SEP); for (String attribute : this.attributes) { - sb.append(LanguageTag.SEP).append(attribute); + sj.add(attribute); } for (Entry keyword : this.keywords.entrySet()) { String key = keyword.getKey(); String value = keyword.getValue(); - sb.append(LanguageTag.SEP).append(key); + sj.add(key); if (value.length() > 0) { - sb.append(LanguageTag.SEP).append(value); + sj.add(value); } } - setValue(sb.substring(1)); // skip leading '-' + setValue(sj.toString()); } } diff --git a/jdk/src/java.base/share/classes/sun/util/locale/provider/RuleBasedBreakIterator.java b/jdk/src/java.base/share/classes/sun/util/locale/provider/RuleBasedBreakIterator.java index f8c68fa35c2..a1962e463da 100644 --- a/jdk/src/java.base/share/classes/sun/util/locale/provider/RuleBasedBreakIterator.java +++ b/jdk/src/java.base/share/classes/sun/util/locale/provider/RuleBasedBreakIterator.java @@ -547,12 +547,7 @@ class RuleBasedBreakIterator extends BreakIterator { */ @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append('['); - sb.append("checksum=0x"); - sb.append(Long.toHexString(checksum)); - sb.append(']'); - return sb.toString(); + return "[checksum=0x" + Long.toHexString(checksum) + ']'; } /** diff --git a/jdk/src/java.base/unix/classes/sun/nio/ch/InheritedChannel.java b/jdk/src/java.base/unix/classes/sun/nio/ch/InheritedChannel.java index e696d3eba07..2bb712e7867 100644 --- a/jdk/src/java.base/unix/classes/sun/nio/ch/InheritedChannel.java +++ b/jdk/src/java.base/unix/classes/sun/nio/ch/InheritedChannel.java @@ -226,6 +226,7 @@ class InheritedChannel { // -- Native methods -- + private static native void initIDs(); private static native int dup(int fd) throws IOException; private static native void dup2(int fd, int fd2) throws IOException; private static native int open0(String path, int oflag) throws IOException; @@ -236,5 +237,6 @@ class InheritedChannel { static { IOUtil.load(); + initIDs(); } } diff --git a/jdk/src/java.base/unix/native/libnio/ch/IOUtil.c b/jdk/src/java.base/unix/native/libnio/ch/IOUtil.c index d8bbe849252..438bf41ddea 100644 --- a/jdk/src/java.base/unix/native/libnio/ch/IOUtil.c +++ b/jdk/src/java.base/unix/native/libnio/ch/IOUtil.c @@ -35,7 +35,6 @@ #include "java_lang_Integer.h" #include "nio.h" #include "nio_util.h" -#include "net_util.h" static jfieldID fd_fdID; /* for jint 'fd' in java.io.FileDescriptor */ @@ -45,7 +44,6 @@ Java_sun_nio_ch_IOUtil_initIDs(JNIEnv *env, jclass clazz) { CHECK_NULL(clazz = (*env)->FindClass(env, "java/io/FileDescriptor")); CHECK_NULL(fd_fdID = (*env)->GetFieldID(env, clazz, "fd", "I")); - initInetAddressIDs(env); } JNIEXPORT jboolean JNICALL diff --git a/jdk/src/java.base/unix/native/libnio/ch/InheritedChannel.c b/jdk/src/java.base/unix/native/libnio/ch/InheritedChannel.c index 986348e5320..86d1b05baa2 100644 --- a/jdk/src/java.base/unix/native/libnio/ch/InheritedChannel.c +++ b/jdk/src/java.base/unix/native/libnio/ch/InheritedChannel.c @@ -47,6 +47,13 @@ static int matchFamily(struct sockaddr *sa) { return (family == AF_INET); } +JNIEXPORT void JNICALL +Java_sun_nio_ch_InheritedChannel_initIDs(JNIEnv *env, jclass cla) +{ + /* Initialize InetAddress IDs before later use of NET_XXX functions */ + initInetAddressIDs(env); +} + JNIEXPORT jobject JNICALL Java_sun_nio_ch_InheritedChannel_peerAddress0(JNIEnv *env, jclass cla, jint fd) { diff --git a/jdk/src/java.base/unix/native/libnio/ch/Net.c b/jdk/src/java.base/unix/native/libnio/ch/Net.c index 8887f59109c..197b23a7285 100644 --- a/jdk/src/java.base/unix/native/libnio/ch/Net.c +++ b/jdk/src/java.base/unix/native/libnio/ch/Net.c @@ -151,7 +151,7 @@ static jboolean isSourceFilterSupported(){ JNIEXPORT void JNICALL Java_sun_nio_ch_Net_initIDs(JNIEnv *env, jclass clazz) { - /* Here because Windows native code does need to init IDs */ + initInetAddressIDs(env); } JNIEXPORT jboolean JNICALL diff --git a/jdk/src/java.base/unix/native/libnio/fs/UnixNativeDispatcher.c b/jdk/src/java.base/unix/native/libnio/fs/UnixNativeDispatcher.c index d3ee3279e54..e8a1623a87d 100644 --- a/jdk/src/java.base/unix/native/libnio/fs/UnixNativeDispatcher.c +++ b/jdk/src/java.base/unix/native/libnio/fs/UnixNativeDispatcher.c @@ -333,7 +333,7 @@ Java_sun_nio_fs_UnixNativeDispatcher_dup(JNIEnv* env, jclass this, jint fd) { int res = -1; RESTARTABLE(dup((int)fd), res); - if (fd == -1) { + if (res == -1) { throwUnixException(env, errno); } return (jint)res; @@ -361,13 +361,14 @@ Java_sun_nio_fs_UnixNativeDispatcher_fopen0(JNIEnv* env, jclass this, JNIEXPORT void JNICALL Java_sun_nio_fs_UnixNativeDispatcher_fclose(JNIEnv* env, jclass this, jlong stream) { - int res; FILE* fp = jlong_to_ptr(stream); - do { - res = fclose(fp); - } while (res == EOF && errno == EINTR); - if (res == EOF) { + /* NOTE: fclose() wrapper is only used with read-only streams. + * If it ever is used with write streams, it might be better to add + * RESTARTABLE(fflush(fp)) before closing, to make sure the stream + * is completely written even if fclose() failed. + */ + if (fclose(fp) == EOF && errno != EINTR) { throwUnixException(env, errno); } } @@ -675,11 +676,9 @@ Java_sun_nio_fs_UnixNativeDispatcher_fdopendir(JNIEnv* env, jclass this, int dfd JNIEXPORT void JNICALL Java_sun_nio_fs_UnixNativeDispatcher_closedir(JNIEnv* env, jclass this, jlong dir) { - int err; DIR* dirp = jlong_to_ptr(dir); - RESTARTABLE(closedir(dirp), err); - if (errno == -1) { + if (closedir(dirp) == -1 && errno != EINTR) { throwUnixException(env, errno); } } diff --git a/jdk/src/java.base/windows/native/libjava/WinNTFileSystem_md.c b/jdk/src/java.base/windows/native/libjava/WinNTFileSystem_md.c index 6ecf818d3ff..3c280c0c9b4 100644 --- a/jdk/src/java.base/windows/native/libjava/WinNTFileSystem_md.c +++ b/jdk/src/java.base/windows/native/libjava/WinNTFileSystem_md.c @@ -572,10 +572,10 @@ Java_java_io_WinNTFileSystem_createFileExclusively(JNIEnv *env, jclass cls, SetLastError(error); JNU_ThrowIOExceptionWithLastError(env, "Could not open file"); } - } - free(pathbuf); - return JNI_FALSE; } + free(pathbuf); + return JNI_FALSE; + } free(pathbuf); CloseHandle(h); return JNI_TRUE; @@ -636,7 +636,7 @@ Java_java_io_WinNTFileSystem_list(JNIEnv *env, jobject this, jobject file) if (search_path == 0) { free (pathbuf); errno = ENOMEM; - JNU_ThrowOutOfMemoryError(env, "native memory allocation faiuled"); + JNU_ThrowOutOfMemoryError(env, "native memory allocation failed"); return NULL; } wcscpy(search_path, pathbuf); @@ -652,7 +652,7 @@ Java_java_io_WinNTFileSystem_list(JNIEnv *env, jobject this, jobject file) /* Remove trailing space chars from directory name */ len = (int)wcslen(search_path); - while (search_path[len-1] == ' ') { + while (search_path[len-1] == L' ') { len--; } search_path[len] = 0; @@ -713,13 +713,15 @@ Java_java_io_WinNTFileSystem_list(JNIEnv *env, jobject this, jobject file) return NULL; // error FindClose(handle); - /* Copy the final results into an appropriately-sized array */ - old = rv; - rv = (*env)->NewObjectArray(env, len, str_class, NULL); - if (rv == NULL) - return NULL; /* error */ - if (JNU_CopyObjectArray(env, rv, old, len) < 0) - return NULL; /* error */ + if (len < maxlen) { + /* Copy the final results into an appropriately-sized array */ + old = rv; + rv = (*env)->NewObjectArray(env, len, str_class, NULL); + if (rv == NULL) + return NULL; /* error */ + if (JNU_CopyObjectArray(env, rv, old, len) < 0) + return NULL; /* error */ + } return rv; } @@ -753,9 +755,7 @@ Java_java_io_WinNTFileSystem_rename0(JNIEnv *env, jobject this, jobject from, jboolean rv = JNI_FALSE; WCHAR *frompath = fileToNTPath(env, from, ids.path); WCHAR *topath = fileToNTPath(env, to, ids.path); - if (frompath == NULL || topath == NULL) - return JNI_FALSE; - if (_wrename(frompath, topath) == 0) { + if (frompath != NULL && topath != NULL && _wrename(frompath, topath) == 0) { rv = JNI_TRUE; } free(frompath); diff --git a/jdk/src/java.base/windows/native/libnio/ch/IOUtil.c b/jdk/src/java.base/windows/native/libnio/ch/IOUtil.c index 49de1eb89d7..5c33ac4de23 100644 --- a/jdk/src/java.base/windows/native/libnio/ch/IOUtil.c +++ b/jdk/src/java.base/windows/native/libnio/ch/IOUtil.c @@ -56,7 +56,6 @@ Java_sun_nio_ch_IOUtil_initIDs(JNIEnv *env, jclass clazz) CHECK_NULL(clazz = (*env)->FindClass(env, "java/io/FileDescriptor")); CHECK_NULL(fd_fdID = (*env)->GetFieldID(env, clazz, "fd", "I")); CHECK_NULL(handle_fdID = (*env)->GetFieldID(env, clazz, "handle", "J")); - initInetAddressIDs(env); } /************************************************************** diff --git a/jdk/src/java.base/windows/native/libnio/ch/Net.c b/jdk/src/java.base/windows/native/libnio/ch/Net.c index fb0faa87b84..b92e63ac11b 100644 --- a/jdk/src/java.base/windows/native/libnio/ch/Net.c +++ b/jdk/src/java.base/windows/native/libnio/ch/Net.c @@ -81,7 +81,7 @@ static void setConnectionReset(SOCKET s, BOOL enable) { JNIEXPORT void JNICALL Java_sun_nio_ch_Net_initIDs(JNIEnv *env, jclass clazz) { - /* nothing to do */ + initInetAddressIDs(env); } JNIEXPORT jboolean JNICALL diff --git a/jdk/src/java.smartcardio/share/classes/javax/smartcardio/CardPermission.java b/jdk/src/java.smartcardio/share/classes/javax/smartcardio/CardPermission.java index e803bbc9bb3..8086dbc7cd3 100644 --- a/jdk/src/java.smartcardio/share/classes/javax/smartcardio/CardPermission.java +++ b/jdk/src/java.smartcardio/share/classes/javax/smartcardio/CardPermission.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -26,7 +26,7 @@ package javax.smartcardio; import java.io.*; - +import java.util.StringJoiner; import java.security.Permission; /** @@ -180,20 +180,14 @@ public class CardPermission extends Permission { if (mask == A_ALL) { return S_ALL; } - boolean first = true; - StringBuilder sb = new StringBuilder(); + StringJoiner sj = new StringJoiner(","); for (int i = 0; i < ARRAY_MASKS.length; i++) { - int action = ARRAY_MASKS[i]; + final int action = ARRAY_MASKS[i]; if ((mask & action) == action) { - if (first == false) { - sb.append(","); - } else { - first = false; - } - sb.append(ARRAY_STRINGS[i]); + sj.add(ARRAY_STRINGS[i]); } } - return sb.toString(); + return sj.toString(); } diff --git a/jdk/src/jdk.attach/aix/classes/sun/tools/attach/AixAttachProvider.java b/jdk/src/jdk.attach/aix/classes/sun/tools/attach/AttachProviderImpl.java similarity index 89% rename from jdk/src/jdk.attach/aix/classes/sun/tools/attach/AixAttachProvider.java rename to jdk/src/jdk.attach/aix/classes/sun/tools/attach/AttachProviderImpl.java index a78c6609720..532c3db0a3d 100644 --- a/jdk/src/jdk.attach/aix/classes/sun/tools/attach/AixAttachProvider.java +++ b/jdk/src/jdk.attach/aix/classes/sun/tools/attach/AttachProviderImpl.java @@ -32,19 +32,18 @@ import com.sun.tools.attach.spi.AttachProvider; import java.io.IOException; -// Based on 'LinuxAttachProvider.java'. All occurrences of the string -// "Linux" have been textually replaced by "Aix" to avoid confusion. +// Based on linux/classes/sun/tools/attach/AttachProviderImpl.java. /* * An AttachProvider implementation for Aix that uses a UNIX domain * socket. */ -public class AixAttachProvider extends HotSpotAttachProvider { +public class AttachProviderImpl extends HotSpotAttachProvider { // perf counter for the JVM version private static final String JVM_VERSION = "java.property.java.vm.version"; - public AixAttachProvider() { + public AttachProviderImpl() { } public String name() { @@ -64,7 +63,7 @@ public class AixAttachProvider extends HotSpotAttachProvider { // to be not attachable. testAttachable(vmid); - return new AixVirtualMachine(this, vmid); + return new VirtualMachineImpl(this, vmid); } public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd) @@ -79,7 +78,7 @@ public class AixAttachProvider extends HotSpotAttachProvider { if (vmd instanceof HotSpotVirtualMachineDescriptor) { assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable(); checkAttachPermission(); - return new AixVirtualMachine(this, vmd.id()); + return new VirtualMachineImpl(this, vmd.id()); } else { return attachVirtualMachine(vmd.id()); } diff --git a/jdk/src/jdk.attach/aix/classes/sun/tools/attach/AixVirtualMachine.java b/jdk/src/jdk.attach/aix/classes/sun/tools/attach/VirtualMachineImpl.java similarity index 95% rename from jdk/src/jdk.attach/aix/classes/sun/tools/attach/AixVirtualMachine.java rename to jdk/src/jdk.attach/aix/classes/sun/tools/attach/VirtualMachineImpl.java index 714f5c0d570..a76d0a99771 100644 --- a/jdk/src/jdk.attach/aix/classes/sun/tools/attach/AixVirtualMachine.java +++ b/jdk/src/jdk.attach/aix/classes/sun/tools/attach/VirtualMachineImpl.java @@ -34,13 +34,12 @@ import java.io.IOException; import java.io.File; import java.util.Properties; -// Based on 'LinuxVirtualMachine.java'. All occurrences of the string -// "Linux" have been textually replaced by "Aix" to avoid confusion. +// Based on linux/classes/sun/tools/attach/VirtualMachineImpl.java. /* * Aix implementation of HotSpotVirtualMachine */ -public class AixVirtualMachine extends HotSpotVirtualMachine { +public class VirtualMachineImpl extends HotSpotVirtualMachine { // "/tmp" is used as a global well-known location for the files // .java_pid. and .attach_pid. It is important that this // location is the same for all processes, otherwise the tools @@ -54,7 +53,7 @@ public class AixVirtualMachine extends HotSpotVirtualMachine { /** * Attaches to the target VM */ - AixVirtualMachine(AttachProvider provider, String vmid) + VirtualMachineImpl(AttachProvider provider, String vmid) throws AttachNotSupportedException, IOException { super(provider, vmid); @@ -241,11 +240,11 @@ public class AixVirtualMachine extends HotSpotVirtualMachine { } else if (len == 0) return 0; - return AixVirtualMachine.read(s, bs, off, len); + return VirtualMachineImpl.read(s, bs, off, len); } public void close() throws IOException { - AixVirtualMachine.close(s); + VirtualMachineImpl.close(s); } } @@ -287,7 +286,7 @@ public class AixVirtualMachine extends HotSpotVirtualMachine { } catch (java.io.UnsupportedEncodingException x) { throw new InternalError(x); } - AixVirtualMachine.write(fd, b, 0, b.length); + VirtualMachineImpl.write(fd, b, 0, b.length); } byte b[] = new byte[1]; b[0] = 0; diff --git a/jdk/src/jdk.attach/aix/native/libattach/AixVirtualMachine.c b/jdk/src/jdk.attach/aix/native/libattach/VirtualMachineImpl.c similarity index 89% rename from jdk/src/jdk.attach/aix/native/libattach/AixVirtualMachine.c rename to jdk/src/jdk.attach/aix/native/libattach/VirtualMachineImpl.c index 7422427803f..df330549d8d 100644 --- a/jdk/src/jdk.attach/aix/native/libattach/AixVirtualMachine.c +++ b/jdk/src/jdk.attach/aix/native/libattach/VirtualMachineImpl.c @@ -45,7 +45,7 @@ * occurrences of the string "Linux" have been replaced by "Aix". */ -#include "sun_tools_attach_AixVirtualMachine.h" +#include "sun_tools_attach_VirtualMachineImpl.h" #define RESTARTABLE(_cmd, _result) do { \ do { \ @@ -55,11 +55,11 @@ /* - * Class: sun_tools_attach_AixVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: socket * Signature: ()I */ -JNIEXPORT jint JNICALL Java_sun_tools_attach_AixVirtualMachine_socket +JNIEXPORT jint JNICALL Java_sun_tools_attach_VirtualMachineImpl_socket (JNIEnv *env, jclass cls) { int fd = socket(PF_UNIX, SOCK_STREAM, 0); @@ -79,11 +79,11 @@ JNIEXPORT jint JNICALL Java_sun_tools_attach_AixVirtualMachine_socket } /* - * Class: sun_tools_attach_AixVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: connect * Signature: (ILjava/lang/String;)I */ -JNIEXPORT void JNICALL Java_sun_tools_attach_AixVirtualMachine_connect +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_connect (JNIEnv *env, jclass cls, jint fd, jstring path) { jboolean isCopy; @@ -142,11 +142,11 @@ static void SendQuitCallback(const pid_t pid, void* user_data) { } /* - * Class: sun_tools_attach_AixVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: sendQuitTo * Signature: (I)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_AixVirtualMachine_sendQuitTo +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_sendQuitTo (JNIEnv *env, jclass cls, jint pid) { if (kill((pid_t)pid, SIGQUIT)) { @@ -155,11 +155,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_AixVirtualMachine_sendQuitTo } /* - * Class: sun_tools_attach_AixVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: checkPermissions * Signature: (Ljava/lang/String;)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_AixVirtualMachine_checkPermissions +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_checkPermissions (JNIEnv *env, jclass cls, jstring path) { jboolean isCopy; @@ -205,11 +205,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_AixVirtualMachine_checkPermissions } /* - * Class: sun_tools_attach_AixVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: close * Signature: (I)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_AixVirtualMachine_close +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_close (JNIEnv *env, jclass cls, jint fd) { int res; @@ -222,11 +222,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_AixVirtualMachine_close } /* - * Class: sun_tools_attach_AixVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: read * Signature: (I[BI)I */ -JNIEXPORT jint JNICALL Java_sun_tools_attach_AixVirtualMachine_read +JNIEXPORT jint JNICALL Java_sun_tools_attach_VirtualMachineImpl_read (JNIEnv *env, jclass cls, jint fd, jbyteArray ba, jint off, jint baLen) { unsigned char buf[128]; @@ -252,11 +252,11 @@ JNIEXPORT jint JNICALL Java_sun_tools_attach_AixVirtualMachine_read } /* - * Class: sun_tools_attach_AixVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: write * Signature: (I[B)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_AixVirtualMachine_write +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_write (JNIEnv *env, jclass cls, jint fd, jbyteArray ba, jint off, jint bufLen) { size_t remaining = bufLen; diff --git a/jdk/src/jdk.attach/unix/classes/sun/tools/attach/LinuxAttachProvider.java b/jdk/src/jdk.attach/linux/classes/sun/tools/attach/AttachProviderImpl.java similarity index 93% rename from jdk/src/jdk.attach/unix/classes/sun/tools/attach/LinuxAttachProvider.java rename to jdk/src/jdk.attach/linux/classes/sun/tools/attach/AttachProviderImpl.java index de3bf058bdf..adf8b01e6b4 100644 --- a/jdk/src/jdk.attach/unix/classes/sun/tools/attach/LinuxAttachProvider.java +++ b/jdk/src/jdk.attach/linux/classes/sun/tools/attach/AttachProviderImpl.java @@ -35,12 +35,12 @@ import java.io.IOException; * An AttachProvider implementation for Linux that uses a UNIX domain * socket. */ -public class LinuxAttachProvider extends HotSpotAttachProvider { +public class AttachProviderImpl extends HotSpotAttachProvider { // perf counter for the JVM version private static final String JVM_VERSION = "java.property.java.vm.version"; - public LinuxAttachProvider() { + public AttachProviderImpl() { } public String name() { @@ -60,7 +60,7 @@ public class LinuxAttachProvider extends HotSpotAttachProvider { // to be not attachable. testAttachable(vmid); - return new LinuxVirtualMachine(this, vmid); + return new VirtualMachineImpl(this, vmid); } public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd) @@ -75,7 +75,7 @@ public class LinuxAttachProvider extends HotSpotAttachProvider { if (vmd instanceof HotSpotVirtualMachineDescriptor) { assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable(); checkAttachPermission(); - return new LinuxVirtualMachine(this, vmd.id()); + return new VirtualMachineImpl(this, vmd.id()); } else { return attachVirtualMachine(vmd.id()); } diff --git a/jdk/src/jdk.attach/unix/classes/sun/tools/attach/LinuxVirtualMachine.java b/jdk/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java similarity index 97% rename from jdk/src/jdk.attach/unix/classes/sun/tools/attach/LinuxVirtualMachine.java rename to jdk/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java index 9dec425da0d..2bf3e74a8bd 100644 --- a/jdk/src/jdk.attach/unix/classes/sun/tools/attach/LinuxVirtualMachine.java +++ b/jdk/src/jdk.attach/linux/classes/sun/tools/attach/VirtualMachineImpl.java @@ -36,7 +36,7 @@ import java.io.File; /* * Linux implementation of HotSpotVirtualMachine */ -public class LinuxVirtualMachine extends HotSpotVirtualMachine { +public class VirtualMachineImpl extends HotSpotVirtualMachine { // "/tmp" is used as a global well-known location for the files // .java_pid. and .attach_pid. It is important that this // location is the same for all processes, otherwise the tools @@ -53,7 +53,7 @@ public class LinuxVirtualMachine extends HotSpotVirtualMachine { /** * Attaches to the target VM */ - LinuxVirtualMachine(AttachProvider provider, String vmid) + VirtualMachineImpl(AttachProvider provider, String vmid) throws AttachNotSupportedException, IOException { super(provider, vmid); @@ -262,11 +262,11 @@ public class LinuxVirtualMachine extends HotSpotVirtualMachine { } else if (len == 0) return 0; - return LinuxVirtualMachine.read(s, bs, off, len); + return VirtualMachineImpl.read(s, bs, off, len); } public void close() throws IOException { - LinuxVirtualMachine.close(s); + VirtualMachineImpl.close(s); } } @@ -308,7 +308,7 @@ public class LinuxVirtualMachine extends HotSpotVirtualMachine { } catch (java.io.UnsupportedEncodingException x) { throw new InternalError(x); } - LinuxVirtualMachine.write(fd, b, 0, b.length); + VirtualMachineImpl.write(fd, b, 0, b.length); } byte b[] = new byte[1]; b[0] = 0; diff --git a/jdk/src/jdk.attach/unix/native/libattach/LinuxVirtualMachine.c b/jdk/src/jdk.attach/linux/native/libattach/VirtualMachineImpl.c similarity index 89% rename from jdk/src/jdk.attach/unix/native/libattach/LinuxVirtualMachine.c rename to jdk/src/jdk.attach/linux/native/libattach/VirtualMachineImpl.c index 855ad9299f7..6f6c0793fb8 100644 --- a/jdk/src/jdk.attach/unix/native/libattach/LinuxVirtualMachine.c +++ b/jdk/src/jdk.attach/linux/native/libattach/VirtualMachineImpl.c @@ -40,7 +40,7 @@ #include #include -#include "sun_tools_attach_LinuxVirtualMachine.h" +#include "sun_tools_attach_VirtualMachineImpl.h" #define RESTARTABLE(_cmd, _result) do { \ do { \ @@ -128,11 +128,11 @@ static pid_t getParent(pid_t pid) { /* - * Class: sun_tools_attach_LinuxVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: socket * Signature: ()I */ -JNIEXPORT jint JNICALL Java_sun_tools_attach_LinuxVirtualMachine_socket +JNIEXPORT jint JNICALL Java_sun_tools_attach_VirtualMachineImpl_socket (JNIEnv *env, jclass cls) { int fd = socket(PF_UNIX, SOCK_STREAM, 0); @@ -143,11 +143,11 @@ JNIEXPORT jint JNICALL Java_sun_tools_attach_LinuxVirtualMachine_socket } /* - * Class: sun_tools_attach_LinuxVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: connect * Signature: (ILjava/lang/String;)I */ -JNIEXPORT void JNICALL Java_sun_tools_attach_LinuxVirtualMachine_connect +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_connect (JNIEnv *env, jclass cls, jint fd, jstring path) { jboolean isCopy; @@ -189,11 +189,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_LinuxVirtualMachine_connect } /* - * Class: sun_tools_attach_LinuxVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: isLinuxThreads * Signature: ()V */ -JNIEXPORT jboolean JNICALL Java_sun_tools_attach_LinuxVirtualMachine_isLinuxThreads +JNIEXPORT jboolean JNICALL Java_sun_tools_attach_VirtualMachineImpl_isLinuxThreads (JNIEnv *env, jclass cls) { # ifndef _CS_GNU_LIBPTHREAD_VERSION @@ -250,11 +250,11 @@ static void ChildCountCallback(const pid_t pid, void* user_data) { } /* - * Class: sun_tools_attach_LinuxVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: getLinuxThreadsManager * Signature: (I)I */ -JNIEXPORT jint JNICALL Java_sun_tools_attach_LinuxVirtualMachine_getLinuxThreadsManager +JNIEXPORT jint JNICALL Java_sun_tools_attach_VirtualMachineImpl_getLinuxThreadsManager (JNIEnv *env, jclass cls, jint pid) { ChildCountContext context; @@ -312,11 +312,11 @@ static void SendQuitCallback(const pid_t pid, void* user_data) { } /* - * Class: sun_tools_attach_LinuxVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: sendQuitToChildrenOf * Signature: (I)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_LinuxVirtualMachine_sendQuitToChildrenOf +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_sendQuitToChildrenOf (JNIEnv *env, jclass cls, jint pid) { SendQuitContext context; @@ -329,11 +329,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_LinuxVirtualMachine_sendQuitToChild } /* - * Class: sun_tools_attach_LinuxVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: sendQuitTo * Signature: (I)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_LinuxVirtualMachine_sendQuitTo +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_sendQuitTo (JNIEnv *env, jclass cls, jint pid) { if (kill((pid_t)pid, SIGQUIT)) { @@ -342,11 +342,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_LinuxVirtualMachine_sendQuitTo } /* - * Class: sun_tools_attach_LinuxVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: checkPermissions * Signature: (Ljava/lang/String;)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_LinuxVirtualMachine_checkPermissions +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_checkPermissions (JNIEnv *env, jclass cls, jstring path) { jboolean isCopy; @@ -390,11 +390,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_LinuxVirtualMachine_checkPermission } /* - * Class: sun_tools_attach_LinuxVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: close * Signature: (I)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_LinuxVirtualMachine_close +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_close (JNIEnv *env, jclass cls, jint fd) { int res; @@ -402,11 +402,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_LinuxVirtualMachine_close } /* - * Class: sun_tools_attach_LinuxVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: read * Signature: (I[BI)I */ -JNIEXPORT jint JNICALL Java_sun_tools_attach_LinuxVirtualMachine_read +JNIEXPORT jint JNICALL Java_sun_tools_attach_VirtualMachineImpl_read (JNIEnv *env, jclass cls, jint fd, jbyteArray ba, jint off, jint baLen) { unsigned char buf[128]; @@ -432,11 +432,11 @@ JNIEXPORT jint JNICALL Java_sun_tools_attach_LinuxVirtualMachine_read } /* - * Class: sun_tools_attach_LinuxVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: write * Signature: (I[B)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_LinuxVirtualMachine_write +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_write (JNIEnv *env, jclass cls, jint fd, jbyteArray ba, jint off, jint bufLen) { size_t remaining = bufLen; diff --git a/jdk/src/jdk.attach/unix/classes/sun/tools/attach/BsdAttachProvider.java b/jdk/src/jdk.attach/macosx/classes/sun/tools/attach/AttachProviderImpl.java similarity index 93% rename from jdk/src/jdk.attach/unix/classes/sun/tools/attach/BsdAttachProvider.java rename to jdk/src/jdk.attach/macosx/classes/sun/tools/attach/AttachProviderImpl.java index c4f6a5cdc97..0f129769c0e 100644 --- a/jdk/src/jdk.attach/unix/classes/sun/tools/attach/BsdAttachProvider.java +++ b/jdk/src/jdk.attach/macosx/classes/sun/tools/attach/AttachProviderImpl.java @@ -35,12 +35,12 @@ import java.io.IOException; * An AttachProvider implementation for Bsd that uses a UNIX domain * socket. */ -public class BsdAttachProvider extends HotSpotAttachProvider { +public class AttachProviderImpl extends HotSpotAttachProvider { // perf counter for the JVM version private static final String JVM_VERSION = "java.property.java.vm.version"; - public BsdAttachProvider() { + public AttachProviderImpl() { } public String name() { @@ -60,7 +60,7 @@ public class BsdAttachProvider extends HotSpotAttachProvider { // to be not attachable. testAttachable(vmid); - return new BsdVirtualMachine(this, vmid); + return new VirtualMachineImpl(this, vmid); } public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd) @@ -75,7 +75,7 @@ public class BsdAttachProvider extends HotSpotAttachProvider { if (vmd instanceof HotSpotVirtualMachineDescriptor) { assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable(); checkAttachPermission(); - return new BsdVirtualMachine(this, vmd.id()); + return new VirtualMachineImpl(this, vmd.id()); } else { return attachVirtualMachine(vmd.id()); } diff --git a/jdk/src/jdk.attach/unix/classes/sun/tools/attach/BsdVirtualMachine.java b/jdk/src/jdk.attach/macosx/classes/sun/tools/attach/VirtualMachineImpl.java similarity index 97% rename from jdk/src/jdk.attach/unix/classes/sun/tools/attach/BsdVirtualMachine.java rename to jdk/src/jdk.attach/macosx/classes/sun/tools/attach/VirtualMachineImpl.java index ad344f1411e..0e304d0347d 100644 --- a/jdk/src/jdk.attach/unix/classes/sun/tools/attach/BsdVirtualMachine.java +++ b/jdk/src/jdk.attach/macosx/classes/sun/tools/attach/VirtualMachineImpl.java @@ -36,7 +36,7 @@ import java.io.File; /* * Bsd implementation of HotSpotVirtualMachine */ -public class BsdVirtualMachine extends HotSpotVirtualMachine { +public class VirtualMachineImpl extends HotSpotVirtualMachine { // "tmpdir" is used as a global well-known location for the files // .java_pid. and .attach_pid. It is important that this // location is the same for all processes, otherwise the tools @@ -52,7 +52,7 @@ public class BsdVirtualMachine extends HotSpotVirtualMachine { /** * Attaches to the target VM */ - BsdVirtualMachine(AttachProvider provider, String vmid) + VirtualMachineImpl(AttachProvider provider, String vmid) throws AttachNotSupportedException, IOException { super(provider, vmid); @@ -247,11 +247,11 @@ public class BsdVirtualMachine extends HotSpotVirtualMachine { return 0; } - return BsdVirtualMachine.read(s, bs, off, len); + return VirtualMachineImpl.read(s, bs, off, len); } public void close() throws IOException { - BsdVirtualMachine.close(s); + VirtualMachineImpl.close(s); } } @@ -275,7 +275,7 @@ public class BsdVirtualMachine extends HotSpotVirtualMachine { } catch (java.io.UnsupportedEncodingException x) { throw new InternalError(); } - BsdVirtualMachine.write(fd, b, 0, b.length); + VirtualMachineImpl.write(fd, b, 0, b.length); } byte b[] = new byte[1]; b[0] = 0; diff --git a/jdk/src/jdk.attach/unix/native/libattach/BsdVirtualMachine.c b/jdk/src/jdk.attach/macosx/native/libattach/VirtualMachineImpl.c similarity index 87% rename from jdk/src/jdk.attach/unix/native/libattach/BsdVirtualMachine.c rename to jdk/src/jdk.attach/macosx/native/libattach/VirtualMachineImpl.c index 7735a90b4ba..8fa1e6abd78 100644 --- a/jdk/src/jdk.attach/unix/native/libattach/BsdVirtualMachine.c +++ b/jdk/src/jdk.attach/macosx/native/libattach/VirtualMachineImpl.c @@ -41,7 +41,7 @@ #include #include -#include "sun_tools_attach_BsdVirtualMachine.h" +#include "sun_tools_attach_VirtualMachineImpl.h" #define RESTARTABLE(_cmd, _result) do { \ do { \ @@ -50,11 +50,11 @@ } while(0) /* - * Class: sun_tools_attach_BsdVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: socket * Signature: ()I */ -JNIEXPORT jint JNICALL Java_sun_tools_attach_BsdVirtualMachine_socket +JNIEXPORT jint JNICALL Java_sun_tools_attach_VirtualMachineImpl_socket (JNIEnv *env, jclass cls) { int fd = socket(PF_UNIX, SOCK_STREAM, 0); @@ -65,11 +65,11 @@ JNIEXPORT jint JNICALL Java_sun_tools_attach_BsdVirtualMachine_socket } /* - * Class: sun_tools_attach_BsdVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: connect * Signature: (ILjava/lang/String;)I */ -JNIEXPORT void JNICALL Java_sun_tools_attach_BsdVirtualMachine_connect +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_connect (JNIEnv *env, jclass cls, jint fd, jstring path) { jboolean isCopy; @@ -111,11 +111,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_BsdVirtualMachine_connect } /* - * Class: sun_tools_attach_BsdVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: sendQuitTo * Signature: (I)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_BsdVirtualMachine_sendQuitTo +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_sendQuitTo (JNIEnv *env, jclass cls, jint pid) { if (kill((pid_t)pid, SIGQUIT)) { @@ -124,11 +124,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_BsdVirtualMachine_sendQuitTo } /* - * Class: sun_tools_attach_BsdVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: checkPermissions * Signature: (Ljava/lang/String;)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_BsdVirtualMachine_checkPermissions +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_checkPermissions (JNIEnv *env, jclass cls, jstring path) { jboolean isCopy; @@ -172,11 +172,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_BsdVirtualMachine_checkPermissions } /* - * Class: sun_tools_attach_BsdVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: close * Signature: (I)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_BsdVirtualMachine_close +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_close (JNIEnv *env, jclass cls, jint fd) { int res; @@ -184,11 +184,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_BsdVirtualMachine_close } /* - * Class: sun_tools_attach_BsdVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: read * Signature: (I[BI)I */ -JNIEXPORT jint JNICALL Java_sun_tools_attach_BsdVirtualMachine_read +JNIEXPORT jint JNICALL Java_sun_tools_attach_VirtualMachineImpl_read (JNIEnv *env, jclass cls, jint fd, jbyteArray ba, jint off, jint baLen) { unsigned char buf[128]; @@ -214,11 +214,11 @@ JNIEXPORT jint JNICALL Java_sun_tools_attach_BsdVirtualMachine_read } /* - * Class: sun_tools_attach_BsdVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: write * Signature: (I[B)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_BsdVirtualMachine_write +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_write (JNIEnv *env, jclass cls, jint fd, jbyteArray ba, jint off, jint bufLen) { size_t remaining = bufLen; @@ -249,7 +249,7 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_BsdVirtualMachine_write * Method: createAttachFile * Signature: (Ljava.lang.String;)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_BsdVirtualMachine_createAttachFile(JNIEnv *env, jclass cls, jstring path) +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_createAttachFile(JNIEnv *env, jclass cls, jstring path) { const char* _path; jboolean isCopy; @@ -286,7 +286,7 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_BsdVirtualMachine_createAttachFile( * Method: getTempDir * Signature: (V)Ljava.lang.String; */ -JNIEXPORT jstring JNICALL Java_sun_tools_attach_BsdVirtualMachine_getTempDir(JNIEnv *env, jclass cls) +JNIEXPORT jstring JNICALL Java_sun_tools_attach_VirtualMachineImpl_getTempDir(JNIEnv *env, jclass cls) { // This must be hard coded because it's the system's temporary // directory not the java application's temp directory, ala java.io.tmpdir. diff --git a/jdk/src/jdk.attach/share/classes/META-INF/services/com.sun.tools.attach.spi.AttachProvider b/jdk/src/jdk.attach/share/classes/META-INF/services/com.sun.tools.attach.spi.AttachProvider index 4cb7f1d2c73..7ab9b79274a 100644 --- a/jdk/src/jdk.attach/share/classes/META-INF/services/com.sun.tools.attach.spi.AttachProvider +++ b/jdk/src/jdk.attach/share/classes/META-INF/services/com.sun.tools.attach.spi.AttachProvider @@ -22,13 +22,4 @@ # or visit www.oracle.com if you need additional information or have any # questions. # -# List all Sun provided attach providers here. If there -# are providers that are only available on a particular OS -# then prefix the line with #[OS] and they will automatically -# uncommented by the build process. -# -#[solaris]sun.tools.attach.SolarisAttachProvider -#[windows]sun.tools.attach.WindowsAttachProvider -#[linux]sun.tools.attach.LinuxAttachProvider -#[macosx]sun.tools.attach.BsdAttachProvider -#[aix]sun.tools.attach.AixAttachProvider +sun.tools.attach.AttachProviderImpl diff --git a/jdk/src/jdk.attach/unix/classes/sun/tools/attach/SolarisAttachProvider.java b/jdk/src/jdk.attach/solaris/classes/sun/tools/attach/AttachProviderImpl.java similarity index 92% rename from jdk/src/jdk.attach/unix/classes/sun/tools/attach/SolarisAttachProvider.java rename to jdk/src/jdk.attach/solaris/classes/sun/tools/attach/AttachProviderImpl.java index 9fd6dd1e2bd..b044bb6965f 100644 --- a/jdk/src/jdk.attach/unix/classes/sun/tools/attach/SolarisAttachProvider.java +++ b/jdk/src/jdk.attach/solaris/classes/sun/tools/attach/AttachProviderImpl.java @@ -34,9 +34,9 @@ import java.io.IOException; * An AttachProvider implementation for Solaris that use the doors * interface to the VM. */ -public class SolarisAttachProvider extends HotSpotAttachProvider { +public class AttachProviderImpl extends HotSpotAttachProvider { - public SolarisAttachProvider() { + public AttachProviderImpl() { } public String name() { @@ -56,7 +56,7 @@ public class SolarisAttachProvider extends HotSpotAttachProvider { // to be not attachable. testAttachable(vmid); - return new SolarisVirtualMachine(this, vmid); + return new VirtualMachineImpl(this, vmid); } public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd) @@ -71,7 +71,7 @@ public class SolarisAttachProvider extends HotSpotAttachProvider { if (vmd instanceof HotSpotVirtualMachineDescriptor) { assert ((HotSpotVirtualMachineDescriptor)vmd).isAttachable(); checkAttachPermission(); - return new SolarisVirtualMachine(this, vmd.id()); + return new VirtualMachineImpl(this, vmd.id()); } else { return attachVirtualMachine(vmd.id()); } diff --git a/jdk/src/jdk.attach/unix/classes/sun/tools/attach/SolarisVirtualMachine.java b/jdk/src/jdk.attach/solaris/classes/sun/tools/attach/VirtualMachineImpl.java similarity index 97% rename from jdk/src/jdk.attach/unix/classes/sun/tools/attach/SolarisVirtualMachine.java rename to jdk/src/jdk.attach/solaris/classes/sun/tools/attach/VirtualMachineImpl.java index 3c57e4bda6a..b93f745475e 100644 --- a/jdk/src/jdk.attach/unix/classes/sun/tools/attach/SolarisVirtualMachine.java +++ b/jdk/src/jdk.attach/solaris/classes/sun/tools/attach/VirtualMachineImpl.java @@ -37,7 +37,7 @@ import java.io.FileNotFoundException; /* * Solaris implementation of HotSpotVirtualMachine. */ -public class SolarisVirtualMachine extends HotSpotVirtualMachine { +public class VirtualMachineImpl extends HotSpotVirtualMachine { // "/tmp" is used as a global well-known location for the files // .java_pid. and .attach_pid. It is important that this // location is the same for all processes, otherwise the tools @@ -51,7 +51,7 @@ public class SolarisVirtualMachine extends HotSpotVirtualMachine { /** * Attaches to the target VM */ - SolarisVirtualMachine(AttachProvider provider, String vmid) + VirtualMachineImpl(AttachProvider provider, String vmid) throws AttachNotSupportedException, IOException { super(provider, vmid); @@ -190,11 +190,11 @@ public class SolarisVirtualMachine extends HotSpotVirtualMachine { } else if (len == 0) return 0; - return SolarisVirtualMachine.read(s, bs, off, len); + return VirtualMachineImpl.read(s, bs, off, len); } public void close() throws IOException { - SolarisVirtualMachine.close(s); + VirtualMachineImpl.close(s); } } diff --git a/jdk/src/jdk.attach/unix/native/libattach/SolarisVirtualMachine.c b/jdk/src/jdk.attach/solaris/native/libattach/VirtualMachineImpl.c similarity index 92% rename from jdk/src/jdk.attach/unix/native/libattach/SolarisVirtualMachine.c rename to jdk/src/jdk.attach/solaris/native/libattach/VirtualMachineImpl.c index 32dd249f321..7f0f0e37560 100644 --- a/jdk/src/jdk.attach/unix/native/libattach/SolarisVirtualMachine.c +++ b/jdk/src/jdk.attach/solaris/native/libattach/VirtualMachineImpl.c @@ -36,7 +36,7 @@ #include "jni.h" #include "jni_util.h" -#include "sun_tools_attach_SolarisVirtualMachine.h" +#include "sun_tools_attach_VirtualMachineImpl.h" #define RESTARTABLE(_cmd, _result) do { \ do { \ @@ -45,11 +45,11 @@ } while(0) /* - * Class: sun_tools_attach_SolarisVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: open * Signature: (Ljava/lang/String;)I */ -JNIEXPORT jint JNICALL Java_sun_tools_attach_SolarisVirtualMachine_open +JNIEXPORT jint JNICALL Java_sun_tools_attach_VirtualMachineImpl_open (JNIEnv *env, jclass cls, jstring path) { jboolean isCopy; @@ -85,11 +85,11 @@ JNIEXPORT jint JNICALL Java_sun_tools_attach_SolarisVirtualMachine_open } /* - * Class: sun_tools_attach_SolarisVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: checkPermissions * Signature: (Ljava/lang/String;)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_SolarisVirtualMachine_checkPermissions +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_checkPermissions (JNIEnv *env, jclass cls, jstring path) { jboolean isCopy; @@ -133,11 +133,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_SolarisVirtualMachine_checkPermissi } /* - * Class: sun_tools_attach_SolarisVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: close * Signature: (I)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_SolarisVirtualMachine_close +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_close (JNIEnv *env, jclass cls, jint fd) { int ret; @@ -145,11 +145,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_SolarisVirtualMachine_close } /* - * Class: sun_tools_attach_SolarisVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: read * Signature: (I[BI)I */ -JNIEXPORT jint JNICALL Java_sun_tools_attach_SolarisVirtualMachine_read +JNIEXPORT jint JNICALL Java_sun_tools_attach_VirtualMachineImpl_read (JNIEnv *env, jclass cls, jint fd, jbyteArray ba, jint off, jint baLen) { unsigned char buf[128]; @@ -175,11 +175,11 @@ JNIEXPORT jint JNICALL Java_sun_tools_attach_SolarisVirtualMachine_read } /* - * Class: sun_tools_attach_SolarisVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: sigquit * Signature: (I)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_SolarisVirtualMachine_sigquit +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_sigquit (JNIEnv *env, jclass cls, jint pid) { if (kill((pid_t)pid, SIGQUIT) == -1) { @@ -224,11 +224,11 @@ static const char* translate_error(jint err) { static const char* PROTOCOL_VERSION = "1"; /* - * Class: sun_tools_attach_SolarisVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: enqueue * Signature: (JILjava/lang/String;[Ljava/lang/Object;)V */ -JNIEXPORT jint JNICALL Java_sun_tools_attach_SolarisVirtualMachine_enqueue +JNIEXPORT jint JNICALL Java_sun_tools_attach_VirtualMachineImpl_enqueue (JNIEnv *env, jclass cls, jint fd, jstring cmd, jobjectArray args) { jint arg_count, i; diff --git a/jdk/src/jdk.attach/windows/classes/sun/tools/attach/WindowsAttachProvider.java b/jdk/src/jdk.attach/windows/classes/sun/tools/attach/AttachProviderImpl.java similarity index 95% rename from jdk/src/jdk.attach/windows/classes/sun/tools/attach/WindowsAttachProvider.java rename to jdk/src/jdk.attach/windows/classes/sun/tools/attach/AttachProviderImpl.java index 76083a4d559..c094622e7db 100644 --- a/jdk/src/jdk.attach/windows/classes/sun/tools/attach/WindowsAttachProvider.java +++ b/jdk/src/jdk.attach/windows/classes/sun/tools/attach/AttachProviderImpl.java @@ -34,9 +34,9 @@ import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; -public class WindowsAttachProvider extends HotSpotAttachProvider { +public class AttachProviderImpl extends HotSpotAttachProvider { - public WindowsAttachProvider() { + public AttachProviderImpl() { String os = System.getProperty("os.name"); if (os.startsWith("Windows 9") || os.equals("Windows Me")) { throw new RuntimeException( @@ -66,7 +66,7 @@ public class WindowsAttachProvider extends HotSpotAttachProvider { // to be not attachable. testAttachable(vmid); - return new WindowsVirtualMachine(this, vmid); + return new VirtualMachineImpl(this, vmid); } public List listVirtualMachines() { @@ -84,7 +84,7 @@ public class WindowsAttachProvider extends HotSpotAttachProvider { */ private static boolean isTempPathSecure() { if (!wasTempPathChecked) { - synchronized (WindowsAttachProvider.class) { + synchronized (AttachProviderImpl.class) { if (!wasTempPathChecked) { // get the value of TMP/TEMP, ignoring UNC, and paths that // aren't absolute @@ -146,7 +146,7 @@ public class WindowsAttachProvider extends HotSpotAttachProvider { if (isLibraryLoadedByProcess("jvm.dll", processes[i])) { String pid = Integer.toString(processes[i]); try { - new WindowsVirtualMachine(this, pid).detach(); + new VirtualMachineImpl(this, pid).detach(); // FIXME - for now we don't have an appropriate display // name so we use pid@hostname diff --git a/jdk/src/jdk.attach/windows/classes/sun/tools/attach/WindowsVirtualMachine.java b/jdk/src/jdk.attach/windows/classes/sun/tools/attach/VirtualMachineImpl.java similarity index 96% rename from jdk/src/jdk.attach/windows/classes/sun/tools/attach/WindowsVirtualMachine.java rename to jdk/src/jdk.attach/windows/classes/sun/tools/attach/VirtualMachineImpl.java index 3b34c0d181a..8eabefa403c 100644 --- a/jdk/src/jdk.attach/windows/classes/sun/tools/attach/WindowsVirtualMachine.java +++ b/jdk/src/jdk.attach/windows/classes/sun/tools/attach/VirtualMachineImpl.java @@ -35,14 +35,14 @@ import java.io.IOException; import java.io.InputStream; import java.util.Random; -public class WindowsVirtualMachine extends HotSpotVirtualMachine { +public class VirtualMachineImpl extends HotSpotVirtualMachine { // the enqueue code stub (copied into each target VM) private static byte[] stub; private volatile long hProcess; // handle to the process - WindowsVirtualMachine(AttachProvider provider, String id) + VirtualMachineImpl(AttachProvider provider, String id) throws AttachNotSupportedException, IOException { super(provider, id); @@ -154,12 +154,12 @@ public class WindowsVirtualMachine extends HotSpotVirtualMachine { } else if (len == 0) return 0; - return WindowsVirtualMachine.readPipe(hPipe, bs, off, len); + return VirtualMachineImpl.readPipe(hPipe, bs, off, len); } public void close() throws IOException { if (hPipe != -1) { - WindowsVirtualMachine.closePipe(hPipe); + VirtualMachineImpl.closePipe(hPipe); hPipe = -1; } } diff --git a/jdk/src/jdk.attach/windows/native/libattach/WindowsAttachProvider.c b/jdk/src/jdk.attach/windows/native/libattach/AttachProviderImpl.c similarity index 87% rename from jdk/src/jdk.attach/windows/native/libattach/WindowsAttachProvider.c rename to jdk/src/jdk.attach/windows/native/libattach/AttachProviderImpl.c index e812b0f935f..7915d67d1c2 100644 --- a/jdk/src/jdk.attach/windows/native/libattach/WindowsAttachProvider.c +++ b/jdk/src/jdk.attach/windows/native/libattach/AttachProviderImpl.c @@ -30,15 +30,15 @@ #include "jni.h" #include "jni_util.h" -#include "sun_tools_attach_WindowsAttachProvider.h" +#include "sun_tools_attach_AttachProviderImpl.h" /* - * Class: sun_tools_attach_WindowsAttachProvider + * Class: sun_tools_attach_AttachProviderImpl * Method: tempPath * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL -Java_sun_tools_attach_WindowsAttachProvider_tempPath(JNIEnv *env, jclass cls) +Java_sun_tools_attach_AttachProviderImpl_tempPath(JNIEnv *env, jclass cls) { char buf[256]; DWORD bufLen, actualLen; @@ -64,12 +64,12 @@ Java_sun_tools_attach_WindowsAttachProvider_tempPath(JNIEnv *env, jclass cls) } /* - * Class: sun_tools_attach_WindowsAttachProvider + * Class: sun_tools_attach_AttachProviderImpl * Method: volumeFlags * Signature: ()J */ JNIEXPORT jlong JNICALL -Java_sun_tools_attach_WindowsAttachProvider_volumeFlags(JNIEnv *env, jclass cls, jstring str) +Java_sun_tools_attach_AttachProviderImpl_volumeFlags(JNIEnv *env, jclass cls, jstring str) { jboolean isCopy; const char* volume; @@ -98,13 +98,13 @@ Java_sun_tools_attach_WindowsAttachProvider_volumeFlags(JNIEnv *env, jclass cls, /* - * Class: sun_tools_attach_WindowsAttachProvider + * Class: sun_tools_attach_AttachProviderImpl * Method: enumProcesses * Signature: ([JI)I */ JNIEXPORT jint JNICALL -Java_sun_tools_attach_WindowsAttachProvider_enumProcesses(JNIEnv *env, jclass cls, - jintArray arr, jint max) +Java_sun_tools_attach_AttachProviderImpl_enumProcesses(JNIEnv *env, jclass cls, + jintArray arr, jint max) { DWORD size, bytesReturned; DWORD* ptr; @@ -124,13 +124,13 @@ Java_sun_tools_attach_WindowsAttachProvider_enumProcesses(JNIEnv *env, jclass cl } /* - * Class: sun_tools_attach_WindowsAttachProvider + * Class: sun_tools_attach_AttachProviderImpl * Method: isLibraryLoadedByProcess * Signature: (I[Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL -Java_sun_tools_attach_WindowsAttachProvider_isLibraryLoadedByProcess(JNIEnv *env, jclass cls, - jstring str, jint processId) +Java_sun_tools_attach_AttachProviderImpl_isLibraryLoadedByProcess(JNIEnv *env, jclass cls, + jstring str, jint processId) { HANDLE hProcess; jboolean isCopy; diff --git a/jdk/src/jdk.attach/windows/native/libattach/WindowsVirtualMachine.c b/jdk/src/jdk.attach/windows/native/libattach/VirtualMachineImpl.c similarity index 93% rename from jdk/src/jdk.attach/windows/native/libattach/WindowsVirtualMachine.c rename to jdk/src/jdk.attach/windows/native/libattach/VirtualMachineImpl.c index 411d1777a54..2fc0438f82a 100644 --- a/jdk/src/jdk.attach/windows/native/libattach/WindowsVirtualMachine.c +++ b/jdk/src/jdk.attach/windows/native/libattach/VirtualMachineImpl.c @@ -28,7 +28,7 @@ #include "jni.h" #include "jni_util.h" -#include "sun_tools_attach_WindowsVirtualMachine.h" +#include "sun_tools_attach_VirtualMachineImpl.h" /* kernel32 */ @@ -124,11 +124,11 @@ void jvm_attach_thread_func_end (void) { /* - * Class: sun_tools_attach_WindowsVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: init * Signature: ()V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_WindowsVirtualMachine_init +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_init (JNIEnv *env, jclass cls) { // All following APIs exist on Windows XP with SP2/Windows Server 2008 @@ -139,11 +139,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_WindowsVirtualMachine_init /* - * Class: sun_tools_attach_WindowsVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: generateStub * Signature: ()[B */ -JNIEXPORT jbyteArray JNICALL Java_sun_tools_attach_WindowsVirtualMachine_generateStub +JNIEXPORT jbyteArray JNICALL Java_sun_tools_attach_VirtualMachineImpl_generateStub (JNIEnv *env, jclass cls) { /* @@ -161,11 +161,11 @@ JNIEXPORT jbyteArray JNICALL Java_sun_tools_attach_WindowsVirtualMachine_generat } /* - * Class: sun_tools_attach_WindowsVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: openProcess * Signature: (I)J */ -JNIEXPORT jlong JNICALL Java_sun_tools_attach_WindowsVirtualMachine_openProcess +JNIEXPORT jlong JNICALL Java_sun_tools_attach_VirtualMachineImpl_openProcess (JNIEnv *env, jclass cls, jint pid) { HANDLE hProcess = NULL; @@ -236,11 +236,11 @@ JNIEXPORT jlong JNICALL Java_sun_tools_attach_WindowsVirtualMachine_openProcess /* - * Class: sun_tools_attach_WindowsVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: closeProcess * Signature: (J)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_WindowsVirtualMachine_closeProcess +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_closeProcess (JNIEnv *env, jclass cls, jlong hProcess) { CloseHandle((HANDLE)hProcess); @@ -248,11 +248,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_WindowsVirtualMachine_closeProcess /* - * Class: sun_tools_attach_WindowsVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: createPipe * Signature: (Ljava/lang/String;)J */ -JNIEXPORT jlong JNICALL Java_sun_tools_attach_WindowsVirtualMachine_createPipe +JNIEXPORT jlong JNICALL Java_sun_tools_attach_VirtualMachineImpl_createPipe (JNIEnv *env, jclass cls, jstring pipename) { HANDLE hPipe; @@ -281,22 +281,22 @@ JNIEXPORT jlong JNICALL Java_sun_tools_attach_WindowsVirtualMachine_createPipe } /* - * Class: sun_tools_attach_WindowsVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: closePipe * Signature: (J)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_WindowsVirtualMachine_closePipe +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_closePipe (JNIEnv *env, jclass cls, jlong hPipe) { CloseHandle( (HANDLE)hPipe ); } /* - * Class: sun_tools_attach_WindowsVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: connectPipe * Signature: (J)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_WindowsVirtualMachine_connectPipe +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_connectPipe (JNIEnv *env, jclass cls, jlong hPipe) { BOOL fConnected; @@ -309,11 +309,11 @@ JNIEXPORT void JNICALL Java_sun_tools_attach_WindowsVirtualMachine_connectPipe } /* - * Class: sun_tools_attach_WindowsVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: readPipe * Signature: (J[BII)I */ -JNIEXPORT jint JNICALL Java_sun_tools_attach_WindowsVirtualMachine_readPipe +JNIEXPORT jint JNICALL Java_sun_tools_attach_VirtualMachineImpl_readPipe (JNIEnv *env, jclass cls, jlong hPipe, jbyteArray ba, jint off, jint baLen) { unsigned char buf[128]; @@ -352,11 +352,11 @@ JNIEXPORT jint JNICALL Java_sun_tools_attach_WindowsVirtualMachine_readPipe /* - * Class: sun_tools_attach_WindowsVirtualMachine + * Class: sun_tools_attach_VirtualMachineImpl * Method: enqueue * Signature: (JZLjava/lang/String;[Ljava/lang/Object;)V */ -JNIEXPORT void JNICALL Java_sun_tools_attach_WindowsVirtualMachine_enqueue +JNIEXPORT void JNICALL Java_sun_tools_attach_VirtualMachineImpl_enqueue (JNIEnv *env, jclass cls, jlong handle, jbyteArray stub, jstring cmd, jstring pipename, jobjectArray args) { diff --git a/jdk/src/demo/aix/jvmti/hprof/porting_aix.c b/jdk/src/jdk.hprof.agent/aix/native/libhprof/porting_aix.c similarity index 100% rename from jdk/src/demo/aix/jvmti/hprof/porting_aix.c rename to jdk/src/jdk.hprof.agent/aix/native/libhprof/porting_aix.c diff --git a/jdk/src/demo/aix/jvmti/hprof/porting_aix.h b/jdk/src/jdk.hprof.agent/aix/native/libhprof/porting_aix.h similarity index 100% rename from jdk/src/demo/aix/jvmti/hprof/porting_aix.h rename to jdk/src/jdk.hprof.agent/aix/native/libhprof/porting_aix.h diff --git a/jdk/src/demo/share/jvmti/hprof/README.txt b/jdk/src/jdk.hprof.agent/share/native/libhprof/README.txt similarity index 94% rename from jdk/src/demo/share/jvmti/hprof/README.txt rename to jdk/src/jdk.hprof.agent/share/native/libhprof/README.txt index cfefddb9b6a..b57b287c634 100644 --- a/jdk/src/demo/share/jvmti/hprof/README.txt +++ b/jdk/src/jdk.hprof.agent/share/native/libhprof/README.txt @@ -106,12 +106,8 @@ Design and Implementation: * Sources in the JDK workspace The sources and Makefiles live in: - src/share/classes/com/sun/demo/jvmti/hprof/* - src/share/demo/jvmti/hprof/* + src/jdk.hprof.agent/* src/share/demo/jvmti/java_crw_demo/* - src/solaris/demo/jvmti/hprof/* - src/windows/demo/jvmti/hprof/* - make/java/java_hprof_demo/* - make/java/java_crw_demo/* + make/lib/Lib-jdk.hprof.agent.gmk -------- diff --git a/jdk/src/demo/share/jvmti/hprof/debug_malloc.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/debug_malloc.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/debug_malloc.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/debug_malloc.c diff --git a/jdk/src/demo/share/jvmti/hprof/debug_malloc.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/debug_malloc.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/debug_malloc.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/debug_malloc.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_b_spec.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_b_spec.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_b_spec.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_b_spec.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_blocks.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_blocks.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_blocks.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_blocks.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_blocks.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_blocks.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_blocks.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_blocks.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_check.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_check.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_check.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_check.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_check.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_check.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_check.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_check.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_class.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_class.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_class.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_class.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_class.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_class.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_class.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_class.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_cpu.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_cpu.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_cpu.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_cpu.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_cpu.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_cpu.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_cpu.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_cpu.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_error.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_error.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_error.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_error.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_error.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_error.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_error.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_error.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_event.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_event.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_event.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_event.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_event.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_event.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_event.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_event.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_frame.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_frame.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_frame.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_frame.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_frame.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_frame.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_frame.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_frame.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_init.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_init.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_init.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_init.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_init.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_init.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_init.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_init.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_io.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_io.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_io.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_io.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_io.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_io.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_io.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_io.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_ioname.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_ioname.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_ioname.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_ioname.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_ioname.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_ioname.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_ioname.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_ioname.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_listener.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_listener.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_listener.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_listener.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_listener.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_listener.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_listener.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_listener.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_loader.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_loader.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_loader.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_loader.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_loader.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_loader.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_loader.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_loader.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_md.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_md.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_md.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_md.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_monitor.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_monitor.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_monitor.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_monitor.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_monitor.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_monitor.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_monitor.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_monitor.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_object.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_object.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_object.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_object.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_object.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_object.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_object.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_object.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_reference.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_reference.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_reference.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_reference.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_reference.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_reference.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_reference.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_reference.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_site.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_site.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_site.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_site.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_site.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_site.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_site.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_site.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_stack.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_stack.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_stack.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_stack.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_stack.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_stack.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_stack.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_stack.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_string.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_string.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_string.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_string.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_string.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_string.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_string.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_string.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_table.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_table.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_table.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_table.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_table.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_table.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_table.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_table.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_tag.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_tag.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_tag.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_tag.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_tag.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_tag.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_tag.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_tag.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_tls.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_tls.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_tls.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_tls.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_tls.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_tls.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_tls.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_tls.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_trace.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_trace.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_trace.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_trace.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_trace.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_trace.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_trace.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_trace.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_tracker.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_tracker.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_tracker.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_tracker.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_tracker.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_tracker.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_tracker.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_tracker.h diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_util.c b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_util.c similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_util.c rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_util.c diff --git a/jdk/src/demo/share/jvmti/hprof/hprof_util.h b/jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_util.h similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/hprof_util.h rename to jdk/src/jdk.hprof.agent/share/native/libhprof/hprof_util.h diff --git a/jdk/src/demo/share/jvmti/hprof/jvm.hprof.txt b/jdk/src/jdk.hprof.agent/share/native/libhprof/jvm.hprof.txt similarity index 100% rename from jdk/src/demo/share/jvmti/hprof/jvm.hprof.txt rename to jdk/src/jdk.hprof.agent/share/native/libhprof/jvm.hprof.txt diff --git a/jdk/src/demo/share/jvmti/hprof/manual.html b/jdk/src/jdk.hprof.agent/share/native/libhprof/manual.html similarity index 99% rename from jdk/src/demo/share/jvmti/hprof/manual.html rename to jdk/src/jdk.hprof.agent/share/native/libhprof/manual.html index a62610dad66..f4ddc2ec6bc 100644 --- a/jdk/src/demo/share/jvmti/hprof/manual.html +++ b/jdk/src/jdk.hprof.agent/share/native/libhprof/manual.html @@ -1731,14 +1731,6 @@ stack depth

    -

    Source Code
    -

    -The source to HPROF is available in the JDK download in the -demo/jvmti/hprof directory. -

    *As used on this web site, the terms "Java -Virtual Machine" or "JVM" mean a virtual machine for the Java platform. -

    -


    Last modified: 2005 diff --git a/jdk/src/demo/unix/jvmti/hprof/hprof_md.c b/jdk/src/jdk.hprof.agent/unix/native/libhprof/hprof_md.c similarity index 100% rename from jdk/src/demo/unix/jvmti/hprof/hprof_md.c rename to jdk/src/jdk.hprof.agent/unix/native/libhprof/hprof_md.c diff --git a/jdk/src/demo/windows/jvmti/hprof/hprof_md.c b/jdk/src/jdk.hprof.agent/windows/native/libhprof/hprof_md.c similarity index 100% rename from jdk/src/demo/windows/jvmti/hprof/hprof_md.c rename to jdk/src/jdk.hprof.agent/windows/native/libhprof/hprof_md.c diff --git a/jdk/src/demo/share/jpda/com/sun/tools/example/debug/expr/Expr.jj b/jdk/src/jdk.jdi/share/classes/com/sun/tools/example/debug/expr/Expr.jj similarity index 100% rename from jdk/src/demo/share/jpda/com/sun/tools/example/debug/expr/Expr.jj rename to jdk/src/jdk.jdi/share/classes/com/sun/tools/example/debug/expr/Expr.jj diff --git a/jdk/src/jdk.jdwp.agent/share/native/libjdwp/debugInit.c b/jdk/src/jdk.jdwp.agent/share/native/libjdwp/debugInit.c index a1e366ec05f..8ae64d19f49 100644 --- a/jdk/src/jdk.jdwp.agent/share/native/libjdwp/debugInit.c +++ b/jdk/src/jdk.jdwp.agent/share/native/libjdwp/debugInit.c @@ -993,7 +993,7 @@ static void atexit_finish_logging(void) { /* Normal exit(0) (not _exit()) may only reach here */ - finish_logging(0); /* Only first call matters */ + finish_logging(); /* Only first call matters */ } static jboolean @@ -1281,43 +1281,49 @@ bad_option_no_msg: void debugInit_exit(jvmtiError error, const char *msg) { - int exit_code = 0; + enum exit_codes { EXIT_NO_ERRORS = 0, EXIT_JVMTI_ERROR = 1, EXIT_TRANSPORT_ERROR = 2 }; - /* Pick an error code */ - if ( error != JVMTI_ERROR_NONE ) { - exit_code = 1; - if ( docoredump ) { - LOG_MISC(("Dumping core as requested by command line")); - finish_logging(exit_code); - abort(); - } + // Prepare to exit. Log error and finish logging + LOG_MISC(("Exiting with error %s(%d): %s", jvmtiErrorText(error), error, + ((msg == NULL) ? "" : msg))); + + // coredump requested by command line. Keep JVMTI data dirty + if (error != JVMTI_ERROR_NONE && docoredump) { + LOG_MISC(("Dumping core as requested by command line")); + finish_logging(); + abort(); } - if ( msg==NULL ) { - msg = ""; - } - - LOG_MISC(("Exiting with error %s(%d): %s", jvmtiErrorText(error), error, msg)); + finish_logging(); + // Cleanup the JVMTI if we have one if (gdata != NULL) { gdata->vmDead = JNI_TRUE; - - /* Let's try and cleanup the JVMTI, if we even have one */ - if ( gdata->jvmti != NULL ) { - /* Dispose of jvmti (gdata->jvmti becomes NULL) */ + if (gdata->jvmti != NULL) { + // Dispose of jvmti (gdata->jvmti becomes NULL) disposeEnvironment(gdata->jvmti); } } - /* Finish up logging. We reach here if JDWP is doing the exiting. */ - finish_logging(exit_code); /* Only first call matters */ - - /* Let's give the JNI a FatalError if non-exit 0, which is historic way */ - if ( exit_code != 0 ) { - JNIEnv *env = NULL; - jniFatalError(env, msg, error, exit_code); + // We are here with no errors. Kill entire process and exit with zero exit code + if (error == JVMTI_ERROR_NONE) { + forceExit(EXIT_NO_ERRORS); + return; } - /* Last chance to die, this kills the entire process. */ - forceExit(exit_code); + // No transport initilized. + // As we don't have any details here exiting with separate exit code + if (error == AGENT_ERROR_TRANSPORT_INIT) { + forceExit(EXIT_TRANSPORT_ERROR); + return; + } + + // We have JVMTI error. Call hotspot jni_FatalError handler + jniFatalError(NULL, msg, error, EXIT_JVMTI_ERROR); + + // hotspot calls os:abort() so we should never reach code below, + // but guard against possible hotspot changes + + // Last chance to die, this kills the entire process. + forceExit(EXIT_JVMTI_ERROR); } diff --git a/jdk/src/jdk.jdwp.agent/share/native/libjdwp/log_messages.c b/jdk/src/jdk.jdwp.agent/share/native/libjdwp/log_messages.c index 77b8876382d..a2607d1c568 100644 --- a/jdk/src/jdk.jdwp.agent/share/native/libjdwp/log_messages.c +++ b/jdk/src/jdk.jdwp.agent/share/native/libjdwp/log_messages.c @@ -237,7 +237,7 @@ setup_logging(const char *filename, unsigned flags) /* Finish up logging, flush output to the logfile. */ void -finish_logging(int exit_code) +finish_logging() { #ifdef JDWP_LOGGING MUTEX_LOCK(my_mutex); diff --git a/jdk/src/jdk.jdwp.agent/share/native/libjdwp/log_messages.h b/jdk/src/jdk.jdwp.agent/share/native/libjdwp/log_messages.h index 0a442e943b7..129fab66cd5 100644 --- a/jdk/src/jdk.jdwp.agent/share/native/libjdwp/log_messages.h +++ b/jdk/src/jdk.jdwp.agent/share/native/libjdwp/log_messages.h @@ -29,7 +29,7 @@ /* LOG: Must be called like: LOG_category(("anything")) or LOG_category((format,args)) */ void setup_logging(const char *, unsigned); -void finish_logging(int); +void finish_logging(); #define LOG_NULL ((void)0) diff --git a/jdk/src/jdk.runtime/share/classes/sun/security/tools/policytool/PolicyTool.java b/jdk/src/jdk.runtime/share/classes/sun/security/tools/policytool/PolicyTool.java index fa667841b28..7e2e8beea86 100644 --- a/jdk/src/jdk.runtime/share/classes/sun/security/tools/policytool/PolicyTool.java +++ b/jdk/src/jdk.runtime/share/classes/sun/security/tools/policytool/PolicyTool.java @@ -1695,6 +1695,7 @@ class ToolDialog extends JDialog { PERM_ARRAY.add(new MBeanSvrPerm()); PERM_ARRAY.add(new MBeanTrustPerm()); PERM_ARRAY.add(new NetPerm()); + PERM_ARRAY.add(new NetworkPerm()); PERM_ARRAY.add(new PrivCredPerm()); PERM_ARRAY.add(new PropPerm()); PERM_ARRAY.add(new ReflectPerm()); @@ -4321,9 +4322,11 @@ class NetPerm extends Perm { super("NetPermission", "java.net.NetPermission", new String[] { + "allowHttpTrace", "setDefaultAuthenticator", "requestPasswordAuthentication", "specifyStreamHandler", + "getNetworkInformation", "setProxySelector", "getProxySelector", "setCookieHandler", @@ -4335,6 +4338,18 @@ class NetPerm extends Perm { } } +class NetworkPerm extends Perm { + public NetworkPerm() { + super("NetworkPermission", + "jdk.net.NetworkPermission", + new String[] { + "setOption.SO_FLOW_SLA", + "getOption.SO_FLOW_SLA" + }, + null); + } +} + class PrivCredPerm extends Perm { public PrivCredPerm() { super("PrivateCredentialPermission", diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 494e4e0b482..fa11cfc642d 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -127,6 +127,8 @@ # 8046351 com/sun/management/GarbageCollectorMXBean/GarbageCollectionNotificationContentTest.java generic-all com/sun/management/GarbageCollectorMXBean/GarbageCollectionNotificationTest.java generic-all +# 8056143 +java/lang/management/MemoryMXBean/LowMemoryTest.java generic-all ############################################################################ @@ -274,9 +276,6 @@ com/sun/jdi/JdbReadTwiceTest.sh generic-all # jdk_instrument -# 8037082 -java/lang/instrument/NativeMethodPrefixAgent.java generic-all - ############################################################################ # svc_tools diff --git a/jdk/test/com/sun/jdi/DoubleAgentTest.java b/jdk/test/com/sun/jdi/DoubleAgentTest.java index 3568f436ac1..0a0b5e8dcae 100644 --- a/jdk/test/com/sun/jdi/DoubleAgentTest.java +++ b/jdk/test/com/sun/jdi/DoubleAgentTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -21,136 +21,39 @@ * questions. */ +import jdk.testlibrary.OutputAnalyzer; +import jdk.testlibrary.ProcessTools; +import jdk.testlibrary.Utils; + /* @test * @bug 6354345 - * @summary Check that a double agent request fails + * @summary Check that multiple -agentlib statements in command line fails * - * @build VMConnection DoubleAgentTest Exit0 + * @library /lib/testlibrary + * @build jdk.testlibarary.* + * @build DoubleAgentTest Exit0 * @run driver DoubleAgentTest - * */ -import java.io.InputStream; -import java.io.IOException; -import java.io.File; -import java.net.ServerSocket; public class DoubleAgentTest { - static Object locker = new Object(); - static String outputText = ""; + private static final String TEST_CLASSES = System.getProperty( + "test.classes", "."); - /* - * Helper class to redirect process output/error - */ - static class IOHandler implements Runnable { - InputStream in; + public static void main(String[] args) throws Throwable { + int port = Utils.getFreePort(); - IOHandler(InputStream in) { - this.in = in; - } - - static Thread handle(InputStream in) { - IOHandler handler = new IOHandler(in); - Thread thr = new Thread(handler); - thr.setDaemon(true); - thr.start(); - return thr; - } - - public void run() { - try { - byte b[] = new byte[100]; - for (;;) { - int n = in.read(b, 0, 100); - // The first thing that will get read is - // Listening for transport dt_socket at address: xxxxx - // which shows the debuggee is ready to accept connections. - synchronized(locker) { - locker.notify(); - } - if (n < 0) { - break; - } - String s = new String(b, 0, n, "UTF-8"); - System.out.print(s); - synchronized(outputText) { - outputText += s; - } - } - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - - } - - /* - * Launch a server debuggee with the given address - */ - private static Process launch(String address, String class_name) throws IOException { - String exe = System.getProperty("java.home") - + File.separator + "bin" + File.separator + "java"; String jdwpOption = "-agentlib:jdwp=transport=dt_socket" - + ",server=y" + ",suspend=y" + ",address=" + address; - String cmd = exe + " " + VMConnection.getDebuggeeVMOptions() - + " " + jdwpOption - + " " + jdwpOption - + " " + class_name; + + ",server=y" + ",suspend=n" + ",address=*:" + String.valueOf(port); - System.out.println("Starting: " + cmd); - - Process p = Runtime.getRuntime().exec(cmd); - - return p; - } - - /* - * - pick a TCP port - * - Launch a server debuggee that should fail - * - verify we saw error - */ - public static void main(String args[]) throws Exception { - // find a free port - ServerSocket ss = new ServerSocket(0); - int port = ss.getLocalPort(); - ss.close(); - - String address = String.valueOf(port); - - // launch the server debuggee - Process process = launch(address, "Exit0"); - Thread t1 = IOHandler.handle(process.getInputStream()); - Thread t2 = IOHandler.handle(process.getErrorStream()); - - // wait for the debugge to be ready - synchronized(locker) { - locker.wait(); - } - - int exitCode = process.waitFor(); - try { - t1.join(); - t2.join(); - } catch ( InterruptedException e ) { - e.printStackTrace(); - throw new Exception("Debuggee failed InterruptedException"); - } - - if ( outputText.contains("capabilities") ) { - throw new Exception( - "Debuggee failed with ERROR about capabilities: " + outputText); - } - - if ( !outputText.contains("ERROR") ) { - throw new Exception( - "Debuggee does not have ERROR in the output: " + outputText); - } - - if ( exitCode == 0 ) { - throw new Exception( - "Debuggee should have failed with an non-zero exit code"); - } + OutputAnalyzer output = ProcessTools.executeTestJvm("-classpath", + TEST_CLASSES, + jdwpOption, // Notice jdwpOption specified twice + jdwpOption, + "Exit0"); + output.shouldContain("Cannot load this JVM TI agent twice"); + output.shouldHaveExitValue(1); } } diff --git a/jdk/test/com/sun/net/httpserver/SelCacheTest.java b/jdk/test/com/sun/net/httpserver/SelCacheTest.java index 5c574814fde..8c644bccfa5 100644 --- a/jdk/test/com/sun/net/httpserver/SelCacheTest.java +++ b/jdk/test/com/sun/net/httpserver/SelCacheTest.java @@ -24,11 +24,14 @@ /** * @test * @bug 6270015 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.SimpleSSLContext * @run main/othervm -Dsun.net.httpserver.selCacheTimeout=2 SelCacheTest * @summary Light weight HTTP server */ import com.sun.net.httpserver.*; +import jdk.testlibrary.SimpleSSLContext; import java.util.*; import java.util.concurrent.*; @@ -65,7 +68,7 @@ public class SelCacheTest extends Test { executor = Executors.newCachedThreadPool(); s1.setExecutor (executor); s2.setExecutor (executor); - ctx = new SimpleSSLContext(System.getProperty("test.src")).get(); + ctx = new SimpleSSLContext().get(); s2.setHttpsConfigurator(new HttpsConfigurator (ctx)); s1.start(); s2.start(); diff --git a/jdk/test/com/sun/net/httpserver/Test1.java b/jdk/test/com/sun/net/httpserver/Test1.java index aa1c3969a2d..55d278fe1ae 100644 --- a/jdk/test/com/sun/net/httpserver/Test1.java +++ b/jdk/test/com/sun/net/httpserver/Test1.java @@ -24,6 +24,8 @@ /** * @test * @bug 6270015 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.SimpleSSLContext * @run main/othervm Test1 * @run main/othervm -Dsun.net.httpserver.maxReqTime=10 Test1 * @run main/othervm -Dsun.net.httpserver.nodelay=true Test1 @@ -36,6 +38,7 @@ import java.util.concurrent.*; import java.io.*; import java.net.*; import javax.net.ssl.*; +import jdk.testlibrary.SimpleSSLContext; /* basic http/s connectivity test * Tests: @@ -72,7 +75,7 @@ public class Test1 extends Test { executor = Executors.newCachedThreadPool(); s1.setExecutor (executor); s2.setExecutor (executor); - ctx = new SimpleSSLContext(System.getProperty("test.src")).get(); + ctx = new SimpleSSLContext().get(); s2.setHttpsConfigurator(new HttpsConfigurator (ctx)); s1.start(); s2.start(); diff --git a/jdk/test/com/sun/net/httpserver/Test12.java b/jdk/test/com/sun/net/httpserver/Test12.java index 950103af6bc..910ec385a9c 100644 --- a/jdk/test/com/sun/net/httpserver/Test12.java +++ b/jdk/test/com/sun/net/httpserver/Test12.java @@ -24,6 +24,8 @@ /** * @test * @bug 6270015 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.SimpleSSLContext * @run main/othervm Test12 * @summary Light weight HTTP server */ @@ -34,6 +36,7 @@ import java.util.concurrent.*; import java.io.*; import java.net.*; import javax.net.ssl.*; +import jdk.testlibrary.SimpleSSLContext; /* basic http/s connectivity test * Tests: @@ -62,7 +65,7 @@ public class Test12 extends Test { executor = Executors.newCachedThreadPool(); s1.setExecutor (executor); s2.setExecutor (executor); - ctx = new SimpleSSLContext(System.getProperty("test.src")).get(); + ctx = new SimpleSSLContext().get(); s2.setHttpsConfigurator(new HttpsConfigurator (ctx)); s1.start(); s2.start(); diff --git a/jdk/test/com/sun/net/httpserver/Test13.java b/jdk/test/com/sun/net/httpserver/Test13.java index c0181a778f4..0436f8b0643 100644 --- a/jdk/test/com/sun/net/httpserver/Test13.java +++ b/jdk/test/com/sun/net/httpserver/Test13.java @@ -24,6 +24,8 @@ /** * @test * @bug 6270015 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.SimpleSSLContext * @run main/othervm Test13 * @summary Light weight HTTP server */ @@ -34,8 +36,8 @@ import java.util.concurrent.*; import java.util.logging.*; import java.io.*; import java.net.*; - import javax.net.ssl.*; +import jdk.testlibrary.SimpleSSLContext; /* basic http/s connectivity test * Tests: @@ -71,7 +73,7 @@ public class Test13 extends Test { executor = Executors.newCachedThreadPool(); s1.setExecutor (executor); s2.setExecutor (executor); - ctx = new SimpleSSLContext(System.getProperty("test.src")).get(); + ctx = new SimpleSSLContext().get(); s2.setHttpsConfigurator(new HttpsConfigurator (ctx)); s1.start(); s2.start(); diff --git a/jdk/test/com/sun/net/httpserver/Test6a.java b/jdk/test/com/sun/net/httpserver/Test6a.java index 1fb7a8c0a33..fd5a48ee730 100644 --- a/jdk/test/com/sun/net/httpserver/Test6a.java +++ b/jdk/test/com/sun/net/httpserver/Test6a.java @@ -24,6 +24,8 @@ /** * @test * @bug 6270015 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.SimpleSSLContext * @run main/othervm Test6a * @summary Light weight HTTP server */ @@ -34,6 +36,7 @@ import java.util.concurrent.*; import java.io.*; import java.net.*; import javax.net.ssl.*; +import jdk.testlibrary.SimpleSSLContext; /** * Test https POST large file via chunked encoding (unusually small chunks) @@ -47,7 +50,7 @@ public class Test6a extends Test { HttpsServer server = HttpsServer.create (addr, 0); HttpContext ctx = server.createContext ("/test", handler); ExecutorService executor = Executors.newCachedThreadPool(); - SSLContext ssl = new SimpleSSLContext(System.getProperty("test.src")).get(); + SSLContext ssl = new SimpleSSLContext().get(); server.setExecutor (executor); server.setHttpsConfigurator(new HttpsConfigurator (ssl)); server.start (); diff --git a/jdk/test/com/sun/net/httpserver/Test7a.java b/jdk/test/com/sun/net/httpserver/Test7a.java index 2fca431f3a4..3599edf2030 100644 --- a/jdk/test/com/sun/net/httpserver/Test7a.java +++ b/jdk/test/com/sun/net/httpserver/Test7a.java @@ -24,6 +24,8 @@ /** * @test * @bug 6270015 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.SimpleSSLContext * @run main/othervm Test7a * @summary Light weight HTTP server */ @@ -34,6 +36,7 @@ import java.util.concurrent.*; import java.io.*; import java.net.*; import javax.net.ssl.*; +import jdk.testlibrary.SimpleSSLContext; /** * Test POST large file via chunked encoding (large chunks) @@ -52,7 +55,7 @@ public class Test7a extends Test { HttpsServer server = HttpsServer.create (addr, 0); HttpContext ctx = server.createContext ("/test", handler); ExecutorService executor = Executors.newCachedThreadPool(); - SSLContext ssl = new SimpleSSLContext(System.getProperty("test.src")).get(); + SSLContext ssl = new SimpleSSLContext().get(); server.setHttpsConfigurator(new HttpsConfigurator (ssl)); server.setExecutor (executor); server.start (); diff --git a/jdk/test/com/sun/net/httpserver/Test8a.java b/jdk/test/com/sun/net/httpserver/Test8a.java index e2ef8ee9534..ac11931cacd 100644 --- a/jdk/test/com/sun/net/httpserver/Test8a.java +++ b/jdk/test/com/sun/net/httpserver/Test8a.java @@ -24,6 +24,8 @@ /** * @test * @bug 6270015 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.SimpleSSLContext * @run main/othervm Test8a * @summary Light weight HTTP server */ @@ -34,6 +36,7 @@ import java.util.concurrent.*; import java.io.*; import java.net.*; import javax.net.ssl.*; +import jdk.testlibrary.SimpleSSLContext; /** * Test POST large file via fixed len encoding @@ -55,7 +58,7 @@ public class Test8a extends Test { server = HttpsServer.create (addr, 0); HttpContext ctx = server.createContext ("/test", handler); executor = Executors.newCachedThreadPool(); - SSLContext ssl = new SimpleSSLContext(System.getProperty("test.src")).get(); + SSLContext ssl = new SimpleSSLContext().get(); server.setHttpsConfigurator(new HttpsConfigurator (ssl)); server.setExecutor (executor); server.start (); diff --git a/jdk/test/com/sun/net/httpserver/Test9.java b/jdk/test/com/sun/net/httpserver/Test9.java index a2b74f2bcdd..581b9e54c9f 100644 --- a/jdk/test/com/sun/net/httpserver/Test9.java +++ b/jdk/test/com/sun/net/httpserver/Test9.java @@ -24,6 +24,8 @@ /** * @test * @bug 6270015 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.SimpleSSLContext * @run main/othervm Test9 * @summary Light weight HTTP server */ @@ -34,6 +36,7 @@ import java.util.concurrent.*; import java.io.*; import java.net.*; import javax.net.ssl.*; +import jdk.testlibrary.SimpleSSLContext; /* Same as Test1 but requests run in parallel. */ @@ -59,7 +62,7 @@ public class Test9 extends Test { executor = Executors.newCachedThreadPool(); s1.setExecutor (executor); s2.setExecutor (executor); - ctx = new SimpleSSLContext(System.getProperty("test.src")).get(); + ctx = new SimpleSSLContext().get(); s2.setHttpsConfigurator(new HttpsConfigurator (ctx)); s1.start(); s2.start(); diff --git a/jdk/test/com/sun/net/httpserver/Test9a.java b/jdk/test/com/sun/net/httpserver/Test9a.java index d7460704dcf..6fd3f16562a 100644 --- a/jdk/test/com/sun/net/httpserver/Test9a.java +++ b/jdk/test/com/sun/net/httpserver/Test9a.java @@ -24,6 +24,8 @@ /** * @test * @bug 6270015 + * @library /lib/testlibrary/ + * @build jdk.testlibrary.SimpleSSLContext * @run main/othervm Test9a * @summary Light weight HTTP server */ @@ -34,6 +36,7 @@ import java.util.concurrent.*; import java.io.*; import java.net.*; import javax.net.ssl.*; +import jdk.testlibrary.SimpleSSLContext; /* Same as Test1 but requests run in parallel. */ @@ -56,8 +59,8 @@ public class Test9a extends Test { HttpContext c1 = server.createContext ("/test1", h); executor = Executors.newCachedThreadPool(); server.setExecutor (executor); - serverCtx = new SimpleSSLContext(System.getProperty("test.src")).get(); - clientCtx = new SimpleSSLContext(System.getProperty("test.src")).get(); + serverCtx = new SimpleSSLContext().get(); + clientCtx = new SimpleSSLContext().get(); server.setHttpsConfigurator(new HttpsConfigurator (serverCtx)); server.start(); diff --git a/jdk/test/java/io/ByteArrayOutputStream/MaxCapacity.java b/jdk/test/java/io/ByteArrayOutputStream/MaxCapacity.java new file mode 100644 index 00000000000..e46786cca27 --- /dev/null +++ b/jdk/test/java/io/ByteArrayOutputStream/MaxCapacity.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2014 Google Inc. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @ignore This test has huge memory requirements + * @run main/timeout=1800/othervm -Xmx8g MaxCapacity + * @bug 8055949 + * @summary Check that we can write (almost) Integer.MAX_VALUE bytes + * to a ByteArrayOutputStream. + * @author Martin Buchholz + */ +import java.io.ByteArrayOutputStream; + +public class MaxCapacity { + public static void main(String[] args) { + long maxHeap = Runtime.getRuntime().maxMemory(); + if (maxHeap < 3L * Integer.MAX_VALUE) { + System.out.printf("Skipping test; max memory %sM too small%n", + maxHeap/(1024*1024)); + return; + } + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + for (long n = 0; ; n++) { + try { + baos.write((byte)'x'); + } catch (Throwable t) { + // check data integrity while we're here + byte[] bytes = baos.toByteArray(); + if (bytes.length != n) + throw new AssertionError("wrong length"); + if (bytes[0] != 'x' || + bytes[bytes.length - 1] != 'x') + throw new AssertionError("wrong contents"); + + long gap = Integer.MAX_VALUE - n; + System.out.printf("gap=%dM %d%n", gap/(1024*1024), gap); + if (gap > 1024) + throw t; + // t.printStackTrace(); + break; + } + } + } +} diff --git a/jdk/test/java/lang/instrument/MakeJAR2.sh b/jdk/test/java/lang/instrument/MakeJAR2.sh index 062abe41444..596a0d47ed1 100644 --- a/jdk/test/java/lang/instrument/MakeJAR2.sh +++ b/jdk/test/java/lang/instrument/MakeJAR2.sh @@ -75,9 +75,9 @@ JAR="${COMPILEJAVA}/bin/jar" cp ${TESTSRC}/${AGENT}.java . cp ${TESTSRC}/${APP}.java . -rm -rf ilib -mkdir ilib -cp ${TESTSRC}/ilib/*.java ilib +rm -rf asmlib +mkdir asmlib +cp ${TESTSRC}/asmlib/*.java asmlib rm -rf bootpath mkdir -p bootpath/bootreporter cp ${TESTSRC}/bootreporter/*.java bootpath/bootreporter @@ -86,7 +86,7 @@ cd bootpath ${JAVAC} ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} bootreporter/*.java cd .. -${JAVAC} ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} ${AGENT}.java ilib/*.java +${JAVAC} ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} -XDignore.symbol.file ${AGENT}.java asmlib/*.java ${JAVAC} ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} -classpath .${PATHSEP}bootpath ${APP}.java echo "Manifest-Version: 1.0" > ${AGENT}.mf @@ -98,6 +98,6 @@ while [ $# != 0 ] ; do shift done -${JAR} ${TESTTOOLVMOPTS} cvfm ${AGENT}.jar ${AGENT}.mf ${AGENT}*.class ilib/*.class +${JAR} ${TESTTOOLVMOPTS} cvfm ${AGENT}.jar ${AGENT}.mf ${AGENT}*.class asmlib/*.class -# rm -rf ${AGENT}.java ilib ${AGENT}.mf ${AGENT}*.class +# rm -rf ${AGENT}.java asmlib ${AGENT}.mf ${AGENT}*.class diff --git a/jdk/test/java/lang/instrument/NativeMethodPrefixAgent.java b/jdk/test/java/lang/instrument/NativeMethodPrefixAgent.java index 5bc34e46c15..1a51a8b4953 100644 --- a/jdk/test/java/lang/instrument/NativeMethodPrefixAgent.java +++ b/jdk/test/java/lang/instrument/NativeMethodPrefixAgent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -35,7 +35,7 @@ import java.lang.instrument.*; import java.security.ProtectionDomain; import java.io.*; -import ilib.*; +import asmlib.*; class NativeMethodPrefixAgent { @@ -62,14 +62,25 @@ class NativeMethodPrefixAgent { System.out.println(trname + ": " + (redef? "Retransforming " : "Loading ") + className); if (className != null) { - Options opt = new Options(); - opt.shouldInstrumentNativeMethods = true; - opt.trackerClassName = "bootreporter/StringIdCallbackReporter"; - opt.wrappedTrackerMethodName = "tracker"; - opt.fixedIndex = transformId; - opt.wrappedPrefix = "wrapped_" + trname + "_"; try { - byte[] newcf = Inject.instrumentation(opt, loader, className, classfileBuffer); + byte[] newcf = Instrumentor.instrFor(classfileBuffer) + .addNativeMethodTrackingInjection( + "wrapped_" + trname + "_", + (h)->{ + h.push(h.getName()); + h.push(transformId); + h.invokeStatic("bootreporter/StringIdCallbackReporter", "tracker", "(Ljava/lang/String;I)V", false); + }) + .apply(); + /*** debugging ... + if (newcf != null) { + String fname = trname + (redef?"_redef" : "") + "/" + className; + System.err.println("dumping to: " + fname); + write_buffer(fname + "_before.class", classfileBuffer); + write_buffer(fname + "_instr.class", newcf); + } + ***/ + return redef? null : newcf; } catch (Throwable ex) { System.err.println("ERROR: Injection failure: " + ex); @@ -86,10 +97,14 @@ class NativeMethodPrefixAgent { // for debugging static void write_buffer(String fname, byte[]buffer) { try { - FileOutputStream outStream = new FileOutputStream(fname); - outStream.write(buffer, 0, buffer.length); - outStream.close(); - } catch (Exception ex) { + File f = new File(fname); + if (!f.getParentFile().exists()) { + f.getParentFile().mkdirs(); + } + try (FileOutputStream outStream = new FileOutputStream(f)) { + outStream.write(buffer, 0, buffer.length); + } + } catch (IOException ex) { System.err.println("EXCEPTION in write_buffer: " + ex); } } diff --git a/jdk/test/java/lang/instrument/RetransformAgent.java b/jdk/test/java/lang/instrument/RetransformAgent.java index 34b301b16c8..99d2bc089ed 100644 --- a/jdk/test/java/lang/instrument/RetransformAgent.java +++ b/jdk/test/java/lang/instrument/RetransformAgent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -34,8 +34,7 @@ import java.lang.instrument.*; import java.security.ProtectionDomain; import java.io.*; - -import ilib.*; +import asmlib.*; class RetransformAgent { @@ -75,20 +74,25 @@ class RetransformAgent { // System.err.println("hook " + trname + ": " + className + // (redef? " REDEF" : " LOAD")); if ((redef? onRedef : onLoad) && className != null && className.equals(cname)) { - Options opt = new Options(); - opt.shouldInstrumentIndexed = true; - opt.shouldInstrumentCall = true; - opt.targetMethod = nname; - opt.fixedIndex = redef? redefIndex : loadIndex; - opt.trackerClassName = "RetransformAgent"; + int fixedIndex = redef ? redefIndex : loadIndex; try { - byte[] newcf = Inject.instrumentation(opt, loader, className, classfileBuffer); + byte[] newcf = Instrumentor.instrFor(classfileBuffer) + .addMethodEntryInjection( + nname, + (h)->{ + h.push(fixedIndex); + h.invokeStatic("RetransformAgent", "callTracker", "(I)V", false); + }) + .apply(); /*** debugging ... - String fname = trname + (redef?"_redef" : ""); - write_buffer(fname + "_before.class", classfileBuffer); - write_buffer(fname + "_instr.class", newcf); + if (newcf != null) { + String fname = trname + (redef?"_redef" : "") + "/" + className; + System.err.println("dumping to: " + fname); + write_buffer(fname + "_before.class", classfileBuffer); + write_buffer(fname + "_instr.class", newcf); + } ***/ - System.err.println(trname + ": " + className + " index: " + opt.fixedIndex + + System.err.println(trname + ": " + className + " index: " + fixedIndex + (redef? " REDEF" : " LOAD") + " len before: " + classfileBuffer.length + " after: " + newcf.length); @@ -104,10 +108,14 @@ class RetransformAgent { static void write_buffer(String fname, byte[]buffer) { try { - FileOutputStream outStream = new FileOutputStream(fname); - outStream.write(buffer, 0, buffer.length); - outStream.close(); - } catch (Exception ex) { + File f = new File(fname); + if (!f.getParentFile().exists()) { + f.getParentFile().mkdirs(); + } + try (FileOutputStream outStream = new FileOutputStream(f)) { + outStream.write(buffer, 0, buffer.length); + } + } catch (IOException ex) { System.err.println("EXCEPTION in write_buffer: " + ex); } } diff --git a/jdk/test/java/lang/instrument/asmlib/Instrumentor.java b/jdk/test/java/lang/instrument/asmlib/Instrumentor.java new file mode 100644 index 00000000000..333cd27873f --- /dev/null +++ b/jdk/test/java/lang/instrument/asmlib/Instrumentor.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package asmlib; + +import java.io.PrintStream; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import jdk.internal.org.objectweb.asm.ClassReader; +import jdk.internal.org.objectweb.asm.ClassVisitor; +import jdk.internal.org.objectweb.asm.ClassWriter; +import jdk.internal.org.objectweb.asm.MethodVisitor; +import jdk.internal.org.objectweb.asm.Opcodes; + +import java.util.function.Consumer; +import jdk.internal.org.objectweb.asm.Type; + +public class Instrumentor { + public static class InstrHelper { + private final MethodVisitor mv; + private final String name; + + InstrHelper(MethodVisitor mv, String name) { + this.mv = mv; + this.name = name; + } + + public String getName() { + return this.name; + } + + public void invokeStatic(String owner, String name, String desc, boolean itf) { + mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, itf); + } + + public void invokeSpecial(String owner, String name, String desc) { + mv.visitMethodInsn(Opcodes.INVOKESPECIAL, owner, name, desc, false); + } + + public void invokeVirtual(String owner, String name, String desc) { + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc, false); + } + + public void push(int val) { + if (val >= -1 && val <= 5) { + mv.visitInsn(Opcodes.ICONST_0 + val); + } else if (val >= Byte.MIN_VALUE && val <= Byte.MAX_VALUE) { + mv.visitIntInsn(Opcodes.BIPUSH, val); + } else if (val >= Short.MIN_VALUE && val <= Short.MAX_VALUE) { + mv.visitIntInsn(Opcodes.SIPUSH, val); + } else { + mv.visitLdcInsn(val); + } + } + + public void push(Object val) { + mv.visitLdcInsn(val); + } + + public void println(String s) { + mv.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(System.class), "out", Type.getDescriptor(PrintStream.class)); + mv.visitLdcInsn(s); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PrintStream.class), "println", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); + } + } + + public static Instrumentor instrFor(byte[] classData) { + return new Instrumentor(classData); + } + + + private final ClassReader cr; + private final ClassWriter output; + private ClassVisitor instrumentingVisitor = null; + private final AtomicInteger matches = new AtomicInteger(0); + + private Instrumentor(byte[] classData) { + cr = new ClassReader(classData); + output = new ClassWriter(ClassWriter.COMPUTE_MAXS); + instrumentingVisitor = output; + } + + public synchronized Instrumentor addMethodEntryInjection(String methodName, Consumer injector) { + instrumentingVisitor = new ClassVisitor(Opcodes.ASM5, instrumentingVisitor) { + @Override + public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { + MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); + + if (name.equals(methodName)) { + matches.getAndIncrement(); + + mv = new MethodVisitor(Opcodes.ASM5, mv) { + @Override + public void visitCode() { + injector.accept(new InstrHelper(mv, name)); + } + }; + } + return mv; + } + }; + return this; + } + + public synchronized Instrumentor addNativeMethodTrackingInjection(String prefix, Consumer injector) { + instrumentingVisitor = new ClassVisitor(Opcodes.ASM5, instrumentingVisitor) { + private final Set> wmGenerators = new HashSet<>(); + private String className; + + @Override + public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { + this.className = name; + super.visit(version, access, name, signature, superName, interfaces); + } + + + @Override + public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { + if ((access & Opcodes.ACC_NATIVE) != 0) { + matches.getAndIncrement(); + + String newName = prefix + name; + wmGenerators.add((v)->{ + MethodVisitor mv = v.visitMethod(access & ~Opcodes.ACC_NATIVE, name, desc, signature, exceptions); + mv.visitCode(); + injector.accept(new InstrHelper(mv, name)); + Type[] argTypes = Type.getArgumentTypes(desc); + Type retType = Type.getReturnType(desc); + + boolean isStatic = (access & Opcodes.ACC_STATIC) != 0; + if (!isStatic) { + mv.visitIntInsn(Opcodes.ALOAD, 0); // load "this" + } + + // load the method parameters + if (argTypes.length > 0) { + int ptr = isStatic ? 0 : 1; + for(Type argType : argTypes) { + mv.visitIntInsn(argType.getOpcode(Opcodes.ILOAD), ptr); + ptr += argType.getSize(); + } + } + + mv.visitMethodInsn(isStatic ? Opcodes.INVOKESTATIC : Opcodes.INVOKESPECIAL, className, newName, desc, false); + mv.visitInsn(retType.getOpcode(Opcodes.IRETURN)); + + mv.visitMaxs(1, 1); // dummy call; let ClassWriter to deal with this + mv.visitEnd(); + }); + return super.visitMethod(access, newName, desc, signature, exceptions); + } + return super.visitMethod(access, name, desc, signature, exceptions); + } + + @Override + public void visitEnd() { + wmGenerators.stream().forEach((e) -> { + e.accept(cv); + }); + super.visitEnd(); + } + }; + + return this; + } + + public synchronized byte[] apply() { + cr.accept(instrumentingVisitor, ClassReader.SKIP_DEBUG + ClassReader.EXPAND_FRAMES); + + return matches.get() == 0 ? null : output.toByteArray(); + } +} diff --git a/jdk/test/java/lang/instrument/ilib/ClassDump.java b/jdk/test/java/lang/instrument/ilib/ClassDump.java deleted file mode 100644 index 4dd1908f286..00000000000 --- a/jdk/test/java/lang/instrument/ilib/ClassDump.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package ilib; - -import java.io.IOException; -import java.io.File; -import java.io.FileOutputStream; -import java.io.DataOutputStream; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.CharArrayWriter; -import java.util.List; -import java.util.Iterator; -import java.util.ArrayList; - -public class ClassDump implements RuntimeConstants { - - public static void dump(Options opt, - ClassLoader loader, - String className, - byte[] classfileBuffer) { - ClassReaderWriter c = new ClassReaderWriter(classfileBuffer); - (new ClassDump(className, c)).doit(); - } - - static boolean verbose = true; - - final String className; - final ClassReaderWriter c; - private final PrintStream output; - - int constantPoolCount; - int methodsCount; - - ClassDump(String className, ClassReaderWriter c) { - this.className = className; - this.c = c; - this.output = System.err; - } - - void doit() { - int i; - c.copy(4 + 2 + 2); // magic min/maj version - constantPoolCount = c.copyU2(); - // copy old constant pool - c.copyConstantPool(constantPoolCount); - - traceln("ConstantPool size: " + constantPoolCount); - - c.copy(2 + 2 + 2); // access, this, super - int interfaceCount = c.copyU2(); - traceln("interfaceCount: " + interfaceCount); - c.copy(interfaceCount * 2); - copyFields(); // fields - copyMethods(); // methods - int attrCount = c.copyU2(); - traceln("class attrCount: " + attrCount); - // copy the class attributes - copyAttrs(attrCount); - } - - - void copyFields() { - int count = c.copyU2(); - if (verbose) { - System.out.println("fields count: " + count); - } - for (int i = 0; i < count; ++i) { - c.copy(6); // access, name, descriptor - int attrCount = c.copyU2(); - if (verbose) { - System.out.println("field attr count: " + attrCount); - } - copyAttrs(attrCount); - } - } - - void copyMethods() { - methodsCount = c.copyU2(); - if (verbose) { - System.out.println("methods count: " + methodsCount); - } - for (int i = 0; i < methodsCount; ++i) { - copyMethod(); - } - } - - void copyMethod() { - int accessFlags = c.copyU2();// access flags - int nameIndex = c.copyU2(); // name - checkIndex(nameIndex, "Method name"); - String methodName = c.constantPoolString(nameIndex); - traceln("method: " + methodName); - int descriptorIndex = c.copyU2(); // descriptor - checkIndex(descriptorIndex, "Method descriptor"); - int attrCount = c.copyU2(); // attribute count - if (verbose) { - System.out.println("method attr count: " + attrCount); - } - for (int i = 0; i < attrCount; ++i) { - copyAttrForMethod(methodName, accessFlags); - } - } - - void copyAttrs(int attrCount) { - for (int i = 0; i < attrCount; ++i) { - copyAttr(); - } - } - - void copyAttr() { - c.copy(2); // name - int len = c.copyU4(); // attr len - if (verbose) { - System.out.println("attr len: " + len); - } - c.copy(len); // attribute info - } - - void copyAttrForMethod(String methodName, int accessFlags) { - int nameIndex = c.copyU2(); // name - // check for Code attr - checkIndex(nameIndex, "Method attr name"); - if (nameIndex == c.codeAttributeIndex) { - try { - copyCodeAttr(methodName); - } catch (IOException exc) { - System.err.println("Code Exception - " + exc); - System.exit(1); - } - } else { - int len = c.copyU4(); // attr len - traceln("method attr len: " + len); - c.copy(len); // attribute info - } - } - - void copyAttrForCode() throws IOException { - int nameIndex = c.copyU2(); // name - - checkIndex(nameIndex, "Code attr name"); - int len = c.copyU4(); // attr len - traceln("code attr len: " + len); - c.copy(len); // attribute info - } - - void copyCodeAttr(String methodName) throws IOException { - traceln("Code attr found"); - int attrLength = c.copyU4(); // attr len - checkLength(attrLength, "Code attr length"); - int maxStack = c.readU2(); // max stack - c.copyU2(); // max locals - int codeLength = c.copyU4(); // code length - checkLength(codeLength, "Code length"); - - copyExceptionTable(); - - int attrCount = c.copyU2(); - checkLength(attrCount, "Code attr count"); - for (int i = 0; i < attrCount; ++i) { - copyAttrForCode(); - } - } - - /** - * Copy the exception table for this method code - */ - void copyExceptionTable() throws IOException { - int tableLength = c.copyU2(); // exception table len - checkLength(tableLength, "Exception Table length"); - if (tableLength > 0) { - traceln(); - traceln("Exception table:"); - traceln(" from:old/new to:old/new target:old/new type"); - for (int tcnt = tableLength; tcnt > 0; --tcnt) { - int startPC = c.readU2(); - int endPC = c.readU2(); - int handlerPC = c.readU2(); - int catchType = c.copyU2(); - if (verbose) { - traceFixedWidthInt(startPC, 6); - traceFixedWidthInt(endPC, 6); - traceFixedWidthInt(handlerPC, 6); - trace(" "); - if (catchType == 0) - traceln("any"); - else { - traceln("" + catchType); - } - } - } - } - } - - private void checkIndex(int index, String comment) { - if (index > constantPoolCount) { - output.println("ERROR BAD INDEX " + comment + " : " + index); - } else { - traceln(comment + " : " + index); - } - } - - private void checkLength(int length, String comment) { - if (length > c.inputBytes().length) { - output.println("ERROR BAD LENGTH " + comment + " : " + length); - } else { - traceln(comment + " : " + length); - } - } - - private void trace(String str) { - if (verbose) { - output.print(str); - } - } - - private void traceln(String str) { - if (verbose) { - output.println(str); - } - } - - private void traceln() { - if (verbose) { - output.println(); - } - } - - private void trace(int i) { - if (verbose) { - output.print(i); - } - } - - /** - * Print an integer so that it takes 'length' characters in - * the output. Temporary until formatting code is stable. - */ - private void traceFixedWidthInt(int x, int length) { - if (verbose) { - CharArrayWriter baStream = new CharArrayWriter(); - PrintWriter pStream = new PrintWriter(baStream); - pStream.print(x); - String str = baStream.toString(); - for (int cnt = length - str.length(); cnt > 0; --cnt) - trace(" "); - trace(str); - } - } - - -} diff --git a/jdk/test/java/lang/instrument/ilib/ClassReaderWriter.java b/jdk/test/java/lang/instrument/ilib/ClassReaderWriter.java deleted file mode 100644 index 6d9ed4d507a..00000000000 --- a/jdk/test/java/lang/instrument/ilib/ClassReaderWriter.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package ilib; - -class ClassReaderWriter implements RuntimeConstants { - - int codeAttributeIndex; - int lineNumberAttributeIndex; - int localVarAttributeIndex; - - private final byte[] orig; - private final byte[] gen; - private final int sectionLength; - - private static final int GROWTH_FACTOR = 2; - private static final int SECTIONS = 2; - private static final String codeAttributeName = "Code"; - private static final String lineNumberAttributeName = "LineNumberTable"; - private static final String localVarAttributeName = "LocalVariableTable"; - - private int[] genSectionPos = new int[SECTIONS]; - - private int inputPos = 0; - private int genPos = 0; - private int markPos = 0; - private int currentSection = 0; - - private String[] constantPool; - - ClassReaderWriter(byte[] orig) { - this.orig = orig; - sectionLength = orig.length * GROWTH_FACTOR; - gen = new byte[sectionLength * SECTIONS]; - for (int section = 0; section < SECTIONS; ++section) { - genSectionPos[section] = section * sectionLength; - } - } - - int setSection(int section) { - int prevSection = currentSection; - genSectionPos[prevSection] = genPos; - genPos = genSectionPos[section]; - currentSection = section; - return prevSection; - } - - byte[] result() { - int section; - int totalLength = 0; - - setSection(0); // save current section - - for (section = 0; section < SECTIONS; ++section) { - int sectionStart = section * sectionLength; - int sectionGenLength = genSectionPos[section] - sectionStart; - totalLength += sectionGenLength; - } - - byte[] newcf = new byte[totalLength]; - int written = 0; - for (section = 0; section < SECTIONS; ++section) { - int sectionStart = section * sectionLength; - int sectionGenLength = genSectionPos[section] - sectionStart; - System.arraycopy(gen, sectionStart, newcf, written, sectionGenLength); - written += sectionGenLength; - } - - return newcf; - } - - int readU1() { - return ((int)orig[inputPos++]) & 0xFF; - } - - int readU2() { - int res = readU1(); - return (res << 8) + readU1(); - } - - short readS2() { - int res = readU1(); - return (short)((res << 8) + readU1()); - } - - int readU4() { - int res = readU2(); - return (res << 16) + readU2(); - } - - void writeU1(int val) { - gen[genPos++] = (byte)val; - } - - void writeU2(int val) { - writeU1(val >> 8); - writeU1(val & 0xFF); - } - - void writeU4(int val) { - writeU2(val >> 16); - writeU2(val & 0xFFFF); - } - - int copyU1() { - int value = readU1(); - writeU1(value); - return value; - } - - int copyU2() { - int value = readU2(); - writeU2(value); - return value; - } - - int copyU4() { - int value = readU4(); - writeU4(value); - return value; - } - - void copy(int count) { - for (int i = 0; i < count; ++i) { - gen[genPos++] = orig[inputPos++]; - } - } - - void skip(int count) { - inputPos += count; - } - - byte[] readBytes(int count) { - byte[] bytes = new byte[count]; - for (int i = 0; i < count; ++i) { - bytes[i] = orig[inputPos++]; - } - return bytes; - } - - void writeBytes(byte[] bytes) { - for (int i = 0; i < bytes.length; ++i) { - gen[genPos++] = bytes[i]; - } - } - - byte[] inputBytes() { - return orig; - } - - int inputPosition() { - return inputPos; - } - - void setInputPosition(int pos) { - inputPos = pos; - } - - void markLocalPositionStart() { - markPos = inputPos; - } - - int localPosition() { - return inputPos - markPos; - } - - void rewind() { - setInputPosition(markPos); - } - - int generatedPosition() { - return genPos; - } - - void randomAccessWriteU2(int pos, int val) { - int savePos = genPos; - genPos = pos; - writeU2(val); - genPos = savePos; - } - - void randomAccessWriteU4(int pos, int val) { - int savePos = genPos; - genPos = pos; - writeU4(val); - genPos = savePos; - } - - String constantPoolString(int index) { - return constantPool[index]; - } - - void copyConstantPool(int constantPoolCount){ - // copy const pool - constantPool = new String[constantPoolCount]; - // index zero not in class file - for (int i = 1; i < constantPoolCount; ++i) { - int tag = readU1(); - writeU1(tag); - switch (tag) { - case CONSTANT_CLASS: - case CONSTANT_STRING: - copy(2); - break; - case CONSTANT_FIELD: - case CONSTANT_METHOD: - case CONSTANT_INTERFACEMETHOD: - case CONSTANT_INTEGER: - case CONSTANT_FLOAT: - case CONSTANT_NAMEANDTYPE: - copy(4); - break; - case CONSTANT_LONG: - case CONSTANT_DOUBLE: - copy(8); - ++i; // these take two CP entries - duh! - break; - case CONSTANT_UTF8: - int len = copyU2(); - byte[] utf8 = readBytes(len); - String str = null; // null to shut the compiler up - try { - str = new String(utf8, "UTF-8"); - } catch (Exception exc) { - throw new Error("CP exception: " + exc); - } - constantPool[i] = str; - if (str.equals(codeAttributeName)) { - codeAttributeIndex = i; - } else if (str.equals(lineNumberAttributeName)) { - lineNumberAttributeIndex = i; - } else if (str.equals(localVarAttributeName)) { - localVarAttributeIndex = i; - } - writeBytes(utf8); - break; - default: - throw new Error(i + " unexpected CP tag: " + tag); - } - } - } - -} diff --git a/jdk/test/java/lang/instrument/ilib/Info.java b/jdk/test/java/lang/instrument/ilib/Info.java deleted file mode 100644 index ea0bbb5d567..00000000000 --- a/jdk/test/java/lang/instrument/ilib/Info.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package ilib; - -public class Info { - final int counter; - final String className; - final String methodName; - final int location; - - Info(int counter, String className, String methodName, int location) { - this.counter = counter; - this.className = className; - this.methodName = methodName; - this.location = location; - } -} diff --git a/jdk/test/java/lang/instrument/ilib/Inject.java b/jdk/test/java/lang/instrument/ilib/Inject.java deleted file mode 100644 index 22acbc9324b..00000000000 --- a/jdk/test/java/lang/instrument/ilib/Inject.java +++ /dev/null @@ -1,746 +0,0 @@ -/* - * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package ilib; - -import java.io.IOException; -import java.io.File; -import java.io.FileOutputStream; -import java.io.DataOutputStream; -import java.util.List; -import java.util.Iterator; -import java.util.ArrayList; - -public class Inject implements RuntimeConstants { - - public static byte[] instrumentation(Options opt, - ClassLoader loader, - String className, - byte[] classfileBuffer) { - ClassReaderWriter c = new ClassReaderWriter(classfileBuffer); - (new Inject(className, c, loader == null, opt)).doit(); - return c.result(); - } - - static boolean verbose = false; - - final String className; - final ClassReaderWriter c; - final boolean isSystem; - final Options options; - - int constantPoolCount; - int methodsCount; - int methodsCountPos; - int profiler; - int wrappedTrackerIndex = 0; - int thisClassIndex = 0; - - TrackerInjector callInjector; - TrackerInjector allocInjector; - TrackerInjector defaultInjector; - - static interface TrackerInjector extends Injector { - void reinit(int tracker); - int stackSize(int currentSize); - } - - static class SimpleInjector implements TrackerInjector { - byte[] injection; - - public int stackSize(int currentSize) { - return currentSize; - } - - public void reinit(int tracker) { - injection = new byte[3]; - injection[0] = (byte)opc_invokestatic; - injection[1] = (byte)(tracker >> 8); - injection[2] = (byte)tracker; - } - - public byte[] bytecodes(String className, String methodName, int location) { - return injection; - } - } - - static class ObjectInjector implements TrackerInjector { - byte[] injection; - - public int stackSize(int currentSize) { - return currentSize + 1; - } - - public void reinit(int tracker) { - injection = new byte[4]; - injection[0] = (byte)opc_dup; - injection[1] = (byte)opc_invokestatic; - injection[2] = (byte)(tracker >> 8); - injection[3] = (byte)tracker; - } - - public byte[] bytecodes(String className, String methodName, int location) { - return injection; - } - } - - class IndexedInjector implements TrackerInjector { - int counter = 0; - int tracker; - List infoList = new ArrayList<>(); - - public int stackSize(int currentSize) { - return currentSize + 1; - } - - public void reinit(int tracker) { - this.tracker = tracker; - } - - void dump(File outDir, String filename) throws IOException { - try (FileOutputStream fileOut = - new FileOutputStream(new File(outDir, filename)); - DataOutputStream dataOut = new DataOutputStream(fileOut)) - { - String currentClassName = null; - - dataOut.writeInt(infoList.size()); - for (Iterator it = infoList.iterator(); it.hasNext(); ) { - Info info = it.next(); - if (!info.className.equals(currentClassName)) { - dataOut.writeInt(123456); // class name marker - currentClassName = info.className; - dataOut.writeUTF(currentClassName); - } - dataOut.writeInt(info.location); - dataOut.writeUTF(info.methodName); - } - } - } - - public byte[] bytecodes(String className, String methodName, int location) { - byte[] injection = new byte[6]; - int injectedIndex = options.fixedIndex != 0? options.fixedIndex : ++counter; - infoList.add(new Info(counter, className, methodName, location)); - injection[0] = (byte)opc_sipush; - injection[1] = (byte)(injectedIndex >> 8); - injection[2] = (byte)injectedIndex; - injection[3] = (byte)opc_invokestatic; - injection[4] = (byte)(tracker >> 8); - injection[5] = (byte)tracker; - return injection; - } - } - - Inject(String className, ClassReaderWriter c, boolean isSystem, Options options) { - this.className = className; - this.c = c; - this.isSystem = isSystem; - this.options = options; - } - - void doit() { - int i; - c.copy(4 + 2 + 2); // magic min/maj version - int constantPoolCountPos = c.generatedPosition(); - constantPoolCount = c.copyU2(); - // copy old constant pool - c.copyConstantPool(constantPoolCount); - - if (verbose) { - System.out.println("ConstantPool expanded from: " + - constantPoolCount); - } - - profiler = addClassToConstantPool(options.trackerClassName); - if (options.shouldInstrumentNew || options.shouldInstrumentObjectInit) { - if (options.shouldInstrumentIndexed) { - if (allocInjector == null) { - // first time - create it - allocInjector = new IndexedInjector(); - } - int allocTracker = addMethodToConstantPool(profiler, - options.allocTrackerMethodName, - "(I)V"); - allocInjector.reinit(allocTracker); - } else if (options.shouldInstrumentObject) { - if (allocInjector == null) { - // first time - create it - allocInjector = new ObjectInjector(); - } - int allocTracker = addMethodToConstantPool(profiler, - options.allocTrackerMethodName, - "(Ljava/lang/Object;)V"); - allocInjector.reinit(allocTracker); - } else { - if (allocInjector == null) { - // first time - create it - allocInjector = new SimpleInjector(); - } - int allocTracker = addMethodToConstantPool(profiler, - options.allocTrackerMethodName, - "()V"); - allocInjector.reinit(allocTracker); - } - defaultInjector = allocInjector; - } - if (options.shouldInstrumentCall) { - if (options.shouldInstrumentIndexed) { - if (callInjector == null) { - // first time - create it - callInjector = new IndexedInjector(); - } - int callTracker = addMethodToConstantPool(profiler, - options.callTrackerMethodName, - "(I)V"); - callInjector.reinit(callTracker); - } else { - if (callInjector == null) { - // first time - create it - callInjector = new SimpleInjector(); - } - int callTracker = addMethodToConstantPool(profiler, - options.callTrackerMethodName, - "()V"); - callInjector.reinit(callTracker); - } - defaultInjector = callInjector; - } - - if (verbose) { - System.out.println("To: " + constantPoolCount); - } - - c.setSection(1); - - c.copy(2 + 2 + 2); // access, this, super - int interfaceCount = c.copyU2(); - if (verbose) { - System.out.println("interfaceCount: " + interfaceCount); - } - c.copy(interfaceCount * 2); - copyFields(); // fields - copyMethods(); // methods - int attrCountPos = c.generatedPosition(); - int attrCount = c.copyU2(); - if (verbose) { - System.out.println("class attrCount: " + attrCount); - } - // copy the class attributes - copyAttrs(attrCount); - - c.randomAccessWriteU2(constantPoolCountPos, constantPoolCount); - } - - - void copyFields() { - int count = c.copyU2(); - if (verbose) { - System.out.println("fields count: " + count); - } - for (int i = 0; i < count; ++i) { - c.copy(6); // access, name, descriptor - int attrCount = c.copyU2(); - if (verbose) { - System.out.println("field attr count: " + attrCount); - } - copyAttrs(attrCount); - } - } - - void copyMethods() { - methodsCountPos = c.generatedPosition(); - methodsCount = c.copyU2(); - int initialMethodsCount = methodsCount; - if (verbose) { - System.out.println("methods count: " + methodsCount); - } - for (int i = 0; i < initialMethodsCount; ++i) { - copyMethod(); - } - } - - void copyMethod() { - int accessFlags = c.copyU2();// access flags - if (options.shouldInstrumentNativeMethods && (accessFlags & ACC_NATIVE) != 0) { - wrapNativeMethod(accessFlags); - return; - } - int nameIndex = c.copyU2(); // name - String methodName = c.constantPoolString(nameIndex); - c.copyU2(); // descriptor - int attrCount = c.copyU2(); // attribute count - if (verbose) { - System.out.println("methods attr count: " + attrCount); - } - for (int i = 0; i < attrCount; ++i) { - copyAttrForMethod(methodName, accessFlags); - } - } - - void wrapNativeMethod(int accessFlags) { - // first, copy the native method with the name changed - // accessFlags have already been copied - int nameIndex = c.readU2(); // name - String methodName = c.constantPoolString(nameIndex); - String wrappedMethodName = options.wrappedPrefix + methodName; - int wrappedNameIndex = writeCPEntryUtf8(wrappedMethodName); - c.writeU2(wrappedNameIndex); // change to the wrapped name - - int descriptorIndex = c.copyU2(); // descriptor index - - int attrCount = c.copyU2(); // attribute count - // need to replicate these attributes (esp Exceptions) in wrapper - // so mark this location so we can rewind - c.markLocalPositionStart(); - for (int i = 0; i < attrCount; ++i) { - copyAttrForMethod(methodName, accessFlags); - } - if (true) { - System.err.println(" wrapped: " + methodName); - } - - // now write the wrapper method - c.writeU2(accessFlags & ~ACC_NATIVE); - c.writeU2(nameIndex); // original unwrapped name - c.writeU2(descriptorIndex); // descriptor is the same - - c.writeU2(attrCount + 1); // wrapped plus a code attribute - // rewind to wrapped attributes - c.rewind(); - for (int i = 0; i < attrCount; ++i) { - copyAttrForMethod(methodName, accessFlags); - } - - // generate a Code attribute for the wrapper method - int wrappedIndex = addMethodToConstantPool(getThisClassIndex(), - wrappedNameIndex, - descriptorIndex); - String descriptor = c.constantPoolString(descriptorIndex); - createWrapperCodeAttr(nameIndex, accessFlags, descriptor, wrappedIndex); - - // increment method count - c.randomAccessWriteU2(methodsCountPos, ++methodsCount); - } - - void copyAttrs(int attrCount) { - for (int i = 0; i < attrCount; ++i) { - copyAttr(); - } - } - - void copyAttr() { - c.copy(2); // name - int len = c.copyU4(); // attr len - if (verbose) { - System.out.println("attr len: " + len); - } - c.copy(len); // attribute info - } - - void copyAttrForMethod(String methodName, int accessFlags) { - int nameIndex = c.copyU2(); // name - // check for Code attr - if (nameIndex == c.codeAttributeIndex) { - try { - copyCodeAttr(methodName); - } catch (IOException exc) { - System.err.println("Code Exception - " + exc); - System.exit(1); - } - } else { - int len = c.copyU4(); // attr len - if (verbose) { - System.out.println("method attr len: " + len); - } - c.copy(len); // attribute info - } - } - - void copyAttrForCode(InjectBytecodes ib) throws IOException { - int nameIndex = c.copyU2(); // name - - // check for Code attr - if (nameIndex == c.lineNumberAttributeIndex) { - ib.copyLineNumberAttr(); - } else if (nameIndex == c.localVarAttributeIndex) { - ib.copyLocalVarAttr(); - } else { - int len = c.copyU4(); // attr len - if (verbose) { - System.out.println("code attr len: " + len); - } - c.copy(len); // attribute info - } - } - - void copyCodeAttr(String methodName) throws IOException { - if (verbose) { - System.out.println("Code attr found"); - } - int attrLengthPos = c.generatedPosition(); - int attrLength = c.copyU4(); // attr len - int maxStack = c.readU2(); // max stack - c.writeU2(defaultInjector == null? maxStack : - defaultInjector.stackSize(maxStack)); // big enough for injected code - c.copyU2(); // max locals - int codeLengthPos = c.generatedPosition(); - int codeLength = c.copyU4(); // code length - if (options.targetMethod != null && !options.targetMethod.equals(methodName)) { - c.copy(attrLength - 8); // copy remainder minus already copied - return; - } - if (isSystem) { - if (codeLength == 1 && methodName.equals("finalize")) { - if (verbose) { - System.out.println("empty system finalizer not instrumented"); - } - c.copy(attrLength - 8); // copy remainder minus already copied - return; - } - if (codeLength == 1 && methodName.equals("")) { - if (verbose) { - System.out.println("empty system constructor not instrumented"); - } - if (!options.shouldInstrumentObjectInit) { - c.copy(attrLength - 8); // copy remainder minus already copied - return; - } - } - if (methodName.equals("")) { - if (verbose) { - System.out.println("system class initializer not instrumented"); - } - c.copy(attrLength - 8); // copy remainder minus already copied - return; - } - } - if (options.shouldInstrumentObjectInit - && (!className.equals("java/lang/Object") - || !methodName.equals(""))) { - c.copy(attrLength - 8); // copy remainder minus already copied - return; - } - - InjectBytecodes ib = new InjectBytecodes(c, codeLength, className, methodName); - - if (options.shouldInstrumentNew) { - ib.injectAfter(opc_new, allocInjector); - ib.injectAfter(opc_newarray, allocInjector); - ib.injectAfter(opc_anewarray, allocInjector); - ib.injectAfter(opc_multianewarray, allocInjector); - } - if (options.shouldInstrumentCall) { - ib.inject(0, callInjector.bytecodes(className, methodName, 0)); - } - if (options.shouldInstrumentObjectInit) { - ib.inject(0, allocInjector.bytecodes(className, methodName, 0)); - } - - ib.adjustOffsets(); - - // fix up code length - int newCodeLength = c.generatedPosition() - (codeLengthPos + 4); - c.randomAccessWriteU4(codeLengthPos, newCodeLength); - if (verbose) { - System.out.println("code length old: " + codeLength + - ", new: " + newCodeLength); - } - - ib.copyExceptionTable(); - - int attrCount = c.copyU2(); - for (int i = 0; i < attrCount; ++i) { - copyAttrForCode(ib); - } - - // fix up attr length - int newAttrLength = c.generatedPosition() - (attrLengthPos + 4); - c.randomAccessWriteU4(attrLengthPos, newAttrLength); - if (verbose) { - System.out.println("attr length old: " + attrLength + - ", new: " + newAttrLength); - } - } - - int nextDescriptorIndex(String descriptor, int index) { - switch (descriptor.charAt(index)) { - case 'B': // byte - case 'C': // char - case 'I': // int - case 'S': // short - case 'Z': // boolean - case 'F': // float - case 'D': // double - case 'J': // long - return index + 1; - case 'L': // object - int i = index + 1; - while (descriptor.charAt(i) != ';') { - ++i; - } - return i + 1; - case '[': // array - return nextDescriptorIndex(descriptor, index + 1); - } - throw new InternalError("should not reach here"); - } - - int getWrappedTrackerIndex() { - if (wrappedTrackerIndex == 0) { - wrappedTrackerIndex = addMethodToConstantPool(profiler, - options.wrappedTrackerMethodName, - "(Ljava/lang/String;I)V"); - } - return wrappedTrackerIndex; - } - - int getThisClassIndex() { - if (thisClassIndex == 0) { - thisClassIndex = addClassToConstantPool(className); - } - return thisClassIndex; - } - - int computeMaxLocals(String descriptor, int accessFlags) { - int index = 1; - int slot = 0; - - if ((accessFlags & ACC_STATIC) == 0) { - ++slot; - } - char type; - while ((type = descriptor.charAt(index)) != ')') { - switch (type) { - case 'B': // byte - case 'C': // char - case 'I': // int - case 'S': // short - case 'Z': // boolean - case 'F': // float - case 'L': // object - case '[': // array - ++slot; - break; - case 'D': // double - case 'J': // long - slot += 2; - break; - } - index = nextDescriptorIndex(descriptor, index); - } - - return slot; - } - - - void createWrapperCodeAttr(int methodNameIndex, int accessFlags, - String descriptor, int wrappedIndex) { - int maxLocals = computeMaxLocals(descriptor, accessFlags); - - c.writeU2(c.codeAttributeIndex); // - int attrLengthPos = c.generatedPosition(); - c.writeU4(0); // attr len -- fix up below - c.writeU2(maxLocals + 4); // max stack - c.writeU2(maxLocals); // max locals - int codeLengthPos = c.generatedPosition(); - c.writeU4(0); // code length -- fix up below - - int methodStringIndex = writeCPEntryString(methodNameIndex); - - c.writeU1(opc_ldc_w); - c.writeU2(methodStringIndex); // send the method name - c.writeU1(opc_sipush); - c.writeU2(options.fixedIndex); - c.writeU1(opc_invokestatic); - c.writeU2(getWrappedTrackerIndex()); - - // set-up args - int index = 1; - int slot = 0; - if ((accessFlags & ACC_STATIC) == 0) { - c.writeU1(opc_aload_0); // this - ++slot; - } - char type; - while ((type = descriptor.charAt(index)) != ')') { - switch (type) { - case 'B': // byte - case 'C': // char - case 'I': // int - case 'S': // short - case 'Z': // boolean - c.writeU1(opc_iload); - c.writeU1(slot); - ++slot; - break; - case 'F': // float - c.writeU1(opc_fload); - c.writeU1(slot); - ++slot; - break; - case 'D': // double - c.writeU1(opc_dload); - c.writeU1(slot); - slot += 2; - break; - case 'J': // long - c.writeU1(opc_lload); - c.writeU1(slot); - slot += 2; - break; - case 'L': // object - case '[': // array - c.writeU1(opc_aload); - c.writeU1(slot); - ++slot; - break; - } - index = nextDescriptorIndex(descriptor, index); - } - - // call the wrapped version - if ((accessFlags & ACC_STATIC) == 0) { - c.writeU1(opc_invokevirtual); - } else { - c.writeU1(opc_invokestatic); - } - c.writeU2(wrappedIndex); - - // return correct type - switch (descriptor.charAt(index+1)) { - case 'B': // byte - case 'C': // char - case 'I': // int - case 'S': // short - case 'Z': // boolean - c.writeU1(opc_ireturn); - break; - case 'F': // float - c.writeU1(opc_freturn); - break; - case 'D': // double - c.writeU1(opc_dreturn); - break; - case 'J': // long - c.writeU1(opc_lreturn); - break; - case 'L': // object - case '[': // array - c.writeU1(opc_areturn); - break; - case 'V': // void - c.writeU1(opc_return); - break; - } - - // end of code - - // fix up code length - int newCodeLength = c.generatedPosition() - (codeLengthPos + 4); - c.randomAccessWriteU4(codeLengthPos, newCodeLength); - - c.writeU2(0); // exception table length - c.writeU2(0); // attribute count - - // fix up attr length - int newAttrLength = c.generatedPosition() - (attrLengthPos + 4); - c.randomAccessWriteU4(attrLengthPos, newAttrLength); - } - - - int addClassToConstantPool(String className) { - int prevSection = c.setSection(0); - int classNameIndex = writeCPEntryUtf8(className); - int classIndex = writeCPEntryClass(classNameIndex); - c.setSection(prevSection); - return classIndex; - } - - int addMethodToConstantPool(int classIndex, - String methodName, - String descr) { - int prevSection = c.setSection(0); - int methodNameIndex = writeCPEntryUtf8(methodName); - int descrIndex = writeCPEntryUtf8(descr); - c.setSection(prevSection); - return addMethodToConstantPool(classIndex, methodNameIndex, descrIndex); - } - - int addMethodToConstantPool(int classIndex, - int methodNameIndex, - int descrIndex) { - int prevSection = c.setSection(0); - int nameAndTypeIndex = writeCPEntryNameAndType(methodNameIndex, - descrIndex); - int methodIndex = writeCPEntryMethodRef(classIndex, nameAndTypeIndex); - c.setSection(prevSection); - return methodIndex; - } - - int writeCPEntryUtf8(String str) { - int prevSection = c.setSection(0); - int len = str.length(); - c.writeU1(CONSTANT_UTF8); // Utf8 tag - c.writeU2(len); - for (int i = 0; i < len; ++i) { - c.writeU1(str.charAt(i)); - } - c.setSection(prevSection); - return constantPoolCount++; - } - - int writeCPEntryString(int utf8Index) { - int prevSection = c.setSection(0); - c.writeU1(CONSTANT_STRING); - c.writeU2(utf8Index); - c.setSection(prevSection); - return constantPoolCount++; - } - - int writeCPEntryClass(int classNameIndex) { - int prevSection = c.setSection(0); - c.writeU1(CONSTANT_CLASS); - c.writeU2(classNameIndex); - c.setSection(prevSection); - return constantPoolCount++; - } - - int writeCPEntryNameAndType(int nameIndex, int descrIndex) { - int prevSection = c.setSection(0); - c.writeU1(CONSTANT_NAMEANDTYPE); - c.writeU2(nameIndex); - c.writeU2(descrIndex); - c.setSection(prevSection); - return constantPoolCount++; - } - - int writeCPEntryMethodRef(int classIndex, int nameAndTypeIndex) { - int prevSection = c.setSection(0); - c.writeU1(CONSTANT_METHOD); - c.writeU2(classIndex); - c.writeU2(nameAndTypeIndex); - c.setSection(prevSection); - return constantPoolCount++; - } -} diff --git a/jdk/test/java/lang/instrument/ilib/InjectBytecodes.java b/jdk/test/java/lang/instrument/ilib/InjectBytecodes.java deleted file mode 100644 index 53e6a2feaea..00000000000 --- a/jdk/test/java/lang/instrument/ilib/InjectBytecodes.java +++ /dev/null @@ -1,769 +0,0 @@ -/* - * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * An extension of BinaryCode that allows code to be printed. - * Includes printing of disassembled byte codes, exception info, - * local variable and line number info. - * - */ - -package ilib; - -import java.io.ByteArrayInputStream; -import java.io.CharArrayWriter; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.PrintStream; -import java.util.Map; -import java.util.HashMap; - -class InjectBytecodes implements RuntimeConstants { - - private final ClassReaderWriter c; - private final PrintStream output; - private final int length; - private final int[] map; - private final byte[] widening; - private final Injector[] before = new Injector[256]; - private final Injector[] after = new Injector[256]; - private final String className; - private final String methodName; - private final Map snippets = new HashMap<>(); - - private int pos; - private int newPos; - - private class Span { - final int delta; - final int target; - final int newDelta; - final int newTarget; - - Span(int delta) { - this.delta = delta; - this.target = pos + delta; - this.newTarget = map[target]; - this.newDelta = newTarget - newPos; - } - } - - /** - * Constructor - */ - InjectBytecodes(ClassReaderWriter c, int length, - String className, String methodName) { - this.c = c; - this.output = System.out; - this.length = length; - this.map = new int[length + 1]; - this.widening = new byte[length + 1]; - this.className = className; - this.methodName = methodName; - c.markLocalPositionStart(); - for (int i = 0; i <= length; ++i) { - map[i] = i; - } - } - - public void inject(int at, byte[] newCode) { - snippets.put(new Integer(at), newCode); - trace("external "); - inject(at, newCode.length); - } - - private void inject(int at, int len) { - if (Inject.verbose) { - traceln("Injecting " + len + " at " + at); - } - for (int i = at; i <= length; ++i) { - map[i] += len; - } - } - - private void widen(int at, int len) { - int delta = len - widening[at]; - if (Inject.verbose) { - traceln(); - traceln("Widening to " + len + " at " + at); - } - inject(c.localPosition(), delta); // inject at end of instruction - widening[at] = (byte)len; // mark at beginning of instruction - } - - public void injectBefore(int code, Injector inj) { - before[code] = inj; - } - - public void injectAfter(int code, Injector inj) { - after[code] = inj; - } - - private void trace(String str) { - if (Inject.verbose) { - output.print(str); - } - } - - private void traceln(String str) { - if (Inject.verbose) { - output.println(str); - } - } - - private void traceln() { - if (Inject.verbose) { - output.println(); - } - } - - private void trace(int i) { - if (Inject.verbose) { - output.print(i); - } - } - - /** - * Print an integer so that it takes 'length' characters in - * the output. Temporary until formatting code is stable. - */ - private void traceFixedWidthInt(int x, int length) { - if (Inject.verbose) { - CharArrayWriter baStream = new CharArrayWriter(); - PrintWriter pStream = new PrintWriter(baStream); - pStream.print(x); - String str = baStream.toString(); - for (int cnt = length - str.length(); cnt > 0; --cnt) - trace(" "); - trace(str); - } - } - - void adjustOffsets() throws IOException { - if (Inject.verbose) { - traceln(); - traceln("Method " + methodName); - traceln(); - } - c.rewind(); - while (c.localPosition() < length) { - insertAtInstruction(); - } - trace("Searching for adjustments..."); - c.rewind(); - while (c.localPosition() < length) { - if (!adjustInstruction()) { - c.rewind(); - traceln(); - traceln("Restarting adjustments after change..."); - } - } - // write the new bytecodes - traceln(); - traceln(); - trace("Writing new code..."); - c.rewind(); - while (c.localPosition() < length) { - writeInstruction(); - } - if (!snippets.isEmpty()) { - throw new Error("not all snippets written"); - } - } - - /** - * Walk one instruction inserting instrumentation at specified instructions - */ - private void insertAtInstruction() throws IOException { - pos = c.localPosition(); - int opcode = c.readU1(); - if (opcode == opc_wide) { - // no support for instrumenting wide instructions - int wopcode = c.readU1(); - int lvIndex = c.readU2(); - switch (wopcode) { - case opc_aload: case opc_astore: - case opc_fload: case opc_fstore: - case opc_iload: case opc_istore: - case opc_lload: case opc_lstore: - case opc_dload: case opc_dstore: - case opc_ret: - break; - - case opc_iinc: - c.readS2(); - break; - default: - throw new Error("Invalid wide opcode: " + wopcode); - } - } else { - Injector inj; - - inj = before[opcode]; - if (inj != null) { - inject(pos, inj.bytecodes(className, methodName, pos)); - } - - switch (opcode) { - case opc_tableswitch:{ - int header = (pos+1+3) & (~3); // 4byte boundry - c.skip(header - (pos+1)); // skip old padding - - c.readU4(); - int low = c.readU4(); - int high = c.readU4(); - c.skip((high+1-low) * 4); - break; - } - - case opc_lookupswitch:{ - int header = (pos+1+3) & (~3); // 4byte boundry - c.skip(header - (pos+1)); // skip padding - - c.readU4(); - int npairs = c.readU4(); - c.skip(npairs * 8); - break; - } - - default: { - int instrLen = opcLengths[opcode]; - c.skip(instrLen-1); - } - } - inj = after[opcode]; - if (inj != null) { - pos = c.localPosition(); - inject(pos, inj.bytecodes(className, methodName, pos)); - } - } - } - - /** - * Walk one instruction adjusting for insertions - */ - private boolean adjustInstruction() throws IOException { - pos = c.localPosition(); - newPos = map[pos]; - int opcode = c.readU1(); - if (Inject.verbose) { - traceln(); - traceFixedWidthInt(pos, 4); - traceFixedWidthInt(newPos, 4); - trace(" "); - } - if (opcode == opc_wide) { - int wopcode = c.readU1(); - int lvIndex = c.readU2(); - if (Inject.verbose) { - trace(opcNames[wopcode] + "_w "); - } - switch (wopcode) { - case opc_aload: case opc_astore: - case opc_fload: case opc_fstore: - case opc_iload: case opc_istore: - case opc_lload: case opc_lstore: - case opc_dload: case opc_dstore: - case opc_ret: - trace(lvIndex); - break; - - case opc_iinc: - int constVal = c.readS2(); - if (Inject.verbose) { - trace(lvIndex + " " + constVal); - } - break; - default: - throw new Error("Invalid wide opcode: " + wopcode); - } - } else { - if (Inject.verbose) { - trace(opcNames[opcode]); - } - switch (opcode) { - - case opc_tableswitch:{ - int widened = widening[pos]; - int header = (pos+1+3) & (~3); // 4byte boundry - int newHeader = (newPos+1+3) & (~3); // 4byte boundry - - c.skip(header - (pos+1)); // skip old padding - - Span defaultSkip = new Span(c.readU4()); - int low = c.readU4(); - int high = c.readU4(); - if (Inject.verbose) { - trace(" " + low + " to " + high); - trace(": default= [was] " + defaultSkip.target); - trace(" [now] " + defaultSkip.newTarget); - for (int i = low; i <= high; ++i) { - Span jump = new Span(c.readU4()); - traceln(""); - trace('\t'); - traceFixedWidthInt(i, 5); - trace(": " + jump.newTarget); - } - } else { - c.skip((high+1-low) * 4); - } - int newPadding = newHeader - newPos; - int oldPadding = header - pos; - int deltaPadding = newPadding - oldPadding; - if (widened != deltaPadding) { - widen(pos, deltaPadding); - return false; // cause restart - } - break; - } - - case opc_lookupswitch:{ - int widened = widening[pos]; - int header = (pos+1+3) & (~3); // 4byte boundry - int newHeader = (newPos+1+3) & (~3); // 4byte boundry - - c.skip(header - (pos+1)); // skip old padding - - Span defaultSkip = new Span(c.readU4()); - int npairs = c.readU4(); - if (Inject.verbose) { - trace(" npairs: " + npairs); - trace(": default= [was] " + defaultSkip.target); - trace(" [now] " + defaultSkip.newTarget); - for (int i = 0; i< npairs; ++i) { - int match = c.readU4(); - Span jump = new Span(c.readU4()); - traceln(""); - trace('\t'); - traceFixedWidthInt(match, 5); - trace(": " + jump.newTarget); - } - } else { - c.skip(npairs * 8); - } - int newPadding = newHeader - newPos; - int oldPadding = header - pos; - int deltaPadding = newPadding - oldPadding; - if (widened != deltaPadding) { - widen(pos, deltaPadding); - return false; // cause restart - } - break; - } - - case opc_jsr: case opc_goto: - case opc_ifeq: case opc_ifge: case opc_ifgt: - case opc_ifle: case opc_iflt: case opc_ifne: - case opc_if_icmpeq: case opc_if_icmpne: case opc_if_icmpge: - case opc_if_icmpgt: case opc_if_icmple: case opc_if_icmplt: - case opc_if_acmpeq: case opc_if_acmpne: - case opc_ifnull: case opc_ifnonnull: { - int widened = widening[pos]; - Span jump = new Span(c.readS2()); - if (widened == 0) { // not yet widened - int newDelta = jump.newDelta; - if ((newDelta < -32768) || (newDelta > 32767)) { - switch (opcode) { - case opc_jsr: case opc_goto: - widen(pos, 2); // will convert to wide - break; - default: - widen(pos, 5); // will inject goto_w - break; - } - return false; // cause restart - } - } - if (Inject.verbose) { - trace(" [was] " + jump.target + " ==> " + - " [now] " + jump.newTarget); - } - break; - } - - case opc_jsr_w: - case opc_goto_w: { - Span jump = new Span(c.readU4()); - if (Inject.verbose) { - trace(" [was] " + jump.target + - " [now] " + jump.newTarget); - } - break; - } - - default: { - int instrLen = opcLengths[opcode]; - c.skip(instrLen-1); - break; - } - } - } - return true; // successful return - } - - - /** - * Walk one instruction writing the transformed instruction. - */ - private void writeInstruction() throws IOException { - pos = c.localPosition(); - newPos = map[pos]; - byte[] newCode = snippets.remove(new Integer(pos)); - if (newCode != null) { - traceln(); - traceFixedWidthInt(pos, 4); - trace(" ... -- Inserting new code"); - c.writeBytes(newCode); - } - int opcode = c.readU1(); - if (Inject.verbose) { - traceln(); - traceFixedWidthInt(pos, 4); - traceFixedWidthInt(newPos, 4); - trace(" "); - } - if (opcode == opc_wide) { - int wopcode = c.readU1(); - int lvIndex = c.readU2(); - if (Inject.verbose) { - trace(opcNames[wopcode] + "_w "); - } - c.writeU1(opcode); - c.writeU1(wopcode); - c.writeU2(lvIndex); - switch (wopcode) { - case opc_aload: case opc_astore: - case opc_fload: case opc_fstore: - case opc_iload: case opc_istore: - case opc_lload: case opc_lstore: - case opc_dload: case opc_dstore: - case opc_ret: - trace(lvIndex); - break; - - case opc_iinc: - int constVal = c.readS2(); - c.writeU2(constVal); // ??? U vs S - if (Inject.verbose) { - trace(lvIndex + " " + constVal); - } - break; - default: - throw new Error("Invalid wide opcode: " + wopcode); - } - } else { - if (Inject.verbose) { - trace(opcNames[opcode]); - } - switch (opcode) { - - case opc_tableswitch:{ - int header = (pos+1+3) & (~3); // 4byte boundry - int newHeader = (newPos+1+3) & (~3); // 4byte boundry - - c.skip(header - (pos+1)); // skip old padding - - Span defaultSkip = new Span(c.readU4()); - int low = c.readU4(); - int high = c.readU4(); - - c.writeU1(opcode); // copy instruction - for (int i = newPos+1; i < newHeader; ++i) { - c.writeU1(0); // write new padding - } - c.writeU4(defaultSkip.newDelta); - c.writeU4(low); - c.writeU4(high); - - if (Inject.verbose) { - trace(" " + low + " to " + high); - trace(": default= [was] " + defaultSkip.target); - trace(" [now] " + defaultSkip.newTarget); - } - for (int i = low; i <= high; ++i) { - Span jump = new Span(c.readU4()); - c.writeU4(jump.newDelta); - if (Inject.verbose) { - traceln(""); - trace('\t'); - traceFixedWidthInt(i, 5); - trace(": " + jump.newTarget); - } - } - break; - } - - case opc_lookupswitch:{ - int header = (pos+1+3) & (~3); // 4byte boundry - int newHeader = (newPos+1+3) & (~3); // 4byte boundry - - c.skip(header - (pos+1)); // skip old padding - - Span defaultSkip = new Span(c.readU4()); - int npairs = c.readU4(); - if (Inject.verbose) { - trace(" npairs: " + npairs); - trace(": default= [was] " + defaultSkip.target); - trace(" [now] " + defaultSkip.newTarget); - } - c.writeU1(opcode); // copy instruction - for (int i = newPos+1; i < newHeader; ++i) { - c.writeU1(0); // write new padding - } - c.writeU4(defaultSkip.newDelta); - c.writeU4(npairs); - for (int i = 0; i< npairs; ++i) { - int match = c.readU4(); - Span jump = new Span(c.readU4()); - c.writeU4(match); - c.writeU4(jump.newDelta); - if (Inject.verbose) { - traceln(""); - trace('\t'); - traceFixedWidthInt(match, 5); - trace(": " + jump.newTarget); - } - } - break; - } - - case opc_jsr: case opc_goto: - case opc_ifeq: case opc_ifge: case opc_ifgt: - case opc_ifle: case opc_iflt: case opc_ifne: - case opc_if_icmpeq: case opc_if_icmpne: case opc_if_icmpge: - case opc_if_icmpgt: case opc_if_icmple: case opc_if_icmplt: - case opc_if_acmpeq: case opc_if_acmpne: - case opc_ifnull: case opc_ifnonnull: { - int widened = widening[pos]; - Span jump = new Span(c.readS2()); - int newOpcode = opcode; // default to unchanged - if (widened == 0) { // not widened - c.writeU1(opcode); // rewrite instruction - c.writeU2(jump.newDelta); - } else if (widened == 2) { // wide form - switch (opcode) { - case opc_jsr: - newOpcode = opc_jsr_w; - break; - case opc_goto: - newOpcode = opc_jsr_w; - break; - default: - throw new Error("unexpected opcode: " + - opcode); - } - c.writeU1(newOpcode); // write wide instruction - c.writeU4(jump.newDelta); // write new and wide delta - } else if (widened == 5) { // insert goto_w - switch (opcode) { - case opc_ifeq: - newOpcode = opc_ifne; - break; - case opc_ifge: - newOpcode = opc_iflt; - break; - case opc_ifgt: - newOpcode = opc_ifle; - break; - case opc_ifle: - newOpcode = opc_ifgt; - break; - case opc_iflt: - newOpcode = opc_ifge; - break; - case opc_ifne: - newOpcode = opc_ifeq; - break; - case opc_if_icmpeq: - newOpcode = opc_if_icmpne; - break; - case opc_if_icmpne: - newOpcode = opc_if_icmpeq; - break; - case opc_if_icmpge: - newOpcode = opc_if_icmplt; - break; - case opc_if_icmpgt: - newOpcode = opc_if_icmple; - break; - case opc_if_icmple: - newOpcode = opc_if_icmpgt; - break; - case opc_if_icmplt: - newOpcode = opc_if_icmpge; - break; - case opc_if_acmpeq: - newOpcode = opc_if_acmpne; - break; - case opc_if_acmpne: - newOpcode = opc_if_acmpeq; - break; - case opc_ifnull: - newOpcode = opc_ifnonnull; - break; - case opc_ifnonnull: - newOpcode = opc_ifnull; - break; - default: - throw new Error("unexpected opcode: " + - opcode); - } - c.writeU1(newOpcode); // write inverse branch - c.writeU2(3 + 5); // beyond if and goto_w - c.writeU1(opc_goto_w);// add a goto_w - c.writeU4(jump.newDelta); // write new and wide delta - } else { - throw new Error("unexpected widening"); - } - - if (Inject.verbose) { - trace(" [was] " + jump.target + " ==> " + - opcNames[newOpcode] + - " [now] " + jump.newTarget); - } - break; - } - - case opc_jsr_w: - case opc_goto_w: { - Span jump = new Span(c.readU4()); - c.writeU1(opcode); // instruction itself - c.writeU4(jump.newDelta); - if (Inject.verbose) { - trace(" [was] " + jump.target + - " [now] " + jump.newTarget); - } - break; - } - - default: { - int instrLen = opcLengths[opcode]; - c.writeU1(opcode); // instruction itself - c.copy(instrLen-1); - } - } - } - } - - /** - * Copy the exception table for this method code - */ - void copyExceptionTable() throws IOException { - int tableLength = c.copyU2(); // exception table len - if (tableLength > 0) { - traceln(); - traceln("Exception table:"); - traceln(" from:old/new to:old/new target:old/new type"); - for (int tcnt = tableLength; tcnt > 0; --tcnt) { - int startPC = c.readU2(); - int newStartPC = map[startPC]; - c.writeU2(newStartPC); - int endPC = c.readU2(); - int newEndPC = map[endPC]; - c.writeU2(newEndPC); - int handlerPC = c.readU2(); - int newHandlerPC = map[handlerPC]; - c.writeU2(newHandlerPC); - int catchType = c.copyU2(); - if (Inject.verbose) { - traceFixedWidthInt(startPC, 6); - traceFixedWidthInt(newStartPC, 6); - traceFixedWidthInt(endPC, 6); - traceFixedWidthInt(newEndPC, 6); - traceFixedWidthInt(handlerPC, 6); - traceFixedWidthInt(newHandlerPC, 6); - trace(" "); - if (catchType == 0) - traceln("any"); - else { - traceln("" + catchType); - } - } - } - } - } - - /** - * Copy the line number table for this method code - */ - void copyLineNumberAttr() throws IOException { - // name index already read - c.copy(4); // attr len - int tableLength = c.copyU2(); // line table len - if (tableLength > 0) { - if (Inject.verbose) { - traceln(); - traceln("Line numbers for method " + methodName); - } - for (int tcnt = tableLength; tcnt > 0; --tcnt) { - int startPC = c.readU2(); - int newStartPC = map[startPC]; - c.writeU2(newStartPC); - int lineNumber = c.copyU2(); - if (Inject.verbose) { - traceln(" line " + lineNumber + - ": [was] " + startPC + - " [now] " + newStartPC); - } - } - } - } - - /** - * Copy the local variable table for this method code - */ - void copyLocalVarAttr() throws IOException { - // name index already read - c.copy(4); // attr len - int tableLength = c.copyU2(); // local var table len - if (tableLength > 0) { - if (Inject.verbose) { - traceln(); - traceln("Local variables for method " + methodName); - } - for (int tcnt = tableLength; tcnt > 0; --tcnt) { - int startPC = c.readU2(); - int newStartPC = map[startPC]; - c.writeU2(newStartPC); - int length = c.readU2(); - int endPC = startPC + length; - int newEndPC = map[endPC]; - int newLength = newEndPC - newStartPC; - c.writeU2(newLength); - int nameIndex = c.copyU2(); - int descriptorIndex = c.copyU2(); - int index = c.copyU2(); - if (Inject.verbose) { - trace(" "); - trace(descriptorIndex); - trace(" "); - trace(nameIndex); - traceln(" pc= [was] " + startPC + " [now] " + newStartPC + - ", length= [was] " + length + " [now] " + newLength + - ", slot=" + index); - } - } - } - } -} diff --git a/jdk/test/java/lang/instrument/ilib/Injector.java b/jdk/test/java/lang/instrument/ilib/Injector.java deleted file mode 100644 index 0a471eff3db..00000000000 --- a/jdk/test/java/lang/instrument/ilib/Injector.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package ilib; - -interface Injector { - byte[] bytecodes(String className, String methodName, int location); -} diff --git a/jdk/test/java/lang/instrument/ilib/Options.java b/jdk/test/java/lang/instrument/ilib/Options.java deleted file mode 100644 index 27c09288c8f..00000000000 --- a/jdk/test/java/lang/instrument/ilib/Options.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package ilib; - -public class Options { - public boolean shouldInstrumentNew = false; - public boolean shouldInstrumentCall = false; - public boolean shouldInstrumentIndexed = false; - public boolean shouldInstrumentObject = false; - public boolean shouldInstrumentObjectInit = false; - public boolean shouldInstrumentNativeMethods = false; - public String targetMethod = null; - public int fixedIndex = 0; - public String trackerClassName = "MyTracker"; - public String allocTrackerMethodName = "allocTracker"; - public String callTrackerMethodName = "callTracker"; - public String wrappedTrackerMethodName = "wrappedTracker"; - public String wrappedPrefix = "wrapped_up_"; -} diff --git a/jdk/test/java/lang/instrument/ilib/RuntimeConstants.java b/jdk/test/java/lang/instrument/ilib/RuntimeConstants.java deleted file mode 100644 index 01a746ec5ff..00000000000 --- a/jdk/test/java/lang/instrument/ilib/RuntimeConstants.java +++ /dev/null @@ -1,732 +0,0 @@ -/* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package ilib; - -public interface RuntimeConstants { - - /* Signature Characters */ - char SIGC_VOID = 'V'; - String SIG_VOID = "V"; - char SIGC_BOOLEAN = 'Z'; - String SIG_BOOLEAN = "Z"; - char SIGC_BYTE = 'B'; - String SIG_BYTE = "B"; - char SIGC_CHAR = 'C'; - String SIG_CHAR = "C"; - char SIGC_SHORT = 'S'; - String SIG_SHORT = "S"; - char SIGC_INT = 'I'; - String SIG_INT = "I"; - char SIGC_LONG = 'J'; - String SIG_LONG = "J"; - char SIGC_FLOAT = 'F'; - String SIG_FLOAT = "F"; - char SIGC_DOUBLE = 'D'; - String SIG_DOUBLE = "D"; - char SIGC_ARRAY = '['; - String SIG_ARRAY = "["; - char SIGC_CLASS = 'L'; - String SIG_CLASS = "L"; - char SIGC_METHOD = '('; - String SIG_METHOD = "("; - char SIGC_ENDCLASS = ';'; - String SIG_ENDCLASS = ";"; - char SIGC_ENDMETHOD = ')'; - String SIG_ENDMETHOD = ")"; - char SIGC_PACKAGE = '/'; - String SIG_PACKAGE = "/"; - - /* Class File Constants */ - int JAVA_MAGIC = 0xcafebabe; - int JAVA_MIN_SUPPORTED_VERSION = 45; - int JAVA_MAX_SUPPORTED_VERSION = 48; - int JAVA_MAX_SUPPORTED_MINOR_VERSION = 0; - - /* Generate class file version for 1.1 by default */ - int JAVA_DEFAULT_VERSION = 45; - int JAVA_DEFAULT_MINOR_VERSION = 3; - - /* Constant table */ - int CONSTANT_UTF8 = 1; - int CONSTANT_UNICODE = 2; - int CONSTANT_INTEGER = 3; - int CONSTANT_FLOAT = 4; - int CONSTANT_LONG = 5; - int CONSTANT_DOUBLE = 6; - int CONSTANT_CLASS = 7; - int CONSTANT_STRING = 8; - int CONSTANT_FIELD = 9; - int CONSTANT_METHOD = 10; - int CONSTANT_INTERFACEMETHOD = 11; - int CONSTANT_NAMEANDTYPE = 12; - - /* Access and modifier flags */ - int ACC_PUBLIC = 0x00000001; - int ACC_PRIVATE = 0x00000002; - int ACC_PROTECTED = 0x00000004; - int ACC_STATIC = 0x00000008; - int ACC_FINAL = 0x00000010; - int ACC_SYNCHRONIZED = 0x00000020; - int ACC_VOLATILE = 0x00000040; - int ACC_TRANSIENT = 0x00000080; - int ACC_NATIVE = 0x00000100; - int ACC_INTERFACE = 0x00000200; - int ACC_ABSTRACT = 0x00000400; - int ACC_SUPER = 0x00000020; - int ACC_STRICT = 0x00000800; - - /* Type codes */ - int T_CLASS = 0x00000002; - int T_BOOLEAN = 0x00000004; - int T_CHAR = 0x00000005; - int T_FLOAT = 0x00000006; - int T_DOUBLE = 0x00000007; - int T_BYTE = 0x00000008; - int T_SHORT = 0x00000009; - int T_INT = 0x0000000a; - int T_LONG = 0x0000000b; - - /* Opcodes */ - int opc_try = -3; - int opc_dead = -2; - int opc_label = -1; - int opc_nop = 0; - int opc_aconst_null = 1; - int opc_iconst_m1 = 2; - int opc_iconst_0 = 3; - int opc_iconst_1 = 4; - int opc_iconst_2 = 5; - int opc_iconst_3 = 6; - int opc_iconst_4 = 7; - int opc_iconst_5 = 8; - int opc_lconst_0 = 9; - int opc_lconst_1 = 10; - int opc_fconst_0 = 11; - int opc_fconst_1 = 12; - int opc_fconst_2 = 13; - int opc_dconst_0 = 14; - int opc_dconst_1 = 15; - int opc_bipush = 16; - int opc_sipush = 17; - int opc_ldc = 18; - int opc_ldc_w = 19; - int opc_ldc2_w = 20; - int opc_iload = 21; - int opc_lload = 22; - int opc_fload = 23; - int opc_dload = 24; - int opc_aload = 25; - int opc_iload_0 = 26; - int opc_iload_1 = 27; - int opc_iload_2 = 28; - int opc_iload_3 = 29; - int opc_lload_0 = 30; - int opc_lload_1 = 31; - int opc_lload_2 = 32; - int opc_lload_3 = 33; - int opc_fload_0 = 34; - int opc_fload_1 = 35; - int opc_fload_2 = 36; - int opc_fload_3 = 37; - int opc_dload_0 = 38; - int opc_dload_1 = 39; - int opc_dload_2 = 40; - int opc_dload_3 = 41; - int opc_aload_0 = 42; - int opc_aload_1 = 43; - int opc_aload_2 = 44; - int opc_aload_3 = 45; - int opc_iaload = 46; - int opc_laload = 47; - int opc_faload = 48; - int opc_daload = 49; - int opc_aaload = 50; - int opc_baload = 51; - int opc_caload = 52; - int opc_saload = 53; - int opc_istore = 54; - int opc_lstore = 55; - int opc_fstore = 56; - int opc_dstore = 57; - int opc_astore = 58; - int opc_istore_0 = 59; - int opc_istore_1 = 60; - int opc_istore_2 = 61; - int opc_istore_3 = 62; - int opc_lstore_0 = 63; - int opc_lstore_1 = 64; - int opc_lstore_2 = 65; - int opc_lstore_3 = 66; - int opc_fstore_0 = 67; - int opc_fstore_1 = 68; - int opc_fstore_2 = 69; - int opc_fstore_3 = 70; - int opc_dstore_0 = 71; - int opc_dstore_1 = 72; - int opc_dstore_2 = 73; - int opc_dstore_3 = 74; - int opc_astore_0 = 75; - int opc_astore_1 = 76; - int opc_astore_2 = 77; - int opc_astore_3 = 78; - int opc_iastore = 79; - int opc_lastore = 80; - int opc_fastore = 81; - int opc_dastore = 82; - int opc_aastore = 83; - int opc_bastore = 84; - int opc_castore = 85; - int opc_sastore = 86; - int opc_pop = 87; - int opc_pop2 = 88; - int opc_dup = 89; - int opc_dup_x1 = 90; - int opc_dup_x2 = 91; - int opc_dup2 = 92; - int opc_dup2_x1 = 93; - int opc_dup2_x2 = 94; - int opc_swap = 95; - int opc_iadd = 96; - int opc_ladd = 97; - int opc_fadd = 98; - int opc_dadd = 99; - int opc_isub = 100; - int opc_lsub = 101; - int opc_fsub = 102; - int opc_dsub = 103; - int opc_imul = 104; - int opc_lmul = 105; - int opc_fmul = 106; - int opc_dmul = 107; - int opc_idiv = 108; - int opc_ldiv = 109; - int opc_fdiv = 110; - int opc_ddiv = 111; - int opc_irem = 112; - int opc_lrem = 113; - int opc_frem = 114; - int opc_drem = 115; - int opc_ineg = 116; - int opc_lneg = 117; - int opc_fneg = 118; - int opc_dneg = 119; - int opc_ishl = 120; - int opc_lshl = 121; - int opc_ishr = 122; - int opc_lshr = 123; - int opc_iushr = 124; - int opc_lushr = 125; - int opc_iand = 126; - int opc_land = 127; - int opc_ior = 128; - int opc_lor = 129; - int opc_ixor = 130; - int opc_lxor = 131; - int opc_iinc = 132; - int opc_i2l = 133; - int opc_i2f = 134; - int opc_i2d = 135; - int opc_l2i = 136; - int opc_l2f = 137; - int opc_l2d = 138; - int opc_f2i = 139; - int opc_f2l = 140; - int opc_f2d = 141; - int opc_d2i = 142; - int opc_d2l = 143; - int opc_d2f = 144; - int opc_i2b = 145; - int opc_i2c = 146; - int opc_i2s = 147; - int opc_lcmp = 148; - int opc_fcmpl = 149; - int opc_fcmpg = 150; - int opc_dcmpl = 151; - int opc_dcmpg = 152; - int opc_ifeq = 153; - int opc_ifne = 154; - int opc_iflt = 155; - int opc_ifge = 156; - int opc_ifgt = 157; - int opc_ifle = 158; - int opc_if_icmpeq = 159; - int opc_if_icmpne = 160; - int opc_if_icmplt = 161; - int opc_if_icmpge = 162; - int opc_if_icmpgt = 163; - int opc_if_icmple = 164; - int opc_if_acmpeq = 165; - int opc_if_acmpne = 166; - int opc_goto = 167; - int opc_jsr = 168; - int opc_ret = 169; - int opc_tableswitch = 170; - int opc_lookupswitch = 171; - int opc_ireturn = 172; - int opc_lreturn = 173; - int opc_freturn = 174; - int opc_dreturn = 175; - int opc_areturn = 176; - int opc_return = 177; - int opc_getstatic = 178; - int opc_putstatic = 179; - int opc_getfield = 180; - int opc_putfield = 181; - int opc_invokevirtual = 182; - int opc_invokespecial = 183; - int opc_invokestatic = 184; - int opc_invokeinterface = 185; - int opc_xxxunusedxxx = 186; - int opc_new = 187; - int opc_newarray = 188; - int opc_anewarray = 189; - int opc_arraylength = 190; - int opc_athrow = 191; - int opc_checkcast = 192; - int opc_instanceof = 193; - int opc_monitorenter = 194; - int opc_monitorexit = 195; - int opc_wide = 196; - int opc_multianewarray = 197; - int opc_ifnull = 198; - int opc_ifnonnull = 199; - int opc_goto_w = 200; - int opc_jsr_w = 201; - int opc_breakpoint = 202; - - /* Opcode Names */ - String opcNames[] = { - "nop", - "aconst_null", - "iconst_m1", - "iconst_0", - "iconst_1", - "iconst_2", - "iconst_3", - "iconst_4", - "iconst_5", - "lconst_0", - "lconst_1", - "fconst_0", - "fconst_1", - "fconst_2", - "dconst_0", - "dconst_1", - "bipush", - "sipush", - "ldc", - "ldc_w", - "ldc2_w", - "iload", - "lload", - "fload", - "dload", - "aload", - "iload_0", - "iload_1", - "iload_2", - "iload_3", - "lload_0", - "lload_1", - "lload_2", - "lload_3", - "fload_0", - "fload_1", - "fload_2", - "fload_3", - "dload_0", - "dload_1", - "dload_2", - "dload_3", - "aload_0", - "aload_1", - "aload_2", - "aload_3", - "iaload", - "laload", - "faload", - "daload", - "aaload", - "baload", - "caload", - "saload", - "istore", - "lstore", - "fstore", - "dstore", - "astore", - "istore_0", - "istore_1", - "istore_2", - "istore_3", - "lstore_0", - "lstore_1", - "lstore_2", - "lstore_3", - "fstore_0", - "fstore_1", - "fstore_2", - "fstore_3", - "dstore_0", - "dstore_1", - "dstore_2", - "dstore_3", - "astore_0", - "astore_1", - "astore_2", - "astore_3", - "iastore", - "lastore", - "fastore", - "dastore", - "aastore", - "bastore", - "castore", - "sastore", - "pop", - "pop2", - "dup", - "dup_x1", - "dup_x2", - "dup2", - "dup2_x1", - "dup2_x2", - "swap", - "iadd", - "ladd", - "fadd", - "dadd", - "isub", - "lsub", - "fsub", - "dsub", - "imul", - "lmul", - "fmul", - "dmul", - "idiv", - "ldiv", - "fdiv", - "ddiv", - "irem", - "lrem", - "frem", - "drem", - "ineg", - "lneg", - "fneg", - "dneg", - "ishl", - "lshl", - "ishr", - "lshr", - "iushr", - "lushr", - "iand", - "land", - "ior", - "lor", - "ixor", - "lxor", - "iinc", - "i2l", - "i2f", - "i2d", - "l2i", - "l2f", - "l2d", - "f2i", - "f2l", - "f2d", - "d2i", - "d2l", - "d2f", - "i2b", - "i2c", - "i2s", - "lcmp", - "fcmpl", - "fcmpg", - "dcmpl", - "dcmpg", - "ifeq", - "ifne", - "iflt", - "ifge", - "ifgt", - "ifle", - "if_icmpeq", - "if_icmpne", - "if_icmplt", - "if_icmpge", - "if_icmpgt", - "if_icmple", - "if_acmpeq", - "if_acmpne", - "goto", - "jsr", - "ret", - "tableswitch", - "lookupswitch", - "ireturn", - "lreturn", - "freturn", - "dreturn", - "areturn", - "return", - "getstatic", - "putstatic", - "getfield", - "putfield", - "invokevirtual", - "invokespecial", - "invokestatic", - "invokeinterface", - "xxxunusedxxx", - "new", - "newarray", - "anewarray", - "arraylength", - "athrow", - "checkcast", - "instanceof", - "monitorenter", - "monitorexit", - "wide", - "multianewarray", - "ifnull", - "ifnonnull", - "goto_w", - "jsr_w", - "breakpoint" - }; - - /* Opcode Lengths */ - int opcLengths[] = { - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 2, - 3, - 2, - 3, - 3, - 2, - 2, - 2, - 2, - 2, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 2, - 2, - 2, - 2, - 2, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 3, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 2, - 99, - 99, - 1, - 1, - 1, - 1, - 1, - 1, - 3, - 3, - 3, - 3, - 3, - 3, - 3, - 5, - 0, - 3, - 2, - 3, - 1, - 1, - 3, - 3, - 1, - 1, - 0, - 4, - 3, - 3, - 5, - 5, - 1 - }; - -} diff --git a/jdk/test/java/net/URLPermission/URLTest.java b/jdk/test/java/net/URLPermission/URLTest.java index 8318c019ce8..ceb0d2c8aeb 100644 --- a/jdk/test/java/net/URLPermission/URLTest.java +++ b/jdk/test/java/net/URLPermission/URLTest.java @@ -27,7 +27,8 @@ import java.net.URLPermission; * * @test * @bug 8010464 - * @compile ../../../com/sun/net/httpserver/SimpleSSLContext.java + * @library /lib/testlibrary/ + * @build jdk.testlibrary.SimpleSSLContext * @run main/othervm/policy=policy.1 URLTest one * @run main/othervm URLTest one * @run main/othervm/policy=policy.2 URLTest two @@ -43,6 +44,7 @@ import java.util.concurrent.*; import java.util.logging.*; import com.sun.net.httpserver.*; import javax.net.ssl.*; +import jdk.testlibrary.SimpleSSLContext; public class URLTest { static boolean failed = false; @@ -209,10 +211,7 @@ public class URLTest { httpServer.setExecutor (e); httpsServer.setExecutor (es); - // take the keystore from elsewhere in test hierarchy - String keysdir = System.getProperty("test.src") - + "/../../../com/sun/net/httpserver/"; - ctx = new SimpleSSLContext(keysdir).get(); + ctx = new SimpleSSLContext().get(); httpsServer.setHttpsConfigurator(new HttpsConfigurator (ctx)); httpServer.start(); diff --git a/jdk/test/java/net/URLPermission/policy.1 b/jdk/test/java/net/URLPermission/policy.1 index a7468719165..93439790658 100644 --- a/jdk/test/java/net/URLPermission/policy.1 +++ b/jdk/test/java/net/URLPermission/policy.1 @@ -28,12 +28,13 @@ grant { // needed for HttpServer permission "java.net.SocketPermission" "localhost:1024-", "listen,resolve,accept"; permission "java.util.PropertyPermission" "test.src", "read"; - permission java.io.FilePermission "${test.src}/../../../com/sun/net/httpserver/testkeys", "read"; + permission java.io.FilePermission "${test.src}/../../../lib/testlibrary/jdk/testlibrary/testkeys", "read"; //permission "java.util.logging.LoggingPermission" "control"; //permission "java.io.FilePermission" "/tmp/-", "read,write"; permission "java.lang.RuntimePermission" "modifyThread"; permission "java.lang.RuntimePermission" "setFactory"; + permission "java.util.PropertyPermission" "test.src.path", "read"; }; // Normal permissions that aren't granted when run under jtreg diff --git a/jdk/test/java/net/URLPermission/policy.2 b/jdk/test/java/net/URLPermission/policy.2 index b71126a9ab9..43ee0f204a8 100644 --- a/jdk/test/java/net/URLPermission/policy.2 +++ b/jdk/test/java/net/URLPermission/policy.2 @@ -28,12 +28,13 @@ grant { // needed for HttpServer permission "java.net.SocketPermission" "localhost:1024-", "listen,resolve,accept"; permission "java.util.PropertyPermission" "test.src", "read"; - permission java.io.FilePermission "${test.src}/../../../com/sun/net/httpserver/testkeys", "read"; + permission java.io.FilePermission "${test.src}/../../../lib/testlibrary/jdk/testlibrary/testkeys", "read"; //permission "java.util.logging.LoggingPermission" "control"; //permission "java.io.FilePermission" "/tmp/-", "read,write"; permission "java.lang.RuntimePermission" "modifyThread"; permission "java.lang.RuntimePermission" "setFactory"; + permission "java.util.PropertyPermission" "test.src.path", "read"; }; // Normal permissions that aren't granted when run under jtreg diff --git a/jdk/test/java/net/URLPermission/policy.3 b/jdk/test/java/net/URLPermission/policy.3 index 9c29ce37096..54ddb2a591c 100644 --- a/jdk/test/java/net/URLPermission/policy.3 +++ b/jdk/test/java/net/URLPermission/policy.3 @@ -28,12 +28,13 @@ grant { // needed for HttpServer permission "java.net.SocketPermission" "localhost:1024-", "listen,resolve,accept"; permission "java.util.PropertyPermission" "test.src", "read"; - permission java.io.FilePermission "${test.src}/../../../com/sun/net/httpserver/testkeys", "read"; + permission java.io.FilePermission "${test.src}/../../../lib/testlibrary/jdk/testlibrary/testkeys", "read"; //permission "java.util.logging.LoggingPermission" "control"; //permission "java.io.FilePermission" "/tmp/-", "read,write"; permission "java.lang.RuntimePermission" "modifyThread"; permission "java.lang.RuntimePermission" "setFactory"; + permission "java.util.PropertyPermission" "test.src.path", "read"; }; // Normal permissions that aren't granted when run under jtreg diff --git a/jdk/test/java/security/KeyStore/PKCS12/ReadP12Test.java b/jdk/test/java/security/KeyStore/PKCS12/ReadP12Test.java new file mode 100644 index 00000000000..429a49857e5 --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/ReadP12Test.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2003,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. + * + * 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. + */ + +import static java.lang.System.out; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.Key; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Base64; +import java.util.Enumeration; + +/* + * @test + * @bug 8048617 + * @author Bill Situ + * @summary Read different types p12 key store to Check the read related APIs. + * including following test cases: + * ReadP12_IE_Chain: Read p12 key store (contains private key and associated + * certificate chain) from IE. + * ReadP12_IE_Self: Read p12 key store (contains only private key and + * self-signed certificate) from IE. + * ReadP12_JDK_Chain: Read p12 key store (contains private key and associated + * certificate chain) from JDK + * ReadP12_JDK_Self: Read p12 key store (contains only private key and + * self-signed certificate) from JDK. + * ReadP12_Mozilla_Self: Read p12 key store (contains only private key and + * self-signed certificate) from Mozilla. + * ReadP12_Mozilla_Chain: Read p12 key store (contains private key and + * associated certificate chain) from Mozilla. + * ReadP12_Mozilla_TwoEntries: Read p12 key store (contains 2 entries) from + * Mozilla. + * ReadP12_Netscape_Chain: Read p12 key store (contains private key and + * associated certificate chain) from Netscape. + * ReadP12_Netscape_Self: Read p12 key store (contains only private key and + * self-signed certificate) from Netscape. + * ReadP12_Netscape_TwoEntries: Read p12 key store (contains 2 entries) from + * Netscape. + * ReadP12_OpenSSL: Read p12 key store from OpenSSL. + */ + +public class ReadP12Test { + + private final static String IN_KETYSTORE_TYPE = "pkcs12"; + private final static String IN_KEYSTORE_PRV = "SunJSSE"; + private final static String IN_STORE_PASS = "pass"; + + public static void main(String args[]) throws Exception { + + ReadP12Test jstest = new ReadP12Test(); + String testCase = ""; + try { + testCase = "ReadP12_IE_Chain"; + jstest.readTest("ie_chain.pfx.data"); + + testCase = "ReadP12_IE_Self"; + jstest.readTest("ie_self.pfx.data"); + + testCase = "ReadP12_JDK_Chain"; + jstest.readTest("jdk_chain.p12.data"); + + testCase = "ReadP12_JDK_Self"; + jstest.readTest("jdk_self.p12.data"); + + testCase = "ReadP12_Mozilla_Chain"; + jstest.readTest("mozilla_chain.p12.data"); + + testCase = "ReadP12_Mozilla_Self"; + jstest.readTest("mozilla_self.p12.data"); + + testCase = "ReadP12_Mozilla_TwoEntries"; + jstest.readTest("mozilla_twoentries.p12.data"); + + testCase = "ReadP12_Netscape_Chain"; + jstest.readTest("netscape_chain.p12.data"); + + testCase = "ReadP12_Netscape_Self"; + jstest.readTest("netscape_self.p12.data"); + + testCase = "ReadP12_Netscape_TwoEntries"; + jstest.readTest("netscape_twoentries.p12.data"); + + testCase = "ReadP12_openssl"; + jstest.readTest("openssl.p12.data"); + + } catch (Exception e) { + System.err.println(testCase + ": failed with execption: " + + e.getMessage()); + throw e; + + } + out.println(testCase + ": Pass!!"); + } + + private void readTest(String inKeyStore) throws Exception { + + KeyStore inputKeyStore; + + // Initialize KeyStore + String dir = System.getProperty("test.src", "."); + String keystorePath = dir + File.separator + "certs" + File.separator + + "readP12"; + inputKeyStore = KeyStore + .getInstance(IN_KETYSTORE_TYPE, IN_KEYSTORE_PRV); + // KeyStore have encoded by Base64.getMimeEncoder().encode(),need decode + // first. + byte[] input = Files.readAllBytes(Paths.get(keystorePath, inKeyStore)); + ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64 + .getMimeDecoder().decode(input)); + inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray()); + out.println("Initialize KeyStore : " + inKeyStore + " success"); + + out.println("getProvider : " + inputKeyStore.getProvider()); + out.println("getType : " + inputKeyStore.getType()); + out.println("getDefaultType : " + KeyStore.getDefaultType()); + + int idx = 0; + Enumeration e = inputKeyStore.aliases(); + String alias; + while (e.hasMoreElements()) { + alias = e.nextElement(); + out.println("Alias " + idx + " : " + alias); + if (inputKeyStore.containsAlias(alias) == false) { + throw new RuntimeException("Alias not found"); + } + + out.println("getCreationDate : " + + inputKeyStore.getCreationDate(alias)); + + X509Certificate cert = (X509Certificate) inputKeyStore + .getCertificate(alias); + out.println("getCertificate : " + cert.getSubjectDN()); + String retAlias = inputKeyStore.getCertificateAlias(cert); + if (!retAlias.equals(alias)) { + throw new RuntimeException("Alias mismatch"); + } + out.println("getCertificateAlias : " + retAlias); + + Certificate[] certs = inputKeyStore.getCertificateChain(alias); + for (int i = 0; i < certs.length; i++) { + out.println("getCertificateChain " + i + " : " + + ((X509Certificate) certs[i]).getSubjectDN()); + } + + boolean isCertEntry = inputKeyStore.isCertificateEntry(alias); + // test KeyStore only contain key pair entries. + if (isCertEntry == true) { + throw new RuntimeException( + "inputKeystore should not be certEntry because test keystore only contain key pair entries."); + } + + boolean isKeyEntry = inputKeyStore.isKeyEntry(alias); + if (isKeyEntry) { + Key key = inputKeyStore.getKey(alias, + IN_STORE_PASS.toCharArray()); + out.println("Key : " + key.toString()); + } else { + throw new RuntimeException("Entry type unknown\n"); + } + idx++; + } + + int size = inputKeyStore.size(); + if (idx != size) { + throw new RuntimeException("Size not match"); + } + + } +} diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/ie_chain.pfx.data b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/ie_chain.pfx.data new file mode 100644 index 00000000000..3dbe7e4fcb3 --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/ie_chain.pfx.data @@ -0,0 +1,61 @@ +MIINXgIBAzCCDRoGCSqGSIb3DQEHAaCCDQsEgg0HMIINAzCCA7wGCSqGSIb3DQEHAaCCA60EggOp +MIIDpTCCA6EGCyqGSIb3DQEMCgECoIICtjCCArIwHAYKKoZIhvcNAQwBAzAOBAipOP0AVsizDgIC +B9AEggKQIP/YI9/C2WYbIWxKuqXMD8WPCvqj1fhHmZJ0epCzgEdOR7GT/h2Fy4/wxrthPkj4JqkS +akQog3pjOFtj9D8QtkOw/b761qsyj17TYlQS9C6qVhcddMA+Ca2NcDhKlYofQMNTuYPXkXlpCh5R +CNFgQ+PLVZwNZjqoitjv0RLQqBudhTmJSvfDlW2w+CpbziEeRNzn0pX0/Ts7KxykDscOmUCGHKic +b6FqHoioElcmBp7ae3zdXuvI1x/1Y435qju2yODPpMXEZbdsD5iL07RZyL2vm6lfQbLc37TszDBx +ZZJ7ja5F4V/j/6/AVLkcqfZxFOnXz5Ki9rQblYJbkkTpJAyiNqi8Gx+zgPGtLWvV6KRD0zmxo6q/ +OmdjKz4v9aG7MDSXenoy6tPAOvAQcQYaksvFZs1FjorJJpFzasfTUfy94JzrHUzRSPzNRDANHG/6 +TgxC1FMNw+iQUY9L8j4xrWsr2JN5tAgYcWz1qZrp4cx0he9cbQeqYcjv7ZvIQbIe2zxdvxh7WByy +r8hNMe3RkMOM2yuP85JuWipq+9jt4/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HxsMJ04Th+RZ7s8seoLBeAn7gbsj3B/JUOxIaEx8+W3bjb1 +wq6cc+KqLnvcO2BDvH30PfeQo7YjTNr4wcEoUFZXwhTL5owVc4GKtlfl/YxBXs2E6r6l43svlay6 +vCq58xTvWzzRtzvb6oh6qnoMP2xc8YTdpKma64TBmnFOVE/eGXZxVyk19TXwrokqUliutqhM6acv +x87+Yru+uXTbUpMA0MuW0Ch6uvcwxmM1hq5vHDVBTAfGuXsdQMapKoqseFUfza7N2eSgU8oaJCGQ +rmhvDn+MNzh2VyLOnPBwJ+sUnHM7XOnz/rCD99uRhhssEwZ5Xij+FG3EeTYyntGp6Z7ODIazLHM8 +81QtQDrJg2EDJ5RZHHrPbyUQDCkGpLZNOOoJkAD7I0VZRC3jJb8lTMXdKQjCd39F842+FXTSvOv9 +lmEOFH4AEyI6CokzFQCD0TXhTaG9wtzaE2q41eEKF45J5vyQxrNabZXeovNIVZryK+N8ep28M084 +vXp7uJm0bg5NunK6vTIqsxenQZWvXay8EwYLbAm8crDxK5sbW4tZtNeVxPE6ekCbifdxdgm0671w +rt4wOzAfMAcGBSsOAwIaBBT1C0A3jyKtjUTFASRSO852mKBZQQQUqy721AxhZ26s5Tsue4OHTjEB +CxwCAgfQ \ No newline at end of file diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/ie_self.pfx.data b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/ie_self.pfx.data new file mode 100644 index 00000000000..acde65c2ebe --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/ie_self.pfx.data @@ -0,0 +1,47 @@ +MIIKRgIBAzCCCgIGCSqGSIb3DQEHAaCCCfMEggnvMIIJ6zCCBgwGCSqGSIb3DQEHAaCCBf0EggX5 +MIIF9TCCBfEGCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAjnValj/qxAxQIC +B9AEggTYZZfhDgMBhoV+P+A4KJf/gnrbkgp4ZDWzXl8gOttjRXof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Ckw1/3j5Qdr3feN4GWqOBTfn0cK +eq8RT0pBkT0wOzAfMAcGBSsOAwIaBBRW5H12kY01oB2hnm0lkT0yUbjP4wQUF7tfAlojMdSZIdKB +/FfU1hlVl8YCAgfQ \ No newline at end of file diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/jdk_chain.p12.data b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/jdk_chain.p12.data new file mode 100644 index 00000000000..f379d2ba380 --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/jdk_chain.p12.data @@ -0,0 +1,62 @@ +MIINqAIBAzCCDWIGCSqGSIb3DQEHAaCCDVMEgg1PMIINSzCCAzgGCSqGSIb3DQEHAaCCAykEggMl +MIIDITCCAx0GCyqGSIb3DQEMCgECoIICsjCCAq4wKAYKKoZIhvcNAQwBAzAaBBQj8/7sNqA6OGwS +O3nBO2jejhMCdgICBAAEggKA+SmvxFl8NlTv9TZf9YTiFOoUfLGNNxX+KaW9Qy+vBtAqU9rIqLeU +Wc7K5ovqYIcOHUYqjMECgfGWKEcT5XQljB9uPXh+L55glggXpJ6ZtgNjwOCGfXak+x2nV5ynIRD8 +196Txb3tyGJrEEVvmm5UFMRnFbUiXmwRvV1nBAgAXFCpdv+cowKsY0SS9NIyYujzhObByV70Bd0Y +rOTV6Wvg/Pw/p9FpOskiLSgwxY0Eb+ryAUjMs+DXsH7okVQj5xriWKz2jyRSMvRlxj7qL+SvgTcQ +J+2dB1QO9y34AAP0eTypJhZ2aEZl7PiDJ2QigP7ahm2YCTpGLyR8drrRD4UNWZ6WVt+wp0giTkmd +QHYm/4XVqUDcYbXjOPapfQPDgWEDZdduGS/Lt+ELfeItRP+aPQxBaZoRjfXbUmv96WSbNl4YSEJE +hq3Ri+3xClzXDK08AB1g4ro9kQSMJb/zt5We+X9XLaDl2w4H23/MaMcuBbXb42eLIoSELcBYAlc+ +ffoZ/5rXzRfAjVO0Po3qnB6DAa68DTa1goXvQy5C2j/Qf8G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CjuT1q/TkcTjd3Hheyu+kYbvFpdbltKjZ/m+Vob63G +fwoB0/JPIZseKLjSMMITogNVezAiHsJV4kYyMOmnbRBLA1OyIiV0gnAnX7KpUXg0DXsDO4H9uxGv +DVm9QyD832m7HbDe7vzJv5nrq0yxSJfxPiinq+5GmQUVwYFYsLwfvkUINF4CTeWvFGumOBTU5YNP +4G2NVbAgkNpBwJhljABNXChChAeesBvQ4fTK5L3WwDcCO4uDEIHlIQvd4QJQa+QWQ39voKIOnjz4 +/jGwqFcssy+aXnlI6Ub9UpMkc4vcE3rVB0qanitlSVBszL97PSorJaoddKs+wMBwBiY5RlvRBaFT +EtWbiWfLEeAC4cNkEmDToMZNwE1fS+0ZqSoOYqEjAw2M4HXvmZqqS6bP9zEs9n4qCKaT2dYG6rQB +wpHy0WH9myqcgdY1JILfRpQK6PehDXLUMT8a44Fk9vxULare2dQ3uTTyBqfE+B+ainFQ/QBxP7t+ +vsjPxPxxD22eWUT1v4xhT7mzurM83N+AJAaAU2QJ6vYwTGS2NNTDjmm8pMyoLjey0KJKud8isbAC +mqsZHEC0tqOkdVdikLEmcjq5yMl5qZpDYYHrWbth8/5bdRus+UWj7jXOMBW6h43eyKvs4/HEhWEd +KRyvXX7ylBPr+Ow1JYKcg9IwPTAhMAkGBSsOAwIaBQAEFEkDUNCE10mwzwFgzaDBuOaQNXMqBBQA +IsNed5PjTXd1/rQmWIcCDOy9lgICBAA= \ No newline at end of file diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/jdk_self.p12.data b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/jdk_self.p12.data new file mode 100644 index 00000000000..b643ba4f20a --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/jdk_self.p12.data @@ -0,0 +1,45 @@ +MIIJzgIBAzCCCYgGCSqGSIb3DQEHAaCCCXkEggl1MIIJcTCCA/MGCSqGSIb3DQEHBqCCA+QwggPg +AgEAMIID2QYJKoZIhvcNAQcBMCgGCiq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ndD2dkf+Q5wQUlDj7Q1RzRmooVNZ+0cEv+M/q +I6oCAgQA \ No newline at end of file diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/mozilla_chain.p12.data b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/mozilla_chain.p12.data new file mode 100644 index 00000000000..623d470c86b --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/mozilla_chain.p12.data @@ -0,0 +1,73 @@ +MIACAQMwgAYJKoZIhvcNAQcBoIAkgAQBMAQBgAQBMAQBgAQBBgQBCQQJKoZIhvcNAQcBBAGgBAGA +BAEkBAGABAEEBAEBBAEwBAEEBAEDBAOCAx4EAQQEAQEEATAEAQQEAQMEA4IDGgQBBAQBAQQBBgQB +BAQBAQQBCwQBBAQBCwQLKoZIhvcNAQwKAQIEAQQEAQEEAaAEAQQEAQMEA4ICrQQBBAQBAQQBMAQB +BAQBAwQDggKpBAEEBAEBBAEwBAEEBAEBBAEjBAEEBAEBBAEGBAEEBAEBBAEKBAEEBAEKBAoqhkiG +9w0BDAEDBAEEBAEXBBcwFQQQKJ0s1k6Yhc9YUlHulAdsYwIBAQQBBAQBAQQBBAQBBAQBAwQDggKA +BAEEBAOCAoAEggKALk0hQJ9bgp0taVmPt+8aOIluzqPyDTizShw1vBVIYUZR632m2wd8hZGg7Apd +y7+P/wZQUhAAiqxWMpz7KdMnt2q8oV+7ghH4+2skdMBIAsK3Z5JH+RH5ABwyGdPmO5Xxjtw12eu7 +D82h+CCkf4VpDBlALqkiLLpT1ktyZuabMtLwmBbKiunFue0NWcXD6hPYuKbyAKW206Vj6Dr9XT4J +0KSEeBTKRlDUjZaN1LgNzhbv7D8G42NBTVRtBVcGuxqwckBf5gd0SqJpKnSt8HOw+tv1VqcGnzDK +hWi8szZq674aIlJhhmbqgMD1hAi+Yv+nFuFDbVnvnFAWBXyYGbZhl3sbZTMoMCGVcNgX+O+C083h +9RsWGvszvqPmTxhFoCRHbEl+RxyN1cJzB4HlNhe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8s7zM07dyhzEifUtAKqgGznqqkY5sBsuG9avY7oNvqdRo146LM8ZI3LVkPG4fyQsyKDkivgqrPp +T44uuddd9aCSin1Lot8V5UO+qF+PWJE8VbbObRRP8QUARktQQKNqUsAfry0FLdJ8Yv7Ib4FLtjxn +lD6Sq+WMMpXGnxcEAQQEAQgECMONWxXYfPfhBAEEBAEIBAhh+55FHbAwzgQBBAQBIAQguWZEyrFt +n9z/zuxAuHPdrjF/M8dpcOcSrrU2W6SkiAIEAQQEAQgECCOncp8X/0YIBAEEBAEIBAg9EPBdfPjB +MQQBBAQBCAQIjBJWUnE0AUYEAQQEARAEEDtzVkwblT0wH2JtjnlN3xwEAQQEAQgECKN9mrkoW0bd +BAIAAAQCAAAEAgAABAIAAAQCAAAEAgAAAAAAAAAAMDUwITAJBgUrDgMCGgUABBQi1DByHr7xEEbI +o8rv5OcUCY4LCgQQBJk3S8mxlQnP+3lHAlg/5gAA \ No newline at end of file diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/mozilla_self.p12.data b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/mozilla_self.p12.data new file mode 100644 index 00000000000..c36f26b516b --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/mozilla_self.p12.data @@ -0,0 +1,54 @@ +MIACAQMwgAYJKoZIhvcNAQcBoIAkgAQBMAQBgAQBMAQBgAQBBgQBCQQJKoZIhvcNAQcBBAGgBAGA +BAEkBAGABAEEBAEBBAEwBAEEBAEDBAOCBVoEAQQEAQEEATAEAQQEAQMEA4IFVgQBBAQBAQQBBgQB +BAQBAQQBCwQBBAQBCwQLKoZIhvcNAQwKAQIEAQQEAQEEAaAEAQQEAQMEA4IE9QQBBAQBAQQBMAQB +BAQBAwQDggTxBAEEBAEBBAEwBAEEBAEBBAEjBAEEBAEBBAEGBAEEBAEBBAEKBAEEBAEKBAoqhkiG +9w0BDAEDBAEEBAEXBBcwFQQQ6zZGbbQFxSQTlsEh5FOilQIBAQQBB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kwj+SrxCFu7u64QzRY92hpDtl78gB1qcUZOCNQuf3kv5B4x5ALZyZU7 +Ckr9yu3yjNbgpnJ8gfFE006iAHqpLU2rn6i/xJXHb8cKv8VMHxO0EMR1SOtC7lLNI/iOIpN99/Pm +3U9j6XwcIWoU/4Be9BITKqIw423XThI9qNa9dGj+Oa73xJP6J7dP7gWk2ZmSJclXMA6W72rNqBVe +nO38KaAW72ua7AQBBAQBCAQIeWKILNPVXOMEAQQEAQgECPpwizh9y4WnBAEEBAEYBBi3tGsk9rHI +yZSUfNtMIDrErllTfg2GN3oEAQQEAQgECLz46GLmSgG2BAEEBAEIBAgrwI+J9uoOrgQBBAQBCAQI +1rx18cjRHAwEAQQEARAEEOxoG0/8z95+B8v/zQLWEx4EAQQEAQgECHjhPmEWa8hSBAIAAAQCAAAE +AgAABAIAAAQCAAAEAgAAAAAAAAAAMDUwITAJBgUrDgMCGgUABBTZql8WIANfobuVIA3JOsmBS/sC +0AQQxrOtDDKIzjpW4+rATcwNPAAA \ No newline at end of file diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/mozilla_twoentries.p12.data b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/mozilla_twoentries.p12.data new file mode 100644 index 00000000000..d0c451b24c3 --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/mozilla_twoentries.p12.data @@ -0,0 +1,125 @@ +MIACAQMwgAYJKoZIhvcNAQcBoIAkgAQBMAQBgAQBMAQBgAQBBgQBCQQJKoZIhvcNAQcBBAGgBAGA +BAEkBAGABAEEBAEBBAEwBAEEBAEDBAOCBVoEAQQEAQEEATAEAQQEAQMEA4IFVgQBBAQBAQQBBgQB +BAQBAQQBCwQBBAQBCwQLKoZIhvcNAQwKAQIEAQQEAQEEAaAEAQQEAQMEA4IE9QQBBAQBAQQBMAQB +BAQBAwQDggTxBAEEBAEBBAEwBAEEBAEBBAEjBAEEBAEBBAEGBAEEBAEBBAEKBAEEBAEKBAoqhkiG +9w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ekAMrtiPagaGwJ6sCgMfbniapIFYbv6StYfaFJlgNphS/DIobXbVbyZj5Uxt7FkJ5T4YYKk +mharN+bIxYB4CnLMmq0tWTtu5I0AQ8x4eU+4KIgz80nG+AoqkCiHqCx2/c8jjO+QyJ0gdrUgHStB +acbDEmAGOIPw1I6UbZcbYr+Dw+Jlgu4e32WuT+reIghLt7KCWw90hxWJOYmNIKJJT8Ewz+Df7Wo5 +2Uka3dKxtQHIDC1LgKmEeXTB1Hopcdpz/c6Kq8Ggh0T1kcZXTJSM2MeRvhBIGhOX6k6QMrUtb4eE +KS9TY9rHSncue7f67JqPs5M9O9iOwG+uC7KhVDeiXyVnevcJx1LQoBW+lY7PyBxfz/mLBAEEBAEI +BAgGsHMj+U49xQQBBAQBCAQIYEhNq/vbNkEEAQQEASAEIHVkTzJskJH7dTPVu3L70TP3a9O3UCPP +1XNL8it1xwrUBAEEBAEIBAhv1CJBZZXkRwQBBAQBCAQIjpPAXu2cCDUEAQQEAQgECPzpQ2fbKHER +BAEEBAEQBBBnyGy02G8nSEv/AjOfesi7BAEEBAEIBAjp6fhwciDeoAQCAAAEAgAABAIAAAQCAAAE +AgAABAIAAAAAAAAAADA1MCEwCQYFKw4DAhoFAAQUF710Y0xSt781mbg0wkOomTUoFNYEEG6xrJYt +AoiyQ6u3imI281gAAA== \ No newline at end of file diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/netscape_chain.p12.data b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/netscape_chain.p12.data new file mode 100644 index 00000000000..af0557ab30d --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/netscape_chain.p12.data @@ -0,0 +1,73 @@ +MIACAQMwgAYJKoZIhvcNAQcBoIAkgAQBMAQBgAQBMAQBgAQBBgQBCQQJKoZIhvcNAQcBBAGgBAGA +BAEkBAGABAEEBAEBBAEwBAEEBAEDBAOCAx4EAQQEAQEEATAEAQQEAQMEA4IDGgQBBAQBAQQBBgQB +BAQB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AgAAAAAAAAAAMDUwITAJBgUrDgMCGgUABBSCL64+O9/0Dj3l +l3kjJ0+sn34/TgQQKK+gqvx7hiM6AgcLr375KAAA \ No newline at end of file diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/netscape_self.p12.data b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/netscape_self.p12.data new file mode 100644 index 00000000000..bdc94837e17 --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/netscape_self.p12.data @@ -0,0 +1,54 @@ +MIACAQMwgAYJKoZIhvcNAQcBoIAkgAQBMAQBgAQBMAQBgAQBBgQBCQQJKoZIhvcNAQcBBAGgBAGA +BAEkBAGABAEEBAEBBAEwBAEEBAEDBAOCBVoEAQQEAQEEATAEAQQEAQMEA4IFVgQBBAQBAQQBBgQB +BAQBAQQBCwQBBAQBCwQLKoZIhvcNAQwKAQIEAQQEAQEEAaAEAQQEAQMEA4IE9QQBBAQBAQQBMAQB +BAQBAwQDggTxBAEEBAEBBAEwBAEEBAEBBAEjBAEEBAEBBAEGBAEEBAEBBAEKBAEEBAEKBAoqhkiG +9w0BDAEDBAEEBAEXBBcwFQQQ4eiSg5zfyUwdqG251zs8vwIBAQQBBAQBAQQBBAQBBAQBAwQDggTI +BAEEBAOCBMgEggTIJHLhX9tA330EoYs3J/1z+kyq7Hxnu2hon+xM1+CkmdEpqAh0SMRvyTvJ/chz +MS/RBG+JfioXwBD+Ax9lS64Fr4nuPY7tlIW13cEJ0jsjFl8W0Lpu+dZ2S80wImI88GCIdTPsglnI +Ir2aUy3iAvm0A7XqTp0UB6kluAsJ1ma8AC6LWKnFPW44WPVG1Y40owBF+Dkq00dhjqF+vxWuQIKu +7Hh4CboIA5ydprYp+SH9W1AjaTWuSDLyHr7BFUST/Ei3JzqA17J/+IuJAurIPCLcsB6gyIHRnxNg +/KT8X7X1o1jwa2jpzjj1wUo7yCxGk521gDkdC3IUKVelGYHo0JxepTRVQdl0n62tSwSeb6zk8jhA +n3H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AIAAAQCAAAEAgAAAAAAAAAAMDUwITAJBgUrDgMCGgUABBQzMEgJJvPUMzhrw5LQm5iUbv/C +HwQQ6Vxq63yfCeamza5PZKytWQAA \ No newline at end of file diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/netscape_twoentries.p12.data b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/netscape_twoentries.p12.data new file mode 100644 index 00000000000..cdc8438d0c0 --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/netscape_twoentries.p12.data @@ -0,0 +1,125 @@ +MIACAQMwgAYJKoZIhvcNAQcBoIAkgAQBMAQBgAQBMAQBgAQBBgQBCQQJKoZIhvcNAQcBBAGgBAGA +BAEkBAGABAEEBAEBBAEwBAEEBAEDBAOCBVoEAQQEAQEEATAEAQQEAQMEA4IFVgQBBAQBAQQBBgQB +BAQBAQQBCwQBBAQBCwQLKoZIhvcNAQwKAQIEAQQEAQEEAaAEAQQEAQMEA4IE9QQBBAQBAQQBMAQB +BAQBAwQDggTxBAEEBAEBBAEwBAEEBAEBBAEjBAEEBAEBBAEGBAEEBAEBBAEKBAEEBAEKBAoqhkiG +9w0BDAEDBAEEBAEXBBcwFQQQxXsQcQJrh4QpLLn7YLjghAIBAQQBBAQBAQQBBAQBBAQBAwQDggTI +BAEEBAOCBMgEggTIzyTPE6ABvJ4C4SQLGDsV8SH5rX772SpsrvSJ1pGISoOHvcgwp9rBkg9eBKfJ +uOh4miBCIssLSICJUyNvl8U/P471h4CN9DI0XWWkPY/B/0AxH9rpNED3mS99xznwpNyVDUUFH787 +WpfvkieOwsx8KUxxkU3IY0+1yqgY9NfEUSrIxEq5nBh0euEW1M88jFW6+i5cV3fuyWSROaCF5RIz +jHgXnFJi9uiLDohMBAStZWoiPMZ+Joc67Anoyok5ijjktEBrfyxTxP1AoeemPNq3sbCAPDLKGjxq +yZ4a9ZexL2MpX1AtvKJdAlgxBjon8TSxmNpziyT0gSpE5fN7Bso19uVbEJy07UUee4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xdqbQLnbavPQBAEEBAEIBAgQ1DQiYMlQvwQBBAQBCAQIfobT9m0NL6MEAQQEAQgECO88SOz8Mrm5 +BAEEBAEQBBAhKm3aTWchcpEqcmDZMslFBAEEBAEIBAilVOqmFlh1bAQCAAAEAgAABAIAAAQCAAAE +AgAABAIAAAAAAAAAADA1MCEwCQYFKw4DAhoFAAQU4mtN68ZA4iPtEOTXDVJm54QTLygEEApVeHi+ +LK2fdlxrCGzUHTgAAA== \ No newline at end of file diff --git a/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/openssl.p12.data b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/openssl.p12.data new file mode 100644 index 00000000000..101a03993c5 --- /dev/null +++ b/jdk/test/java/security/KeyStore/PKCS12/certs/readP12/openssl.p12.data @@ -0,0 +1,41 @@ +MIIJDAIBAzCCCNIGCSqGSIb3DQEHAaCCCMMEggi/MIIIuzCCBYcGCSqGSIb3DQEHBqCCBXgwggV0 +AgEAMIIFbQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQIELQQ5giZFkcCAggAgIIFQBgoLahw +nwhVA6dtjxWdyiJlb6vIFa+jVvrftKwtzplcDb3nWS0MD9EJtA5D672Yng7z2szv28JbnA3V9B6g +ZcXStYo3Eb7UAp/ng3iAOIvqu6pLIn077nZVrgMzYeSOVgsXpZUM5IzROWmVsBonsXJyBJbJSg26 +lcOOF7Qoqg/0kRqAgVbOofSrKHHub27IQniVdcV0+5NCEzd+GfmfwGQCHDyhLl9WOsbPSuq+RDWX +tLT3T0jQBfoQuhCtYFuGmPx3RpvtoedJxFpgyfelRZpGgOfbH44V5o2O5hohy8Vq1FaGX4ZnwpX/ +BS3tjcHa6UNbv2+rTevC+ap7Blx8PBUasHDPpf8TcMLVR0dZ66gIp8cHslYT9VOVWWtGLRCyAhCB +6Jo+NotjXhR9Jsh0FJ6vYOzsZxIUvbWzQi3FjYwmyGK04SVk4qGpYHKZFNxdsJQyYhCmB0FD7UEG +DEFHnIZ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zb +cksgnRPW8emqi4b9dpatcakxFyqMaFWEyUNZ9pVJblBMcmWy1jhfmvHLqEMj6XSB0BoxLm/hlvvh +b0BoTeHE6Y4P6uLyVkgO0PDeK2zSilO76xxopwnaHewqSLFrFow6RigMMMuZ3gkRwffWPw7GZ/6w +OAMUkUy9Z4xoWOHxojFYMCMGCSqGSIb3DQEJFTEWBBQ+1XUMoIuapQz8y+wtVU4OS2/MVzAxBgkq +hkiG9w0BCRQxJB4iAHAAawBjAHMAMQAyAG8AcABlAG4AcwBzAGwAdABlAHMAdDAxMCEwCQYFKw4D +AhoFAAQU0eEVVRJLmHOENfblXST7WPskPuMECOPkUlL+BAAZAgIIAA== \ No newline at end of file diff --git a/jdk/test/java/security/MessageDigest/TestDigestIOStream.java b/jdk/test/java/security/MessageDigest/TestDigestIOStream.java new file mode 100644 index 00000000000..46028e85af8 --- /dev/null +++ b/jdk/test/java/security/MessageDigest/TestDigestIOStream.java @@ -0,0 +1,335 @@ +/* + * Copyright (c) 2003, 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. + * + * 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. + */ + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.security.DigestInputStream; +import java.security.DigestOutputStream; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Random; +import static java.lang.System.out; + +/** + * @test + * @bug 8050370 + * @summary MessageDigest tests with DigestIOStream + * @author Kevin Liu + */ + +enum ReadModel { + READ, BUFFER_READ, MIX_READ +} + +public class TestDigestIOStream { + + private static final int[] DATA_LEN_ARRAY = { + 1, 50, 2500, 125000, 6250000 + }; + private static final String[] ALGORITHM_ARRAY = { + "MD2", "MD5", "SHA1", "SHA-224", "SHA-256", "SHA-384", "SHA-512" + }; + + private static byte[] data; + + private static MessageDigest md = null; + + public static void main(String argv[]) throws Exception { + TestDigestIOStream test = new TestDigestIOStream(); + test.run(); + } + + public void run() throws Exception { + for (String algorithm: ALGORITHM_ARRAY) { + + md = MessageDigest.getInstance(algorithm); + + for (int length: DATA_LEN_ARRAY) { + + Random rdm = new Random(); + data = new byte[length]; + rdm.nextBytes(data); + + if (!testMDChange(algorithm, length)) { + throw new RuntimeException("testMDChange failed at:" + + algorithm + "/" + length); + } + if (!testMDShare(algorithm, length)) { + throw new RuntimeException("testMDShare failed at:" + + algorithm + "/" + length); + } + for (ReadModel readModel: ReadModel.values()) { + // test Digest function when digest switch on + if (!testDigestOnOff(algorithm, readModel, true, length)) { + throw new RuntimeException("testDigestOn failed at:" + + algorithm + "/" + length + "/" + readModel); + } + // test Digest function when digest switch off + if (!testDigestOnOff(algorithm, readModel, false, length)) { + throw new RuntimeException("testDigestOff failed at:" + + algorithm + "/" + length + "/" + readModel); + } + } + } + } + int testNumber = ALGORITHM_ARRAY.length * ReadModel.values().length + * DATA_LEN_ARRAY.length * 2 + ALGORITHM_ARRAY.length + * DATA_LEN_ARRAY.length * 2; + out.println("All " + testNumber + " Tests Passed"); + } + + /** + * Test DigestInputStream and DigestOutputStream digest function when digest + * set on and off + * + * @param algo + * Message Digest algorithm + * @param readModel + * which read method used(READ, BUFFER_READ, MIX_READ) + * @param on + * digest switch(on and off) + * @param dataLength + * plain test data length. + * @exception Exception + * throw unexpected exception + */ + public boolean testDigestOnOff(String algo, ReadModel readModel, + boolean on, int dataLength) throws Exception { + + // Generate the DigestInputStream/DigestOutputStream object + try (ByteArrayInputStream bais = new ByteArrayInputStream(data); + DigestInputStream dis = new DigestInputStream(bais, + MessageDigest.getInstance(algo)); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DigestOutputStream dos = new DigestOutputStream(baos, + MessageDigest.getInstance(algo)); + ByteArrayOutputStream baOut = new ByteArrayOutputStream();) { + + // Perform the update using all available/possible update methods + int k = 0; + byte[] buffer = new byte[5]; + boolean enDigest = true; + // Make sure the digest function is on (default) + dis.on(enDigest); + dos.on(enDigest); + + switch (readModel) { + case READ: // use only read() + while ((k = dis.read()) != -1) { + if (on) { + dos.write(k); + } else { + dos.write(k); + if (enDigest) { + baOut.write(k); + } + enDigest = !enDigest; + dos.on(enDigest); + dis.on(enDigest); + } + } + break; + case BUFFER_READ: // use only read(byte[], int, int) + while ((k = dis.read(buffer, 0, buffer.length)) != -1) { + if (on) { + dos.write(buffer, 0, k); + } else { + dos.write(buffer, 0, k); + if (enDigest) { + baOut.write(buffer, 0, k); + } + enDigest = !enDigest; + dis.on(enDigest); + dos.on(enDigest); + } + } + break; + case MIX_READ: // use both read() and read(byte[], int, int) + while ((k = dis.read()) != -1) { + if (on) { + dos.write(k); + if ((k = dis.read(buffer, 0, buffer.length)) != -1) { + dos.write(buffer, 0, k); + } + } else { + dos.write(k); + if (enDigest) { + baOut.write(k); + } + enDigest = !enDigest; + dis.on(enDigest); + dos.on(enDigest); + if ((k = dis.read(buffer, 0, buffer.length)) != -1) { + dos.write(buffer, 0, k); + if (enDigest) { + baOut.write(buffer, 0, k); + } + enDigest = !enDigest; + dis.on(enDigest); + dos.on(enDigest); + } + } + } + break; + default: + out.println("ERROR: Invalid read/write combination choice!"); + return false; + } + + // Get the output and the "correct" digest values + byte[] output1 = dis.getMessageDigest().digest(); + byte[] output2 = dos.getMessageDigest().digest(); + byte[] standard; + if (on) { + standard = md.digest(data); + } else { + byte[] dataDigested = baOut.toByteArray(); + standard = md.digest(dataDigested); + } + + // Compare the output byte array value to the input data + if (!MessageDigest.isEqual(data, baos.toByteArray())) { + out.println("ERROR of " + readModel + + ": output and input data unexpectedly changed"); + return false; + } + // Compare generated digest values + if (!MessageDigest.isEqual(output1, standard) + || !MessageDigest.isEqual(output2, standard)) { + out.println("ERROR" + readModel + + ": generated digest data unexpectedly changed"); + return false; + } + + return true; + } catch (Exception ex) { + out.println("testDigestOnOff failed at:" + algo + "/" + readModel + + "/" + dataLength + " with unexpected exception"); + throw ex; + } + } + + /** + * Test DigestInputStream and DigestOutputStream digest function when Swap + * the message digest engines between DigestIn/OutputStream + * + * @param algo + * Message Digest algorithm + * @param dataLength + * plain test data length. + * @exception Exception + * throw unexpected exception + */ + public boolean testMDChange(String algo, int dataLength) throws Exception { + // Generate the DigestInputStream/DigestOutputStream object + MessageDigest mdIn = MessageDigest.getInstance(algo); + MessageDigest mdOut = MessageDigest.getInstance(algo); + try (ByteArrayInputStream bais = new ByteArrayInputStream(data); + DigestInputStream dis = new DigestInputStream(bais, mdIn); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DigestOutputStream dos = new DigestOutputStream(baos, mdOut);) { + + // Perform the update using all available/possible update methods + int k = 0; + byte[] buffer = new byte[10]; + + // use both read() and read(byte[], int, int) + while ((k = dis.read()) != -1) { + dos.write(k); + if ((k = dis.read(buffer, 0, buffer.length)) != -1) { + dos.write(buffer, 0, k); + } + + // Swap the message digest engines between + // DigestIn/OutputStream objects + dis.setMessageDigest(mdOut); + dos.setMessageDigest(mdIn); + mdIn = dis.getMessageDigest(); + mdOut = dos.getMessageDigest(); + } + + // Get the output and the "correct" digest values + byte[] output1 = mdIn.digest(); + byte[] output2 = mdOut.digest(); + byte[] standard = md.digest(data); + + // Compare generated digest values + return MessageDigest.isEqual(output1, standard) + && MessageDigest.isEqual(output2, standard); + } catch (Exception ex) { + out.println("testMDChange failed at:" + algo + "/" + dataLength + + " with unexpected exception"); + throw ex; + } + } + + /** + * Test DigestInputStream and DigestOutputStream digest function when use + * same message digest object. + * + * @param algo + * Message Digest algorithm + * @param dataLength + * plain test data length. + * @exception Exception + * throw unexpected exception + */ + public boolean testMDShare(String algo, int dataLength) throws Exception { + MessageDigest mdCommon = MessageDigest.getInstance(algo); + // Generate the DigestInputStream/DigestOutputStream object + try (ByteArrayInputStream bais = new ByteArrayInputStream(data); + DigestInputStream dis = new DigestInputStream(bais, mdCommon); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DigestOutputStream dos = new DigestOutputStream(baos, mdCommon);) { + + // Perform the update using all available/possible update methods + int k = 0; + byte[] buffer = new byte[10]; + + // use both read() and read(byte[], int, int) + while (k < data.length) { + int len = dis.read(buffer, 0, buffer.length); + if (len != -1) { + k += len; + if (k < data.length) { + dos.write(data[k]); + k++; + dis.skip(1); + } + } + } + + // Get the output and the "correct" digest values + byte[] output = mdCommon.digest(); + byte[] standard = md.digest(data); + + // Compare generated digest values + return MessageDigest.isEqual(output, standard); + } catch (Exception ex) { + out.println("TestMDShare failed at:" + algo + "/" + dataLength + + " with unexpected exception"); + throw ex; + } + } +} diff --git a/jdk/test/javax/management/remote/mandatory/notif/NotificationAccessControllerTest.java b/jdk/test/javax/management/remote/mandatory/notif/NotificationAccessControllerTest.java index 1dd7927b5e0..fca338f5628 100644 --- a/jdk/test/javax/management/remote/mandatory/notif/NotificationAccessControllerTest.java +++ b/jdk/test/javax/management/remote/mandatory/notif/NotificationAccessControllerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -37,6 +37,8 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Semaphore; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.MBeanServerFactory; @@ -56,10 +58,12 @@ import javax.security.auth.Subject; public class NotificationAccessControllerTest { public class NAC implements NotificationAccessController { - private boolean throwException; + private final boolean throwException; public NAC(boolean throwException) { this.throwException = throwException; } + + @Override public void addNotificationListener( String connectionId, ObjectName name, @@ -72,10 +76,14 @@ public class NotificationAccessControllerTest { (subject == null ? null : subject.getPrincipals())); if (throwException) if (name.getCanonicalName().equals("domain:name=1,type=NB") + && + subject != null && subject.getPrincipals().contains(new JMXPrincipal("role"))) throw new SecurityException(); } + + @Override public void removeNotificationListener( String connectionId, ObjectName name, @@ -88,10 +96,14 @@ public class NotificationAccessControllerTest { (subject == null ? null : subject.getPrincipals())); if (throwException) if (name.getCanonicalName().equals("domain:name=2,type=NB") + && + subject != null && subject.getPrincipals().contains(new JMXPrincipal("role"))) throw new SecurityException(); } + + @Override public void fetchNotification( String connectionId, ObjectName name, @@ -105,13 +117,17 @@ public class NotificationAccessControllerTest { echo("\tsubject: " + (subject == null ? null : subject.getPrincipals())); if (!throwException) - if (name.getCanonicalName().equals("domain:name=2,type=NB") && + if (name.getCanonicalName().equals("domain:name=2,type=NB") + && + subject != null + && subject.getPrincipals().contains(new JMXPrincipal("role"))) throw new SecurityException(); } } public class CustomJMXAuthenticator implements JMXAuthenticator { + @Override public Subject authenticate(Object credentials) { String role = ((String[]) credentials)[0]; echo("\nCreate principal with name = " + role); @@ -129,6 +145,7 @@ public class NotificationAccessControllerTest { public static class NB extends NotificationBroadcasterSupport implements NBMBean { + @Override public void emitNotification(int seqnum, ObjectName name) { if (name == null) { sendNotification(new Notification("nb", this, seqnum)); @@ -139,13 +156,20 @@ public class NotificationAccessControllerTest { } public class Listener implements NotificationListener { - public List notifs = new ArrayList(); + public final List notifs = new CopyOnWriteArrayList<>(); + + private final Semaphore s; + public Listener(Semaphore s) { + this.s = s; + } + @Override public void handleNotification(Notification n, Object h) { echo("handleNotification:"); echo("\tNotification = " + n); echo("\tNotification.SeqNum = " + n.getSequenceNumber()); echo("\tHandback = " + h); notifs.add(n); + s.release(); } } @@ -192,6 +216,17 @@ public class NotificationAccessControllerTest { JMXConnectorServer server = null; JMXConnector client = null; + /* + * (!enableChecks) + * - List must contain three notifs from sources nb1, nb2 and nb3 + * (enableChecks && !throwException) + * - List must contain one notif from source nb1 + * (enableChecks && throwException) + * - List must contain two notifs from sources nb2 and nb3 + */ + final int expected_notifs = + (!enableChecks ? 3 : (throwException ? 2 : 1)); + // Create a new MBeanServer // final MBeanServer mbs = MBeanServerFactory.createMBeanServer(); @@ -199,7 +234,7 @@ public class NotificationAccessControllerTest { try { // Create server environment map // - final Map env = new HashMap(); + final Map env = new HashMap<>(); env.put("jmx.remote.authenticator", new CustomJMXAuthenticator()); if (enableChecks) { env.put("com.sun.jmx.remote.notification.access.controller", @@ -222,7 +257,7 @@ public class NotificationAccessControllerTest { // Create server environment map // - final Map cenv = new HashMap(); + final Map cenv = new HashMap<>(); String[] credentials = new String[] { "role" , "password" }; cenv.put("jmx.remote.credentials", credentials); @@ -246,7 +281,9 @@ public class NotificationAccessControllerTest { // Add notification listener // - Listener li = new Listener(); + Semaphore s = new Semaphore(0); + + Listener li = new Listener(s); try { mbsc.addNotificationListener(nb1, li, null, null); if (enableChecks && throwException) { @@ -263,6 +300,9 @@ public class NotificationAccessControllerTest { } mbsc.addNotificationListener(nb2, li, null, null); + System.out.println("\n+++ Expecting to receive " + expected_notifs + + " notification" + (expected_notifs > 1 ? "s" : "") + + " +++"); // Invoke the "sendNotification" method // mbsc.invoke(nb1, "emitNotification", @@ -277,7 +317,7 @@ public class NotificationAccessControllerTest { // Wait for notifications to be emitted // - Thread.sleep(2000); + s.acquire(expected_notifs); // Remove notification listener // @@ -303,21 +343,7 @@ public class NotificationAccessControllerTest { sources.add(nb1); sources.add(nb2); sources.add(nb3); - if (!enableChecks) { - // List must contain three notifs from sources nb1, nb2 and nb3 - // - result = checkNotifs(3, li.notifs, sources); - } - if (enableChecks && !throwException) { - // List must contain one notif from source nb1 - // - result = checkNotifs(1, li.notifs, sources); - } - if (enableChecks && throwException) { - // List must contain two notifs from sources nb2 and nb3 - // - result = checkNotifs(2, li.notifs, sources); - } + result = checkNotifs(expected_notifs, li.notifs, sources); if (result > 0) { return result; } diff --git a/jdk/test/javax/net/ssl/HttpsURLConnection/Equals.java b/jdk/test/javax/net/ssl/HttpsURLConnection/Equals.java new file mode 100644 index 00000000000..0a482f31b90 --- /dev/null +++ b/jdk/test/javax/net/ssl/HttpsURLConnection/Equals.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 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. + * + * 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. + */ + +/** + * @test + * @library /lib/testlibrary + * @build jdk.testlibrary.SimpleSSLContext + * @run main Equals + * @bug 8055299 + */ + +import com.sun.net.httpserver.*; + +import java.net.*; +import java.util.*; +import java.io.*; +import javax.net.ssl.*; +import java.util.concurrent.*; +import jdk.testlibrary.SimpleSSLContext; + +public class Equals { + + static SSLContext ctx; + + public static void main (String[] args) throws Exception { + HttpsServer s2 = null; + ExecutorService executor=null; + try { + InetSocketAddress addr = new InetSocketAddress (0); + s2 = HttpsServer.create (addr, 0); + HttpHandler h = new Handler (); + HttpContext c2 = s2.createContext ("/test1", h); + executor = Executors.newCachedThreadPool(); + s2.setExecutor (executor); + ctx = new SimpleSSLContext().get(); + s2.setHttpsConfigurator(new HttpsConfigurator (ctx)); + s2.start(); + + int httpsport = s2.getAddress().getPort(); + test(httpsport); + System.out.println ("OK"); + } finally { + if (s2 != null) + s2.stop(2); + if (executor != null) + executor.shutdown (); + } + } + + static class Handler implements HttpHandler { + int invocation = 1; + public void handle (HttpExchange t) + throws IOException + { + InputStream is = t.getRequestBody(); + while (is.read () != -1) { + } + is.close(); + t.sendResponseHeaders (200, 0); + t.close(); + } + } + + static void test (int port) throws Exception { + URL url = new URL ("https://localhost:"+port+"/test1/"); + HttpsURLConnection urlcs = (HttpsURLConnection) url.openConnection(); + urlcs.setHostnameVerifier (new HostnameVerifier () { + public boolean verify (String s, SSLSession s1) { + return true; + } + }); + urlcs.setSSLSocketFactory (ctx.getSocketFactory()); + + InputStream is = urlcs.getInputStream(); + while (is.read() != -1) { + } + is.close(); + if (!urlcs.equals(urlcs)) { + throw new RuntimeException("Test failed"); + } + } +} diff --git a/jdk/test/javax/net/ssl/TLS/CipherTestUtils.java b/jdk/test/javax/net/ssl/TLS/CipherTestUtils.java new file mode 100644 index 00000000000..79a8db6ad42 --- /dev/null +++ b/jdk/test/javax/net/ssl/TLS/CipherTestUtils.java @@ -0,0 +1,687 @@ +/** + * Copyright (c) 2010, 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. + * + * 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. + */ + +import java.io.ByteArrayInputStream; +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.security.KeyFactory; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.Principal; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.UnrecoverableKeyException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPrivateKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509ExtendedKeyManager; +import javax.net.ssl.X509TrustManager; + +/** + * Test that all ciphersuites work in all versions and all client authentication + * types. The way this is setup the server is stateless and all checking is done + * on the client side. + */ + +public class CipherTestUtils { + + public static final int TIMEOUT = 20 * 1000; + public static final SecureRandom secureRandom = new SecureRandom(); + public static char[] PASSWORD = "passphrase".toCharArray(); + private static final List TESTS = new ArrayList<>(3); + private static final List EXCEPTIONS = new ArrayList<>(1); + private static final String CLIENT_PUBLIC_KEY + = "-----BEGIN CERTIFICATE-----\n" + + "MIICtTCCAh4CCQDkYJ46DMcGRjANBgkqhkiG9w0BAQUFADCBnDELMAkGA1UEBhMC\n" + + "VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MR8wHQYDVQQK\n" + + "DBZTdW4gTWljcm9zeXN0ZW1zLCBJbmMuMSYwJAYDVQQLDB1TdW4gTWljcm9zeXN0\n" + + "ZW1zIExhYm9yYXRvcmllczEfMB0GA1UEAwwWVGVzdCBDQSAoMTAyNCBiaXQgUlNB\n" + + "KTAeFw0wOTA0MjcwNDA0MDhaFw0xMzA2MDUwNDA0MDhaMIGgMQswCQYDVQQGEwJV\n" + + "UzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxHzAdBgNVBAoM\n" + + "FlN1biBNaWNyb3N5c3RlbXMsIEluYy4xJjAkBgNVBAsMHVN1biBNaWNyb3N5c3Rl\n" + + "bXMgTGFib3JhdG9yaWVzMSMwIQYDVQQDDBpUZXN0IENsaWVudCAoMTAyNCBiaXQg\n" + + "UlNBKTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAm5rwjmhO7Nwd5GWs+KvQ\n" + + "UnDiqpRDvRriOUFdF0rCI2Op24C+iwUMDGxPsgP7VkUpOdJhw3c72aP0CAWcZ5dN\n" + + "UCW7WVDAxnogCahLCir1jjoGdEjiNGOy0L9sypsM9UvBzJN8uvXsxsTZX4Z88cKU\n" + + "G7RUvN8LQ88zDljk5zr3c2MCAwEAATANBgkqhkiG9w0BAQUFAAOBgQA7LUDrzHln\n" + + "EXuGmwZeeroACB6DVtkClMskF/Pj5GnTxoeNN9DggycX/eOeIDKRloHuMpBeZPJH\n" + + "NUwFu4LB6HBDeldQD9iRp8zD/fPakOdN+1Gk5hciIZZJ5hQmeCl7Va2Gr64vUqZG\n" + + "MkVU755t+7ByLgzWuhPhhsX9QCuPR5FjvQ==\n" + + "-----END CERTIFICATE-----"; + + private static final String CLIENT_PRIVATE_KEY + = "-----BEGIN PRIVATE KEY-----\n" + + "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJua8I5oTuzcHeRl\n" + + "rPir0FJw4qqUQ70a4jlBXRdKwiNjqduAvosFDAxsT7ID+1ZFKTnSYcN3O9mj9AgF\n" + + "nGeXTVAlu1lQwMZ6IAmoSwoq9Y46BnRI4jRjstC/bMqbDPVLwcyTfLr17MbE2V+G\n" + + "fPHClBu0VLzfC0PPMw5Y5Oc693NjAgMBAAECgYA5w73zj8Nk6J3sMNaShe3S/PcY\n" + + "TewLopRCnwI46FbDnnbq9pNFtnzvi7HWKuY983THc1M5peTA+b1Y0QRr7F4Vg4x9\n" + + "9UM0B/tZcIIcJJ3LS+9fXKCbYLQWq5F05JqeZu+i+QLmJFO5+2p7laeQ4oQfW7QE\n" + + "YR4u2mSaLe0SsqHvOQJBAMhgcye9C6pJO0eo2/VtRxAXI7zxNAIjHwKo1cva7bhu\n" + + "GdrMaEAJBAsMJ1GEk7/WDI+3KEbTjQdfIJuAvOR4FXUCQQDGzNn/tl2k93v/ugyM\n" + + "/tBhCKDipYDIbyJMoG2AOtOGmCsiGo5L7idO4OAcm/QiHBQMXjFIVgTUcH8MhGj4\n" + + "blJ3AkA5fUqsxRV6tuYWKkFpif/QgwMS65VDY7Y6+hvVECwSNSyf1PO4I54QWV1S\n" + + "ixok+RHDjgY1Q+77hXSCiQ4o8rcdAkBHvjfR+5sx5IpgUGElJPRIgFenU3j1XH3x\n" + + "T1gVFaWuhg3S4eiGaGzRH4BhcrqY8K8fg4Kfi0N08yA2gTZsqUujAkEAjuNPTuKx\n" + + "ti0LXI09kbGUqOpRMm1zW5TD6LFeEaUN6oxrSZI2YUvu7VyotAqsxX5O0u0f3VQw\n" + + "ySF0Q1oZ6qu7cg==\n" + + "-----END PRIVATE KEY-----"; + private static final String SERVER_PUBLIC_KEY + = "-----BEGIN CERTIFICATE-----\n" + + "MIICtTCCAh4CCQDkYJ46DMcGRTANBgkqhkiG9w0BAQUFADCBnDELMAkGA1UEBhMC\n" + + "VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MR8wHQYDVQQK\n" + + "DBZTdW4gTWljcm9zeXN0ZW1zLCBJbmMuMSYwJAYDVQQLDB1TdW4gTWljcm9zeXN0\n" + + "ZW1zIExhYm9yYXRvcmllczEfMB0GA1UEAwwWVGVzdCBDQSAoMTAyNCBiaXQgUlNB\n" + + "KTAeFw0wOTA0MjcwNDA0MDhaFw0xMzA2MDUwNDA0MDhaMIGgMQswCQYDVQQGEwJV\n" + + "UzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxHzAdBgNVBAoM\n" + + "FlN1biBNaWNyb3N5c3RlbXMsIEluYy4xJjAkBgNVBAsMHVN1biBNaWNyb3N5c3Rl\n" + + "bXMgTGFib3JhdG9yaWVzMSMwIQYDVQQDDBpUZXN0IFNlcnZlciAoMTAyNCBiaXQg\n" + + "UlNBKTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArsHHeZ1O67yuxQKDSAOC\n" + + "Xm271ViwBrXkxe5cvhG8MCCem6Z3XeZ/m6c2ucRwLaQxnmG1m0G6/OYaUXTivjcG\n" + + "/K4bc1I+yjghAWQNLBtsOiP9w0LKibg3TSDehpeuuz/lmB5A4HMqQr8KkY4K7peD\n" + + "1QkJ2Dn3zhbwQ/0d8f5CCbkCAwEAATANBgkqhkiG9w0BAQUFAAOBgQBOd8XojEnu\n" + + "eTUHBwqfmnvRQvbICFDNbbL4KuX/JNPSy1WMGAEbNCTLZ+5yP69js8aUYqAk5vVf\n" + + "dWRLU3MDiEzW7zxE1ubuKWjVuyGbG8Me0G01Hw+evBcZqB64Fz3OFISVfQh7MqE/\n" + + "O0AeakRMH350FRLNl4o6KBSXmF/AADfqQQ==\n" + + "-----END CERTIFICATE-----"; + + private static final String SERVER_PRIVATE_KEY + = "-----BEGIN PRIVATE KEY-----\n" + + "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAK7Bx3mdTuu8rsUC\n" + + "g0gDgl5tu9VYsAa15MXuXL4RvDAgnpumd13mf5unNrnEcC2kMZ5htZtBuvzmGlF0\n" + + "4r43BvyuG3NSPso4IQFkDSwbbDoj/cNCyom4N00g3oaXrrs/5ZgeQOBzKkK/CpGO\n" + + "Cu6Xg9UJCdg5984W8EP9HfH+Qgm5AgMBAAECgYAXUv+3qJo+9mjxHHu/IdDFn6nB\n" + + "ONwNmTtWe5DfQWi3l7LznU0zOC9x6+hu9NvwC4kf1XSyqxw04tVCZ/JXZurEmEBz\n" + + "YtcQ5idRQDkKYXEDOeVUfvtHO6xilzrhPKxxd0GG/sei2pozikkqnYF3OcP0qL+a\n" + + "3nWixZQBRoF2nIRLcQJBAN97TJBr0XTRmE7OCKLUy1+ws7vZB9uQ2efHMsgwOpsY\n" + + "3cEW5qd95hrxLU72sBeu9loHQgBrT2Q3OAxnsPXmgO0CQQDIL3u9kS/O3Ukx+n1H\n" + + "JdPFQCRxrDm/vtJpQEmq+mLqxxnxCFRIYQ2ieAPokBxWeMDtdWJGD3VxhahjPfZm\n" + + "5K59AkEAuDVl0tVMfUIWjT5/F9jXGjUIsZofQ/iN5OLpFOHMLPO+Nd6umPjJpwON\n" + + "GT11wM/S+DprSPUrJ6vsYy1FTCuHsQJBAMXtnO07xgdE6AAQaRmVnyMiXmY+IQMj\n" + + "CyuhsrToyDDWFyIoWB0QSMjg3QxuoHYnAqpGK5qV4ksSGgG13BCz/okCQQCRHTgn\n" + + "DuFG2f7GYLFjI4NaTEzHGp+J9LiNYY1kYYLonpwAC3Z5hzJVanYT3/g23AUZ/fdF\n" + + "v5PDIViuPo5ZB1eD\n" + + "-----END PRIVATE KEY-----"; + + private static final String CA_PUBLIC_KEY + = "-----BEGIN CERTIFICATE-----\n" + + "MIIDCDCCAnGgAwIBAgIJAIYlGfwNBY6NMA0GCSqGSIb3DQEBBQUAMIGcMQswCQYD\n" + + "VQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxHzAd\n" + + "BgNVBAoMFlN1biBNaWNyb3N5c3RlbXMsIEluYy4xJjAkBgNVBAsMHVN1biBNaWNy\n" + + "b3N5c3RlbXMgTGFib3JhdG9yaWVzMR8wHQYDVQQDDBZUZXN0IENBICgxMDI0IGJp\n" + + "dCBSU0EpMB4XDTA5MDQyNzA0MDQwOFoXDTEzMDYwNTA0MDQwOFowgZwxCzAJBgNV\n" + + "BAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEfMB0G\n" + + "A1UECgwWU3VuIE1pY3Jvc3lzdGVtcywgSW5jLjEmMCQGA1UECwwdU3VuIE1pY3Jv\n" + + "c3lzdGVtcyBMYWJvcmF0b3JpZXMxHzAdBgNVBAMMFlRlc3QgQ0EgKDEwMjQgYml0\n" + + "IFJTQSkwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOK4DJxxb0XX6MJ1CVjp\n" + + "9Gmr/Ua8MS12R58F9lDpSKuq8cFexA4W7OdZ4jtbKv0tRHX5YxmbnXedwS+gdcOA\n" + + "GRgXMoeXlgTFGpdL+TR8xKIlMGRSjnR7MpR2tRyIYI2p+UTEiD6LTlIm5Wh4z1q8\n" + + "LYbxyMVD1XNNNymvPM44OjsBAgMBAAGjUDBOMB0GA1UdDgQWBBT27BLUflmfdtbi\n" + + "WTgjwWnoxop2MTAfBgNVHSMEGDAWgBT27BLUflmfdtbiWTgjwWnoxop2MTAMBgNV\n" + + "HRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBAEQELNzhZpjnSgigd+QJ6I/3CPDo\n" + + "SDkMLdP1BHlT/DkMIZvABm+M09ePNlWiLYCNCsL9nWmX0gw0rFDKsTklZyKTUzaM\n" + + "oy/AZCrAaoIc6SO5m1xE1RMyVxd/Y/kg6cbfWxxCJFlMeU5rsSdC97HTE/lDyuoh\n" + + "BmlOBB7SdR+1ScjA\n" + + "-----END CERTIFICATE-----"; + + private static final String CA_PRIVATE_KEY + = "-----BEGIN PRIVATE KEY-----\n" + + "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAOK4DJxxb0XX6MJ1\n" + + "CVjp9Gmr/Ua8MS12R58F9lDpSKuq8cFexA4W7OdZ4jtbKv0tRHX5YxmbnXedwS+g\n" + + "dcOAGRgXMoeXlgTFGpdL+TR8xKIlMGRSjnR7MpR2tRyIYI2p+UTEiD6LTlIm5Wh4\n" + + "z1q8LYbxyMVD1XNNNymvPM44OjsBAgMBAAECgYEApmMOlk3FrQtsvjGof4GLp3Xa\n" + + "tmvs54FzxKhagj0C4UHelNyYpAJ9MLjNiGQ7I31yTeaNrUCAi0XSfsKTSrwbLSnJ\n" + + "qsUPKMBrnzcWrOyui2+cupHZXaTlNeYB97teLJYpa6Ql9CZLoTHoim1+//s7diBh\n" + + "03Vls+M6Poi5PMvv59UCQQD+k/BiokmbBgWHfBY5cZSlx3Z4VTwSHJmHDTO3Tjso\n" + + "EVErXUSVvqD/KHX6eM4VPM8lySV5djWV8lDsESCWMtiLAkEA4/xFNsiOLMQpxW/O\n" + + "bt2tukxJkAxldD4lPoFZR+zbXtMtt8OjERtX2wD+nj6h7jfIeSyVuBEcBN8Uj8xe\n" + + "kgfgIwJAPbKG4LCqHAsCjgpRrIxNVTwZByLJEy6hOqzFathn19cSj+rjs1Lm28/n\n" + + "f9OFRnpdTbAJB/3REM0QNZYVCrG57wJBAN0KuTytZJNouaswhPCew5Kt5mDgc/kp\n" + + "S8j3dk2zCto8W8Ygy1iJrzuqEjPxO+UQdrFtlde51vWuKGxnVIW3VwsCQEldqk7r\n" + + "8y7PgquPP+k3L0OXno5wGBrPcW1+U0mhIZGnwSzE4SPX2ddqUSEUA/Av4RjAckL/\n" + + "fpqmCkpTanyYW9U=\n" + + "-----END PRIVATE KEY-----"; + + private final SSLSocketFactory factory; + private final X509ExtendedKeyManager clientKeyManager; + private final X509ExtendedKeyManager serverKeyManager; + private final X509TrustManager clientTrustManager; + private final X509TrustManager serverTrustManager; + + static abstract class Server implements Runnable { + + final CipherTestUtils cipherTest; + + Server(CipherTestUtils cipherTest) throws Exception { + this.cipherTest = cipherTest; + } + + @Override + public abstract void run(); + + void handleRequest(InputStream in, OutputStream out) + throws IOException { + boolean newline = false; + StringBuilder sb = new StringBuilder(); + while (true) { + int ch = in.read(); + if (ch < 0) { + throw new EOFException(); + } + sb.append((char) ch); + if (ch == '\r') { + // empty + } else if (ch == '\n') { + if (newline) { + // 2nd newline in a row, end of request + break; + } + newline = true; + } else { + newline = false; + } + } + String request = sb.toString(); + if (request.startsWith("GET / HTTP/1.") == false) { + throw new IOException("Invalid request: " + request); + } + out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes()); + out.write("Tested Scenario: ".getBytes()); + TestParameters tp = (TestParameters) CipherTestUtils.TESTS.get(0); + out.write(tp.toString().getBytes()); + out.write(" Test PASSED.".getBytes()); + } + } + + public static class TestParameters { + + String cipherSuite; + String protocol; + String clientAuth; + + TestParameters(String cipherSuite, String protocol, + String clientAuth) { + this.cipherSuite = cipherSuite; + this.protocol = protocol; + this.clientAuth = clientAuth; + } + + boolean isEnabled() { + return true; + } + + @Override + public String toString() { + String s = cipherSuite + " in " + protocol + " mode"; + if (clientAuth != null) { + s += " with " + clientAuth + " client authentication"; + } + return s; + } + } + + private static volatile CipherTestUtils instnace = null; + + public static CipherTestUtils getInstance() throws IOException, + FileNotFoundException, KeyStoreException, + NoSuchAlgorithmException, CertificateException, + UnrecoverableKeyException, InvalidKeySpecException { + if (instnace == null) { + synchronized (CipherTestUtils.class) { + if (instnace == null) { + instnace = new CipherTestUtils(); + } + } + } + return instnace; + } + + public static void setTestedArguments(String testedProtocol, + String testedCipherSuite) { + + TestParameters testedParams; + + String cipherSuite = testedCipherSuite.trim(); + if (cipherSuite.startsWith("SSL_")) { + testedParams = + new TestParameters(cipherSuite, testedProtocol, null); + TESTS.add(testedParams); + + } else { + System.out.println("Your input Cipher suites is not correct, " + + "please try another one ."); + } + } + + public X509ExtendedKeyManager getClientKeyManager() { + return clientKeyManager; + } + + public X509TrustManager getClientTrustManager() { + return clientTrustManager; + } + + public X509ExtendedKeyManager getServerKeyManager() { + return serverKeyManager; + } + + public X509TrustManager getServerTrustManager() { + return serverTrustManager; + } + + public static void addFailure(Exception e) { + EXCEPTIONS.add(e); + } + + private CipherTestUtils() + throws IOException, FileNotFoundException, KeyStoreException, + NoSuchAlgorithmException, CertificateException, + UnrecoverableKeyException, InvalidKeySpecException { + factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); + KeyStore serverKeyStore = createServerKeyStore(SERVER_PUBLIC_KEY, + SERVER_PRIVATE_KEY); + KeyStore serverTrustStore = createServerKeyStore(CA_PUBLIC_KEY, + CA_PRIVATE_KEY); + + if (serverKeyStore != null) { + KeyManagerFactory keyFactory1 + = KeyManagerFactory.getInstance( + KeyManagerFactory.getDefaultAlgorithm()); + keyFactory1.init(serverKeyStore, PASSWORD); + serverKeyManager = (X509ExtendedKeyManager) keyFactory1. + getKeyManagers()[0]; + } else { + serverKeyManager = null; + } + serverTrustManager = serverTrustStore != null + ? new AlwaysTrustManager(serverTrustStore) : null; + + KeyStore clientKeyStore, clientTrustStore; + clientTrustStore = serverTrustStore; + clientKeyStore = + createServerKeyStore(CLIENT_PUBLIC_KEY,CLIENT_PRIVATE_KEY); + if (clientKeyStore != null) { + KeyManagerFactory keyFactory + = KeyManagerFactory.getInstance( + KeyManagerFactory.getDefaultAlgorithm()); + keyFactory.init(clientKeyStore, PASSWORD); + clientKeyManager = (X509ExtendedKeyManager) keyFactory. + getKeyManagers()[0]; + } else { + clientKeyManager = null; + } + clientTrustManager = (clientTrustStore != null) + ? new AlwaysTrustManager(clientTrustStore) : null; + } + + void checkResult(String exception) throws Exception { + if (EXCEPTIONS.size() >= 1) { + Exception actualException = EXCEPTIONS.get(0); + if (exception == null) { + throw new RuntimeException("FAILED: got unexpected exception: " + + actualException); + } + if (!exception.equals(actualException.getClass().getName())) { + throw new RuntimeException("FAILED: got unexpected exception: " + + actualException); + } + + System.out.println("PASSED: got expected exception: " + + actualException); + } else { + if (exception != null) { + throw new RuntimeException("FAILED: " + exception + + " was expected"); + } + System.out.println("PASSED"); + } + } + + SSLSocketFactory getFactory() { + return factory; + } + + static abstract class Client implements Runnable { + + final CipherTestUtils cipherTest; + TestParameters testedParams; + + Client(CipherTestUtils cipherTest) throws Exception { + this.cipherTest = cipherTest; + } + + Client(CipherTestUtils cipherTest, + String testedCipherSuite) throws Exception { + this.cipherTest = cipherTest; + } + + @Override + public final void run() { + + TESTS.stream().map((params) -> { + if (!params.isEnabled()) { + System.out.println("Skipping disabled test " + params); + } + return params; + }).forEach((params) -> { + try { + runTest(params); + System.out.println("Passed " + params); + } catch (Exception e) { + CipherTestUtils.addFailure(e); + System.out.println("** Failed " + params + + "**, got exception:"); + e.printStackTrace(System.err); + } + }); + } + + abstract void runTest(TestParameters params) throws Exception; + + void sendRequest(InputStream in, OutputStream out) throws IOException { + out.write("GET / HTTP/1.0\r\n\r\n".getBytes()); + out.flush(); + StringBuilder sb = new StringBuilder(); + while (true) { + int ch = in.read(); + if (ch < 0) { + break; + } + sb.append((char) ch); + } + String response = sb.toString(); + if (response.startsWith("HTTP/1.0 200 ") == false) { + throw new IOException("Invalid response: " + response); + } else { + System.out.println(); + System.out.println("--- Response --- "); + System.out.println(response); + System.out.println("---------------- "); + } + } + } + + public static void printStringArray(String[] stringArray) { + System.out.print(stringArray.length + " : "); + for (String stringArray1 : stringArray) { + System.out.print(stringArray1); + System.out.print(","); + } + System.out.println(); + } + + public static void printInfo(SSLServerSocket socket) { + System.out.println(); + System.out.println("--- SSL ServerSocket Info ---"); + System.out.print("SupportedProtocols : "); + printStringArray(socket.getSupportedProtocols()); + System.out.print("SupportedCipherSuites : "); + printStringArray(socket.getSupportedCipherSuites()); + System.out.print("EnabledProtocols : "); + printStringArray(socket.getEnabledProtocols()); + System.out.print("EnabledCipherSuites : "); + String[] supportedCipherSuites = socket.getEnabledCipherSuites(); + Arrays.sort(supportedCipherSuites); + printStringArray(supportedCipherSuites); + System.out.println("NeedClientAuth : " + + socket.getNeedClientAuth()); + System.out.println("WantClientAuth : " + + socket.getWantClientAuth()); + System.out.println("-----------------------"); + } + + public static void printInfo(SSLSocket socket) { + System.out.println(); + System.out.println("--- SSL Socket Info ---"); + System.out.print(" SupportedProtocols : "); + printStringArray(socket.getSupportedProtocols()); + System.out.println(" EnabledProtocols : " + + socket.getEnabledProtocols()[0]); + System.out.print(" SupportedCipherSuites : "); + String[] supportedCipherSuites = socket.getEnabledCipherSuites(); + Arrays.sort(supportedCipherSuites); + printStringArray(supportedCipherSuites); + System.out.println(" EnabledCipherSuites : " + + socket.getEnabledCipherSuites()[0]); + System.out.println(" NeedClientAuth : " + + socket.getNeedClientAuth()); + System.out.println(" WantClientAuth : " + + socket.getWantClientAuth()); + System.out.println("-----------------------"); + } + + private static KeyStore createServerKeyStore(String publicKeyStr, + String keySpecStr) throws KeyStoreException, IOException, + NoSuchAlgorithmException, CertificateException, + InvalidKeySpecException { + + KeyStore ks = KeyStore.getInstance("JKS"); + ks.load(null, null); + if (publicKeyStr == null || keySpecStr == null) { + throw new IllegalArgumentException("publicKeyStr or " + + "keySpecStr cannot be null"); + } + String strippedPrivateKey = keySpecStr.substring( + keySpecStr.indexOf("\n"), keySpecStr.lastIndexOf("\n")); + + // generate the private key. + PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( + Base64.getMimeDecoder().decode(strippedPrivateKey)); + KeyFactory kf = KeyFactory.getInstance("RSA"); + RSAPrivateKey priKey + = (RSAPrivateKey) kf.generatePrivate(priKeySpec); + + // generate certificate chain + try (InputStream is = + new ByteArrayInputStream(publicKeyStr.getBytes())) { + // generate certificate from cert string + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + Certificate keyCert = cf.generateCertificate(is); + Certificate[] chain = {keyCert}; + ks.setKeyEntry("TestEntry", priKey, PASSWORD, chain); + } + + return ks; + } + + public static void main(PeerFactory peerFactory, String mode, + String expectedException) + throws Exception { + long time = System.currentTimeMillis(); + setTestedArguments(peerFactory.getTestedProtocol(), + peerFactory.getTestedCipher()); + + System.out.print( + " Initializing test '" + peerFactory.getName() + "'..."); + secureRandom.nextInt(); + + CipherTestUtils cipherTest = CipherTestUtils.getInstance(); + if (mode.equalsIgnoreCase("Server")) { // server mode + Thread serverThread = new Thread(peerFactory.newServer(cipherTest), + "Server"); + serverThread.start(); + } else if (mode.equalsIgnoreCase("Client")) { + peerFactory.newClient(cipherTest).run(); + cipherTest.checkResult(expectedException); + JSSEServer.closeServer = true; + } else { + throw new RuntimeException("unsupported mode"); + } + time = System.currentTimeMillis() - time; + System.out.println("Elapsed time " + time); + + } + + public static abstract class PeerFactory { + + abstract String getName(); + + abstract String getTestedProtocol(); + + abstract String getTestedCipher(); + + abstract Client newClient(CipherTestUtils cipherTest) throws Exception; + + abstract Server newServer(CipherTestUtils cipherTest) throws Exception; + + boolean isSupported(String cipherSuite) { + return true; + } + } +} + +class AlwaysTrustManager implements X509TrustManager { + + X509TrustManager trustManager; + + public AlwaysTrustManager(KeyStore keyStore) + throws NoSuchAlgorithmException, KeyStoreException { + + TrustManagerFactory tmf + = TrustManagerFactory.getInstance(TrustManagerFactory. + getDefaultAlgorithm()); + tmf.init(keyStore); + + TrustManager tms[] = tmf.getTrustManagers(); + for (TrustManager tm : tms) { + trustManager = (X509TrustManager) tm; + return; + } + + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + try { + trustManager.checkClientTrusted(chain, authType); + } catch (CertificateException excep) { + System.out.println("ERROR in client trust manager"); + } + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + try { + trustManager.checkServerTrusted(chain, authType); + } catch (CertificateException excep) { + System.out.println("ERROR in server Trust manger"); + } + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return trustManager.getAcceptedIssuers(); + } +} + +class MyX509KeyManager extends X509ExtendedKeyManager { + + private final X509ExtendedKeyManager keyManager; + private String authType; + + MyX509KeyManager(X509ExtendedKeyManager keyManager) { + this.keyManager = keyManager; + } + + void setAuthType(String authType) { + this.authType = "ECDSA".equals(authType) ? "EC" : authType; + } + + @Override + public String[] getClientAliases(String keyType, Principal[] issuers) { + if (authType == null) { + return null; + } + return keyManager.getClientAliases(authType, issuers); + } + + @Override + public String chooseClientAlias(String[] keyType, Principal[] issuers, + Socket socket) { + if (authType == null) { + return null; + } + return keyManager.chooseClientAlias(new String[]{authType}, + issuers, socket); + } + + @Override + public String chooseEngineClientAlias(String[] keyType, + Principal[] issuers, SSLEngine engine) { + if (authType == null) { + return null; + } + return keyManager.chooseEngineClientAlias(new String[]{authType}, + issuers, engine); + } + + @Override + public String[] getServerAliases(String keyType, Principal[] issuers) { + throw new UnsupportedOperationException("Servers not supported"); + } + + @Override + public String chooseServerAlias(String keyType, Principal[] issuers, + Socket socket) { + throw new UnsupportedOperationException("Servers not supported"); + } + + @Override + public String chooseEngineServerAlias(String keyType, Principal[] issuers, + SSLEngine engine) { + throw new UnsupportedOperationException("Servers not supported"); + } + + @Override + public X509Certificate[] getCertificateChain(String alias) { + return keyManager.getCertificateChain(alias); + } + + @Override + public PrivateKey getPrivateKey(String alias) { + return keyManager.getPrivateKey(alias); + } +} diff --git a/jdk/test/javax/net/ssl/TLS/JSSEClient.java b/jdk/test/javax/net/ssl/TLS/JSSEClient.java new file mode 100644 index 00000000000..b08ae917249 --- /dev/null +++ b/jdk/test/javax/net/ssl/TLS/JSSEClient.java @@ -0,0 +1,120 @@ +/** + * Copyright (c) 2010, 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. + * + * 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. + */ + +import java.io.InputStream; +import java.io.OutputStream; +import java.security.cert.Certificate; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; + +class JSSEClient extends CipherTestUtils.Client { + + private static final String DEFAULT = "DEFAULT"; + private static final String TLS = "TLS"; + + private final SSLContext sslContext; + private final MyX509KeyManager keyManager; + private final int serverPort; + private final String serverHost; + private final String testedProtocol; + + JSSEClient(CipherTestUtils cipherTest, String serverHost, int serverPort, + String testedProtocols, String testedCipherSuite) throws Exception { + super(cipherTest, testedCipherSuite); + this.serverHost = serverHost; + this.serverPort = serverPort; + this.testedProtocol = testedProtocols; + this.keyManager = + new MyX509KeyManager(cipherTest.getClientKeyManager()); + sslContext = SSLContext.getInstance(TLS); + } + + @Override + void runTest(CipherTestUtils.TestParameters params) throws Exception { + SSLSocket socket = null; + try { + System.out.println("Connecting to server..."); + keyManager.setAuthType(params.clientAuth); + sslContext.init(new KeyManager[]{keyManager}, + new TrustManager[]{cipherTest.getClientTrustManager()}, + CipherTestUtils.secureRandom); + SSLSocketFactory factory = (SSLSocketFactory) sslContext. + getSocketFactory(); + socket = (SSLSocket) factory.createSocket(serverHost, + serverPort); + socket.setSoTimeout(CipherTestUtils.TIMEOUT); + socket.setEnabledCipherSuites(params.cipherSuite.split(",")); + if (params.protocol != null && !params.protocol.trim().equals("") + && !params.protocol.trim().equals(DEFAULT)) { + socket.setEnabledProtocols(params.protocol.split(",")); + } + CipherTestUtils.printInfo(socket); + InputStream in = socket.getInputStream(); + OutputStream out = socket.getOutputStream(); + sendRequest(in, out); + SSLSession session = socket.getSession(); + session.invalidate(); + String cipherSuite = session.getCipherSuite(); + if (params.cipherSuite.equals(cipherSuite) == false) { + throw new RuntimeException("Negotiated ciphersuite mismatch: " + + cipherSuite + " != " + params.cipherSuite); + } + String protocol = session.getProtocol(); + if (!DEFAULT.equals(params.protocol) + && !params.protocol.contains(protocol)) { + throw new RuntimeException("Negotiated protocol mismatch: " + + protocol + " != " + params.protocol); + } + if (!cipherSuite.contains("DH_anon")) { + session.getPeerCertificates(); + } + Certificate[] certificates = session.getLocalCertificates(); + if (params.clientAuth == null) { + if (certificates != null) { + throw new RuntimeException("Local certificates " + + "should be null"); + } + } else { + if ((certificates == null) || (certificates.length == 0)) { + throw new RuntimeException("Certificates missing"); + } + String keyAlg = certificates[0].getPublicKey().getAlgorithm(); + if ("EC".equals(keyAlg)) { + keyAlg = "ECDSA"; + } + if (params.clientAuth == null ? keyAlg != null + : !params.clientAuth.equals(keyAlg)) { + throw new RuntimeException("Certificate type mismatch: " + + keyAlg + " != " + params.clientAuth); + } + } + } finally { + if (socket != null) { + socket.close(); + } + } + } +} diff --git a/jdk/test/javax/net/ssl/TLS/JSSEServer.java b/jdk/test/javax/net/ssl/TLS/JSSEServer.java new file mode 100644 index 00000000000..f6e55a31706 --- /dev/null +++ b/jdk/test/javax/net/ssl/TLS/JSSEServer.java @@ -0,0 +1,80 @@ +/** + * Copyright (c) 2010, 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. + * + * 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. + */ + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManager; + +public class JSSEServer extends CipherTestUtils.Server { + + private final SSLServerSocket serverSocket; + private final int serverPort; + static volatile boolean closeServer = false; + + JSSEServer(CipherTestUtils cipherTest, int serverPort, + String protocol, String cipherSuite) throws Exception { + super(cipherTest); + this.serverPort = serverPort; + SSLContext serverContext = SSLContext.getInstance("TLS"); + serverContext.init(new KeyManager[]{cipherTest.getServerKeyManager()}, + new TrustManager[]{cipherTest.getServerTrustManager()}, + CipherTestUtils.secureRandom); + SSLServerSocketFactory factory = + (SSLServerSocketFactory)serverContext.getServerSocketFactory(); + serverSocket = + (SSLServerSocket) factory.createServerSocket(serverPort); + serverSocket.setEnabledProtocols(protocol.split(",")); + serverSocket.setEnabledCipherSuites(cipherSuite.split(",")); + + CipherTestUtils.printInfo(serverSocket); + } + + @Override + public void run() { + System.out.println("JSSE Server listening on port " + serverPort); + while (!closeServer) { + try (final SSLSocket socket = (SSLSocket) serverSocket.accept()) { + socket.setSoTimeout(CipherTestUtils.TIMEOUT); + + try (InputStream in = socket.getInputStream(); + OutputStream out = socket.getOutputStream()) { + handleRequest(in, out); + out.flush(); + } catch (IOException e) { + CipherTestUtils.addFailure(e); + System.out.println("Got IOException:"); + e.printStackTrace(System.err); + } + } catch (Exception e) { + CipherTestUtils.addFailure(e); + System.out.println("Exception:"); + e.printStackTrace(System.err); + } + } + } +} diff --git a/jdk/test/javax/net/ssl/TLS/TestJSSE.java b/jdk/test/javax/net/ssl/TLS/TestJSSE.java new file mode 100644 index 00000000000..ab3fecf18af --- /dev/null +++ b/jdk/test/javax/net/ssl/TLS/TestJSSE.java @@ -0,0 +1,184 @@ +/** + * Copyright (c) 2010, 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. + * + * 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. + */ + +import static java.lang.System.out; +import java.security.Provider; +import java.security.Security; + +/** + * @test + * @bug 8049429 + * @library ../../../../lib/testlibrary/ + * @build jdk.testlibrary.Utils + * @compile CipherTestUtils.java JSSEClient.java JSSEServer.java + * @summary Test that all cipher suites work in all versions and all client + * authentication types. The way this is setup the server is stateless and + * all checking is done on the client side. + * @run main/othervm -DSERVER_PROTOCOL=SSLv3 + * -DCLIENT_PROTOCOL=SSLv3 + * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE + * @run main/othervm -DSERVER_PROTOCOL=TLSv1 + * -DCLIENT_PROTOCOL=SSLv3,TLSv1,TLSv1.1,TLSv1.2 + * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE + * @run main/othervm -DSERVER_PROTOCOL=TLSv1.1 + * -DCLIENT_PROTOCOL=SSLv3,TLSv1,TLSv1.1,TLSv1.2 + * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE + * @run main/othervm -DSERVER_PROTOCOL=TLSv1.2 + * -DCLIENT_PROTOCOL=SSLv3,TLSv1,TLSv1.1,TLSv1.2 + * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE + * @run main/othervm -DSERVER_PROTOCOL=SSLv3,TLSv1 + * -DCLIENT_PROTOCOL=TLSv1 -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE + * @run main/othervm -DSERVER_PROTOCOL=SSLv3,TLSv1,TLSv1.1 + * -DCLIENT_PROTOCOL=TLSv1.1 -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE + * @run main/othervm -DSERVER_PROTOCOL=SSLv3 + * -DCLIENT_PROTOCOL=TLSv1.1,TLSv1.2 + * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 + * TestJSSE javax.net.ssl.SSLHandshakeException + * @run main/othervm -DSERVER_PROTOCOL=TLSv1 + * -DCLIENT_PROTOCOL=TLSv1.1,TLSv1.2 + * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 + * TestJSSE javax.net.ssl.SSLHandshakeException + * @run main/othervm -DSERVER_PROTOCOL=SSLv3,TLSv1,TLSv1.1,TLSv1.2 + * -DCLIENT_PROTOCOL=TLSv1.2 -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE + * @run main/othervm -DSERVER_PROTOCOL=SSLv2Hello,SSLv3,TLSv1 + * -DCLIENT_PROTOCOL=DEFAULT -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE + * @run main/othervm -DSERVER_PROTOCOL=SSLv2Hello,SSLv3,TLSv1,TLSv1.1,TLSv1.2 + * -DCLIENT_PROTOCOL=DEFAULT -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE + * @run main/othervm -DSERVER_PROTOCOL=SSLv2Hello,SSLv3,TLSv1,TLSv1.1,TLSv1.2 + * -DCLIENT_PROTOCOL=DEFAULT -Djdk.tls.client.protocols=TLSv1 + * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 TestJSSE + * @run main/othervm -DSERVER_PROTOCOL=SSLv2Hello,SSLv3,TLSv1 + * -DCLIENT_PROTOCOL=DEFAULT -Djdk.tls.client.protocols=TLSv1.2 + * -DCIPHER=SSL_RSA_WITH_RC4_128_MD5 + * TestJSSE javax.net.ssl.SSLHandshakeException + * + */ + +public class TestJSSE { + + private static final String LOCAL_IP = "127.0.0.1"; + + public static void main(String... args) throws Exception { + String serverProtocol = System.getProperty("SERVER_PROTOCOL"); + String clientProtocol = System.getProperty("CLIENT_PROTOCOL"); + int port = jdk.testlibrary.Utils.getFreePort(); + String cipher = System.getProperty("CIPHER"); + if (serverProtocol == null + || clientProtocol == null + || cipher == null) { + throw new IllegalArgumentException("SERVER_PROTOCOL " + + "or CLIENT_PROTOCOL or CIPHER is missing"); + } + out.println("ServerProtocol =" + serverProtocol); + out.println("ClientProtocol =" + clientProtocol); + out.println("Cipher =" + cipher); + server(serverProtocol, cipher, port, args); + client(port, clientProtocol, cipher, args); + + } + + public static void client(int testPort, + String testProtocols, String testCipher, + String... exception) throws Exception { + String expectedException = exception.length >= 1 + ? exception[0] : null; + out.println("========================================="); + out.println(" Testing - https://" + LOCAL_IP + ":" + testPort); + out.println(" Testing - Protocol : " + testProtocols); + out.println(" Testing - Cipher : " + testCipher); + Provider p = new sun.security.ec.SunEC(); + Security.insertProviderAt(p, 1); + try { + CipherTestUtils.main(new JSSEFactory(LOCAL_IP, + testPort, testProtocols, + testCipher, "client JSSE"), + "client", expectedException); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static void server(String testProtocol, String testCipher, + int testPort, + String... exception) throws Exception { + String expectedException = exception.length >= 1 + ? exception[0] : null; + out.println(" This is Server"); + out.println(" Testing Protocol: " + testProtocol); + out.println(" Testing Cipher: " + testCipher); + out.println(" Testing Port: " + testPort); + Provider p = new sun.security.ec.SunEC(); + Security.insertProviderAt(p, 1); + try { + CipherTestUtils.main(new JSSEFactory(null, testPort, + testProtocol, testCipher, "Server JSSE"), + "Server", expectedException); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static class JSSEFactory extends CipherTestUtils.PeerFactory { + + final String testedCipherSuite, testedProtocol, testHost; + final int testPort; + final String name; + + JSSEFactory(String testHost, int testPort, String testedProtocol, + String testedCipherSuite, String name) { + this.testedCipherSuite = testedCipherSuite; + this.testedProtocol = testedProtocol; + this.testHost = testHost; + this.testPort = testPort; + this.name = name; + } + + @Override + String getName() { + return name; + } + + @Override + String getTestedCipher() { + return testedCipherSuite; + } + + @Override + String getTestedProtocol() { + return testedProtocol; + } + + @Override + CipherTestUtils.Client newClient(CipherTestUtils cipherTest) + throws Exception { + return new JSSEClient(cipherTest, testHost, testPort, + testedProtocol, testedCipherSuite); + } + + @Override + CipherTestUtils.Server newServer(CipherTestUtils cipherTest) + throws Exception { + return new JSSEServer(cipherTest, testPort, + testedProtocol, testedCipherSuite); + } + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/BaseTest.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/BaseTest.java new file mode 100644 index 00000000000..020d3420cd3 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/BaseTest.java @@ -0,0 +1,338 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.File; +import java.net.URL; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.dom.DOMSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import javax.xml.validation.Validator; + + +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.impl.Constants; +import com.sun.org.apache.xerces.internal.impl.xs.SchemaGrammar; +import com.sun.org.apache.xerces.internal.xs.ElementPSVI; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import com.sun.org.apache.xerces.internal.xs.XSElementDeclaration; +import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition; +import javax.xml.transform.stream.StreamSource; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +public abstract class BaseTest { + protected final static String ROOT_TYPE = Constants.XERCES_PROPERTY_PREFIX + + Constants.ROOT_TYPE_DEFINITION_PROPERTY; + + protected final static String IGNORE_XSI_TYPE = Constants.XERCES_FEATURE_PREFIX + + Constants.IGNORE_XSI_TYPE_FEATURE; + + protected final static String ID_IDREF_CHECKING = Constants.XERCES_FEATURE_PREFIX + + Constants.ID_IDREF_CHECKING_FEATURE; + + protected final static String IDC_CHECKING = Constants.XERCES_FEATURE_PREFIX + + Constants.IDC_CHECKING_FEATURE; + + protected final static String UNPARSED_ENTITY_CHECKING = Constants.XERCES_FEATURE_PREFIX + + Constants.UNPARSED_ENTITY_CHECKING_FEATURE; + + protected final static String USE_GRAMMAR_POOL_ONLY = Constants.XERCES_FEATURE_PREFIX + + Constants.USE_GRAMMAR_POOL_ONLY_FEATURE; + + protected final static String DYNAMIC_VALIDATION = Constants.XERCES_FEATURE_PREFIX + + Constants.DYNAMIC_VALIDATION_FEATURE; + + protected final static String DOCUMENT_CLASS_NAME = Constants.XERCES_PROPERTY_PREFIX + + Constants.DOCUMENT_CLASS_NAME_PROPERTY; + + protected Schema schema; + protected Validator fValidator; + + protected SpecialCaseErrorHandler fErrorHandler; + + DocumentBuilder builder; + protected Document fDocument; + + protected ElementPSVI fRootNode; + + protected URL fDocumentURL; + protected String documentPath; + protected String fDocumentId; + + static String errMessage; + + int passed = 0, failed = 0; + + public static boolean isWindows = false; + static { + if (System.getProperty("os.name").indexOf("Windows")>-1) { + isWindows = true; + } + }; + public static final String USER_DIR = System.getProperty("user.dir", "."); + public static final String BASE_DIR = System.getProperty("test.src", USER_DIR) + .replaceAll("\\" + System.getProperty("file.separator"), "/"); + + protected abstract String getSchemaFile(); + + protected abstract String getXMLDocument(); + + public BaseTest(String name) { + fErrorHandler = new SpecialCaseErrorHandler(getRelevantErrorIDs()); + } + + protected void setUp() throws Exception { + + DocumentBuilderFactory docFactory = DocumentBuilderFactory + .newInstance(); + docFactory.setAttribute(DOCUMENT_CLASS_NAME, + "com.sun.org.apache.xerces.internal.dom.PSVIDocumentImpl"); + docFactory.setNamespaceAware(true); + builder = docFactory.newDocumentBuilder(); + + documentPath = BASE_DIR + "/" + getXMLDocument(); +System.out.println("documentPath:"+documentPath); + if (isWindows) { + fDocumentId = "file:/" + documentPath; + } else { + fDocumentId = "file:" + documentPath; + } + //fDocumentURL = ClassLoader.getSystemResource(documentPath); + //fDocumentURL = getClass().getResource(documentPath); +System.out.println("fDocumentId:"+fDocumentId); +//System.out.println("fDocumentURL.toExternalForm:"+fDocumentURL.toExternalForm()); +/** + if (fDocumentURL == null) { + throw new FileNotFoundException("Couldn't find xml file for test: " + documentPath); + } + fDocument = builder.parse(fDocumentURL.toExternalForm()); + fRootNode = (ElementPSVI) fDocument.getDocumentElement(); + */ + SchemaFactory sf = SchemaFactory + .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + sf.setFeature(USE_GRAMMAR_POOL_ONLY, getUseGrammarPoolOnly()); + String schemaPath = BASE_DIR + "/" + getSchemaFile(); + /** + URL schemaURL = ClassLoader.getSystemResource(schemaPath); + if (schemaURL == null) { + throw new FileNotFoundException("Couldn't find schema file for test: " + schemaPath); + } + */ + schema = sf.newSchema(new StreamSource(new File(schemaPath))); + } + + protected void tearDown() throws Exception { + fValidator = null; + fDocument = null; + fRootNode = null; + fErrorHandler.reset(); + System.out.println("\nNumber of tests passed: " + passed); + System.out.println("Number of tests failed: " + failed + "\n"); + + if (errMessage != null) { + throw new RuntimeException(errMessage); + } + } + + protected void validateDocument() throws Exception { + Source source = new DOMSource(fDocument); + source.setSystemId(fDocumentId); + Result result = new DOMResult(fDocument); + fValidator.validate(source, result); + } + + protected void validateFragment() throws Exception { + Source source = new DOMSource((Node) fRootNode); + source.setSystemId(fDocumentId); + Result result = new DOMResult((Node) fRootNode); + fValidator.validate(source, result); + } + + protected void reset() throws Exception { + try { +System.out.println("new File(documentPath)" + new File(documentPath)); + + fDocument = builder.parse(new File(documentPath)); + fRootNode = (ElementPSVI) fDocument.getDocumentElement(); +System.out.println("fDocument" + fDocument); +System.out.println("fRootNode" + fRootNode); + fValidator = schema.newValidator(); + fErrorHandler.reset(); + fValidator.setErrorHandler(fErrorHandler); + fValidator.setFeature(DYNAMIC_VALIDATION, false); + } catch (Exception e) { + e.printStackTrace(); + } + } + + protected PSVIElementNSImpl getChild(int n) { + int numFound = 0; + Node child = ((Node) fRootNode).getFirstChild(); + while (child != null) { + if (child.getNodeType() == Node.ELEMENT_NODE) { + numFound++; + if (numFound == n) { + return (PSVIElementNSImpl) child; + } + } + child = child.getNextSibling(); + } + return null; + } + + protected String[] getRelevantErrorIDs() { + return new String[] {}; + } + + protected boolean getUseGrammarPoolOnly() { + return false; + } + + // specialized asserts + + protected void assertValidity(short expectedValidity, short actualValidity) { + String expectedString = expectedValidity == ItemPSVI.VALIDITY_VALID ? "valid" + : (expectedValidity == ItemPSVI.VALIDITY_INVALID ? "invalid" + : "notKnown"); + String actualString = actualValidity == ItemPSVI.VALIDITY_VALID ? "valid" + : (actualValidity == ItemPSVI.VALIDITY_INVALID ? "invalid" + : "notKnown"); + String message = "{validity} was <" + actualString + + "> but it should have been <" + expectedString + ">"; + assertEquals(message, expectedValidity, actualValidity); + } + + protected void assertValidationAttempted(short expectedAttempted, + short actualAttempted) { + String expectedString = expectedAttempted == ItemPSVI.VALIDATION_FULL ? "full" + : (expectedAttempted == ItemPSVI.VALIDATION_PARTIAL ? "partial" + : "none"); + String actualString = actualAttempted == ItemPSVI.VALIDATION_FULL ? "full" + : (actualAttempted == ItemPSVI.VALIDATION_PARTIAL ? "partial" + : "none"); + String message = "{validity} was <" + actualString + + "> but it should have been <" + expectedString + ">"; + assertEquals(message, expectedAttempted, actualAttempted); + } + + protected void assertElementName(String expectedName, String actualName) { + assertEquals("Local name of element declaration is wrong.", + expectedName, actualName); + } + + protected void assertElementNull(XSElementDeclaration elem) { + assertNull("Element declaration should be null.", elem); + } + + protected void assertElementNamespace(String expectedName, String actualName) { + assertEquals("Namespace of element declaration is wrong.", + expectedName, actualName); + } + + protected void assertElementNamespaceNull(String actualName) { + assertNull("Local name of element declaration should be null.", + actualName); + } + + protected void assertTypeName(String expectedName, String actualName) { + assertEquals("Local name of type definition is wrong.", expectedName, + actualName); + } + + protected void assertTypeNull(XSTypeDefinition type) { + assertNull("Type definition should be null.", type); + } + + protected void assertTypeNamespace(String expectedName, String actualName) { + assertEquals("Namespace of type definition is wrong.", expectedName, + actualName); + } + + protected void assertTypeNamespaceNull(String actualName) { + assertNull("Namespace of type definition should be null.", actualName); + } + + protected void assertError(String error) { + assertTrue("Error <" + error + "> should have occured, but did not.", + fErrorHandler.specialCaseFound(error)); + } + + protected void assertNoError(String error) { + assertFalse("Error <" + error + + "> should not have occured (but it did)", fErrorHandler + .specialCaseFound(error)); + } + + protected void assertAnyType(XSTypeDefinition type) { + assertEquals("Type is supposed to be anyType", SchemaGrammar.fAnyType, + type); + } + + void assertEquals(String msg, Object expected, Object actual) { + if (!expected.equals(actual)) { + fail(msg + " Expected: " + expected + " Actual: " + actual); + } else { + success(null); + } + } + void assertNull(String msg, Object value) { + if (value != null) { + fail(msg); + } else { + success(null); + } + } + void assertTrue(String msg, boolean value) { + if (!value) { + fail(msg); + } else { + success(null); + } + } + void assertFalse(String msg, boolean value) { + if (value) { + fail(msg); + } else { + success(null); + } + } + void fail(String errMsg) { + if (errMessage == null) { + errMessage = errMsg; + } else { + errMessage = errMessage + "\n" + errMsg; + } + failed++; + } + + void success(String msg) { + passed++; + System.out.println(msg); + if (msg != null) { + if (msg.length() != 0) { + System.out.println(msg); + } + } + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/BasicTest.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/BasicTest.java new file mode 100644 index 00000000000..d33e571e28e --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/BasicTest.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class BasicTest extends BaseTest { + + protected String getXMLDocument() { + return "base.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + public BasicTest(String name) { + super(name); + } + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testSimpleValidation() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + doValidityAsserts(); + } + + @Test + public void testSimpleValidationWithTrivialXSIType() { + try { + reset(); + ((PSVIElementNSImpl) fRootNode).setAttributeNS( + "http://www.w3.org/2001/XMLSchema-instance", "type", "X"); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + doValidityAsserts(); + } + + private void doValidityAsserts() { + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementName("A", fRootNode.getElementDeclaration().getName()); + assertElementNamespaceNull(fRootNode.getElementDeclaration() + .getNamespace()); + assertTypeName("X", fRootNode.getTypeDefinition().getName()); + assertTypeNamespaceNull(fRootNode.getTypeDefinition().getNamespace()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/FixedAttrTest.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/FixedAttrTest.java new file mode 100644 index 00000000000..e1f31f0d409 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/FixedAttrTest.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * The purpose of this test is to execute all of the isComparable calls in + * XMLSchemaValidator. There are two calls in processElementContent and two + * calls in processOneAttribute. + * + * @author peterjm + */ +public class FixedAttrTest extends BaseTest { + + protected String getXMLDocument() { + return "fixedAttr.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + public FixedAttrTest(String name) { + super(name); + } + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testDefault() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementName("A", fRootNode.getElementDeclaration().getName()); + + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("B", child.getElementDeclaration().getName()); + + child = super.getChild(2); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("D", child.getElementDeclaration().getName()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/IdIdrefCheckingTest.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IdIdrefCheckingTest.java new file mode 100644 index 00000000000..4d0aa31af8f --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IdIdrefCheckingTest.java @@ -0,0 +1,160 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.xml.sax.SAXException; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +// duplicate IDs +// reference to non-existent ID + +public class IdIdrefCheckingTest extends BaseTest { + public static final String DUPLICATE_ID = "cvc-id.2"; + + public static final String NO_ID_BINDING = "cvc-id.1"; + + protected String getXMLDocument() { + return "idIdref.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + protected String[] getRelevantErrorIDs() { + return new String[] { DUPLICATE_ID, NO_ID_BINDING }; + } + + public IdIdrefCheckingTest(String name) { + super(name); + } + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testDefault() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkDefault(); + } + + @Test + public void testSetFalse() { + try { + reset(); + fValidator.setFeature(ID_IDREF_CHECKING, false); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkValidResult(); + } + + @Test + public void testSetTrue() { + try { + reset(); + fValidator.setFeature(ID_IDREF_CHECKING, true); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkDefault(); + } + + private void checkDefault() { + assertError(DUPLICATE_ID); + assertError(NO_ID_BINDING); + + assertValidity(ItemPSVI.VALIDITY_INVALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementName("A", fRootNode.getElementDeclaration().getName()); + assertTypeName("X", fRootNode.getTypeDefinition().getName()); + + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("A", child.getElementDeclaration().getName()); + assertTypeName("idType", child.getTypeDefinition().getName()); + + child = super.getChild(2); + assertValidity(ItemPSVI.VALIDITY_INVALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("A", child.getElementDeclaration().getName()); + assertTypeName("idType", child.getTypeDefinition().getName()); + + child = super.getChild(3); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("A", child.getElementDeclaration().getName()); + assertTypeName("idrefType", child.getTypeDefinition().getName()); + } + + private void checkValidResult() { + assertNoError(DUPLICATE_ID); + assertNoError(NO_ID_BINDING); + + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementName("A", fRootNode.getElementDeclaration().getName()); + assertTypeName("X", fRootNode.getTypeDefinition().getName()); + + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("A", child.getElementDeclaration().getName()); + assertTypeName("idType", child.getTypeDefinition().getName()); + + child = super.getChild(2); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("A", child.getElementDeclaration().getName()); + assertTypeName("idType", child.getTypeDefinition().getName()); + + child = super.getChild(3); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("A", child.getElementDeclaration().getName()); + assertTypeName("idrefType", child.getTypeDefinition().getName()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/IdentityConstraintCheckingTest.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IdentityConstraintCheckingTest.java new file mode 100644 index 00000000000..3089f6308ec --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IdentityConstraintCheckingTest.java @@ -0,0 +1,186 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.xml.sax.SAXException; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class IdentityConstraintCheckingTest extends BaseTest { + // These values are unstable, since they're not actually error keys, but + // simply + // the first part of the error message. + public static final String DUPLICATE_UNIQUE = "cvc-identity-constraint.4.1"; + + public static final String DUPLICATE_KEY = "cvc-identity-constraint.4.2.2"; + + public static final String INVALID_KEYREF = "cvc-identity-constraint.4.3"; + + protected String getXMLDocument() { + return "idc.xml"; + } + + protected String getSchemaFile() { + return "idc.xsd"; + } + + protected String[] getRelevantErrorIDs() { + return new String[] { DUPLICATE_UNIQUE, DUPLICATE_KEY, INVALID_KEYREF }; + } + + public IdentityConstraintCheckingTest(String name) { + super(name); + } + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testDefault() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkDefault(); + } + + @Test + public void testSetFalse() { + try { + reset(); + fValidator.setFeature(IDC_CHECKING, false); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkValidResult(); + } + + @Test + public void testSetTrue() { + try { + reset(); + fValidator.setFeature(IDC_CHECKING, true); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkDefault(); + } + + private void checkDefault() { + assertError(DUPLICATE_UNIQUE); + assertError(DUPLICATE_KEY); + assertError(INVALID_KEYREF); + + assertValidity(ItemPSVI.VALIDITY_INVALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementName("itemList", fRootNode.getElementDeclaration() + .getName()); + assertTypeName("itemListType", fRootNode.getTypeDefinition().getName()); + + // this one is valid because it's the first one to define the unique + // value + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("item", child.getElementDeclaration().getName()); + assertTypeName("itemType", child.getTypeDefinition().getName()); + + // invalid because it repeats the unique value + child = super.getChild(2); + assertValidity(ItemPSVI.VALIDITY_INVALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("item", child.getElementDeclaration().getName()); + assertTypeName("itemType", child.getTypeDefinition().getName()); + + // invalid because it repeats the key + child = super.getChild(3); + assertValidity(ItemPSVI.VALIDITY_INVALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("item", child.getElementDeclaration().getName()); + assertTypeName("itemType", child.getTypeDefinition().getName()); + + // valid because key references aren't figured out until the validation + // root + child = super.getChild(4); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("itemRef", child.getElementDeclaration().getName()); + assertTypeName("string", child.getTypeDefinition().getName()); + } + + private void checkValidResult() { + assertNoError(DUPLICATE_UNIQUE); + assertNoError(DUPLICATE_KEY); + assertNoError(INVALID_KEYREF); + + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementName("itemList", fRootNode.getElementDeclaration() + .getName()); + assertTypeName("itemListType", fRootNode.getTypeDefinition().getName()); + + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("item", child.getElementDeclaration().getName()); + assertTypeName("itemType", child.getTypeDefinition().getName()); + + child = super.getChild(2); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("item", child.getElementDeclaration().getName()); + assertTypeName("itemType", child.getTypeDefinition().getName()); + + child = super.getChild(3); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("item", child.getElementDeclaration().getName()); + assertTypeName("itemType", child.getTypeDefinition().getName()); + + child = super.getChild(4); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("itemRef", child.getElementDeclaration().getName()); + assertTypeName("string", child.getTypeDefinition().getName()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_A_A.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_A_A.java new file mode 100644 index 00000000000..435c0f97069 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_A_A.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class IgnoreXSITypeTest_A_A extends BaseTest { + + protected String getXMLDocument() { + return "xsitype_A_A.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + public IgnoreXSITypeTest_A_A(String name) { + super(name); + } + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testDefaultDocument() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + // default value of the feature is false + checkFalseResult(); + } + + @Test + public void testDefaultFragment() { + try { + reset(); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + // default value of the feature is false + checkFalseResult(); + } + + @Test + public void testSetFalseDocument() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, false); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkFalseResult(); + } + + @Test + public void testSetFalseFragment() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, false); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkFalseResult(); + } + + @Test + public void testSetTrueDocument() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, true); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkTrueResult(); + } + + @Test + public void testSetTrueFragment() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, true); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkTrueResult(); + } + + private void checkTrueResult() { + checkResult(); + } + + private void checkFalseResult() { + checkResult(); + } + + private void checkResult() { + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementName("A", fRootNode.getElementDeclaration().getName()); + assertTypeName("Y", fRootNode.getTypeDefinition().getName()); + assertTypeNamespaceNull(fRootNode.getTypeDefinition().getNamespace()); + + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("A", child.getElementDeclaration().getName()); + assertTypeName("Y", child.getTypeDefinition().getName()); + assertTypeNamespaceNull(child.getTypeDefinition().getNamespace()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_A_C.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_A_C.java new file mode 100644 index 00000000000..4dd172d0de2 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_A_C.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class IgnoreXSITypeTest_A_C extends BaseTest { + + protected String getXMLDocument() { + return "xsitype_A_C.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + public IgnoreXSITypeTest_A_C(String name) { + super(name); + } + + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testDefaultDocument() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + // default value of the feature is false + checkFalseResult(); + } + + @Test + public void testDefaultFragment() { + try { + reset(); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + // default value of the feature is false + checkFalseResult(); + } + + @Test + public void testSetFalseDocument() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, false); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkFalseResult(); + } + + @Test + public void testSetFalseFragment() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, false); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkFalseResult(); + } + + @Test + public void testSetTrueDocument() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, true); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkTrueResult(); + } + + @Test + public void testSetTrueFragment() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, true); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkTrueResult(); + } + + private void checkTrueResult() { + checkResult(); + } + + private void checkFalseResult() { + checkResult(); + } + + private void checkResult() { + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementName("A", fRootNode.getElementDeclaration().getName()); + assertTypeName("Y", fRootNode.getTypeDefinition().getName()); + assertTypeNamespaceNull(fRootNode.getTypeDefinition().getNamespace()); + + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementNull(child.getElementDeclaration()); + assertTypeName("Y", child.getTypeDefinition().getName()); + assertTypeNamespaceNull(child.getTypeDefinition().getNamespace()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_A.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_A.java new file mode 100644 index 00000000000..fb4886e9d04 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_A.java @@ -0,0 +1,157 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class IgnoreXSITypeTest_C_A extends BaseTest { + + protected String getXMLDocument() { + return "xsitype_C_A.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + public IgnoreXSITypeTest_C_A(String name) { + super(name); + } + + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testDefaultDocument() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + // default value of the feature is false + checkFalseResult(); + } + + @Test + public void testDefaultFragment() { + try { + reset(); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + // default value of the feature is false + checkFalseResult(); + } + + @Test + public void testSetFalseDocument() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, false); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkFalseResult(); + } + + @Test + public void testSetFalseFragment() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, false); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkFalseResult(); + } + + @Test + public void testSetTrueDocument() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, true); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkTrueResult(); + } + + @Test + public void testSetTrueFragment() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, true); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkTrueResult(); + } + + private void checkTrueResult() { + assertValidity(ItemPSVI.VALIDITY_NOTKNOWN, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_PARTIAL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertAnyType(fRootNode.getTypeDefinition()); + + checkChild(); + } + + private void checkFalseResult() { + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertTypeName("Y", fRootNode.getTypeDefinition().getName()); + assertTypeNamespaceNull(fRootNode.getTypeDefinition().getNamespace()); + + checkChild(); + } + + private void checkChild() { + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("A", child.getElementDeclaration().getName()); + assertTypeName("Y", child.getTypeDefinition().getName()); + assertTypeNamespaceNull(child.getTypeDefinition().getNamespace()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_AC.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_AC.java new file mode 100644 index 00000000000..a98ca85a61e --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_AC.java @@ -0,0 +1,174 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class IgnoreXSITypeTest_C_AC extends BaseTest { + + protected String getXMLDocument() { + return "xsitype_C_AC.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + public IgnoreXSITypeTest_C_AC(String name) { + super(name); + } + + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testDefaultDocument() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + // default value of the feature is false + checkFalseResult(); + } + + @Test + public void testDefaultFragment() { + try { + reset(); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + // default value of the feature is false + checkFalseResult(); + } + + @Test + public void testSetFalseDocument() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, false); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkFalseResult(); + } + + @Test + public void testSetFalseFragment() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, false); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkFalseResult(); + } + + @Test + public void testSetTrueDocument() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, true); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkTrueResult(); + } + + @Test + public void testSetTrueFragment() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, true); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkTrueResult(); + } + + private void checkTrueResult() { + assertValidity(ItemPSVI.VALIDITY_NOTKNOWN, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_PARTIAL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertAnyType(fRootNode.getTypeDefinition()); + + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("A", child.getElementDeclaration().getName()); + assertTypeName("Y", child.getTypeDefinition().getName()); + assertTypeNamespaceNull(child.getTypeDefinition().getNamespace()); + + child = super.getChild(2); + assertValidity(ItemPSVI.VALIDITY_NOTKNOWN, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_NONE, child + .getValidationAttempted()); + assertElementNull(child.getElementDeclaration()); + assertAnyType(child.getTypeDefinition()); + } + + private void checkFalseResult() { + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertTypeName("Y", fRootNode.getTypeDefinition().getName()); + assertTypeNamespaceNull(fRootNode.getTypeDefinition().getNamespace()); + + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("A", child.getElementDeclaration().getName()); + assertTypeName("Y", child.getTypeDefinition().getName()); + assertTypeNamespaceNull(child.getTypeDefinition().getNamespace()); + + child = super.getChild(2); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementNull(child.getElementDeclaration()); + assertTypeName("Y", child.getTypeDefinition().getName()); + assertTypeNamespaceNull(child.getTypeDefinition().getNamespace()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_C.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_C.java new file mode 100644 index 00000000000..b2623ac22e4 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_C.java @@ -0,0 +1,158 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class IgnoreXSITypeTest_C_C extends BaseTest { + + protected String getXMLDocument() { + return "xsitype_C_C.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + public IgnoreXSITypeTest_C_C(String name) { + super(name); + } + + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testDefaultDocument() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + // default value of the feature is false + checkFalseResult(); + } + + @Test + public void testDefaultFragment() { + try { + reset(); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + // default value of the feature is false + checkFalseResult(); + } + + @Test + public void testSetFalseDocument() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, false); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkFalseResult(); + } + + @Test + public void testSetFalseFragment() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, false); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkFalseResult(); + } + + @Test + public void testSetTrueDocument() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, true); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkTrueResult(); + } + + @Test + public void testSetTrueFragment() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, true); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkTrueResult(); + } + + private void checkTrueResult() { + assertValidity(ItemPSVI.VALIDITY_NOTKNOWN, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_NONE, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertAnyType(fRootNode.getTypeDefinition()); + + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_NOTKNOWN, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_NONE, child + .getValidationAttempted()); + assertElementNull(child.getElementDeclaration()); + assertAnyType(child.getTypeDefinition()); + } + + private void checkFalseResult() { + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertTypeName("Y", fRootNode.getTypeDefinition().getName()); + assertTypeNamespaceNull(fRootNode.getTypeDefinition().getNamespace()); + + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementNull(child.getElementDeclaration()); + assertTypeName("Y", child.getTypeDefinition().getName()); + assertTypeNamespaceNull(child.getTypeDefinition().getNamespace()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_CA.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_CA.java new file mode 100644 index 00000000000..dc8f4f297d3 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/IgnoreXSITypeTest_C_CA.java @@ -0,0 +1,173 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class IgnoreXSITypeTest_C_CA extends BaseTest { + + protected String getXMLDocument() { + return "xsitype_C_CA.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + public IgnoreXSITypeTest_C_CA(String name) { + super(name); + } + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testDefaultDocument() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + // default value of the feature is false + checkFalseResult(); + } + + @Test + public void testDefaultFragment() { + try { + reset(); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + // default value of the feature is false + checkFalseResult(); + } + + @Test + public void testSetFalseDocument() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, false); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkFalseResult(); + } + + @Test + public void testSetFalseFragment() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, false); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkFalseResult(); + } + + @Test + public void testSetTrueDocument() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, true); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkTrueResult(); + } + + @Test + public void testSetTrueFragment() { + try { + reset(); + fValidator.setFeature(IGNORE_XSI_TYPE, true); + validateFragment(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkTrueResult(); + } + + private void checkTrueResult() { + assertValidity(ItemPSVI.VALIDITY_NOTKNOWN, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_PARTIAL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertAnyType(fRootNode.getTypeDefinition()); + + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_NOTKNOWN, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_NONE, child + .getValidationAttempted()); + assertElementNull(child.getElementDeclaration()); + assertAnyType(child.getTypeDefinition()); + + child = super.getChild(2); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("A", child.getElementDeclaration().getName()); + assertTypeName("Y", child.getTypeDefinition().getName()); + assertTypeNamespaceNull(child.getTypeDefinition().getNamespace()); + } + + private void checkFalseResult() { + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertTypeName("Y", fRootNode.getTypeDefinition().getName()); + assertTypeNamespaceNull(fRootNode.getTypeDefinition().getNamespace()); + + PSVIElementNSImpl child = super.getChild(1); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementNull(child.getElementDeclaration()); + assertTypeName("Y", child.getTypeDefinition().getName()); + assertTypeNamespaceNull(child.getTypeDefinition().getNamespace()); + + child = super.getChild(2); + assertValidity(ItemPSVI.VALIDITY_VALID, child.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, child + .getValidationAttempted()); + assertElementName("A", child.getElementDeclaration().getName()); + assertTypeName("Y", child.getTypeDefinition().getName()); + assertTypeNamespaceNull(child.getTypeDefinition().getNamespace()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/RootTypeDefinitionTest.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/RootTypeDefinitionTest.java new file mode 100644 index 00000000000..c9db8ad14af --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/RootTypeDefinitionTest.java @@ -0,0 +1,235 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import javax.xml.namespace.QName; +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.impl.xs.SchemaSymbols; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class RootTypeDefinitionTest extends BaseTest { + private QName unknownType; + + private QName typeX; + + private QName typeY; + + private QName typeZ; + + private QName typeOtherNamespace; + + private final static String UNKNOWN_TYPE_ERROR = "cvc-type.1"; + + private final static String INVALID_DERIVATION_ERROR = "cvc-elt.4.3"; + + protected String getXMLDocument() { + return "base.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + protected String[] getRelevantErrorIDs() { + return new String[] { UNKNOWN_TYPE_ERROR, INVALID_DERIVATION_ERROR }; + } + + public RootTypeDefinitionTest(String name) { + super(name); + unknownType = new QName("W"); + typeX = new QName("X"); + typeY = new QName("Y"); + typeZ = new QName("Z"); + typeOtherNamespace = new QName("xslt.unittests", "W", "unit"); + } + + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testDefault() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkDefault(); + } + + @Test + public void testSettingNull() { + try { + reset(); + fValidator.setProperty(ROOT_TYPE, null); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkDefault(); + } + + @Test + public void testSettingToUnknownType() { + try { + reset(); + fValidator.setProperty(ROOT_TYPE, unknownType); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + assertError(UNKNOWN_TYPE_ERROR); + checkDefault(); + } + + @Test + public void testSettingToEqualType() { + try { + reset(); + fValidator.setProperty(ROOT_TYPE, typeX); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertTypeName("X", fRootNode.getTypeDefinition().getName()); + } + + @Test + public void testSettingToDerivedType() { + try { + reset(); + // this is required to make it a valid type Y node + ((PSVIElementNSImpl) fRootNode).setAttributeNS(null, "attr", "typeY"); + fValidator.setProperty(ROOT_TYPE, typeY); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertTypeName("Y", fRootNode.getTypeDefinition().getName()); + } + + @Test + public void testSettingToNonDerivedType() { + try { + reset(); + fValidator.setProperty(ROOT_TYPE, typeZ); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertTypeName("Z", fRootNode.getTypeDefinition().getName()); + } + + @Test + public void testSettingToOtherSchemaType() { + try { + reset(); + ((PSVIElementNSImpl) fRootNode).setAttributeNS(SchemaSymbols.URI_XSI, + SchemaSymbols.XSI_SCHEMALOCATION, + "xslt.unittests otherNamespace.xsd"); + fValidator.setProperty(ROOT_TYPE, typeOtherNamespace); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertTypeName("W", fRootNode.getTypeDefinition().getName()); + assertTypeNamespace("xslt.unittests", fRootNode.getTypeDefinition() + .getNamespace()); + } + + @Test + public void testSettingTypeAndXSIType() { + try { + reset(); + // this is required to make it a valid type Y node + ((PSVIElementNSImpl) fRootNode).setAttributeNS(null, "attr", "typeY"); + ((PSVIElementNSImpl) fRootNode).setAttributeNS(SchemaSymbols.URI_XSI, + SchemaSymbols.XSI_TYPE, "Y"); + fValidator.setProperty(ROOT_TYPE, typeX); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertTypeName("Y", fRootNode.getTypeDefinition().getName()); + } + + @Test + public void testSettingTypeAndInvalidXSIType() { + try { + reset(); + ((PSVIElementNSImpl) fRootNode).setAttributeNS(SchemaSymbols.URI_XSI, + SchemaSymbols.XSI_TYPE, "Z"); + fValidator.setProperty(ROOT_TYPE, typeX); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + assertError(INVALID_DERIVATION_ERROR); + assertValidity(ItemPSVI.VALIDITY_INVALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertTypeName("Z", fRootNode.getTypeDefinition().getName()); + } + + private void checkDefault() { + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementName("A", fRootNode.getElementDeclaration().getName()); + assertTypeName("X", fRootNode.getTypeDefinition().getName()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/SpecialCaseErrorHandler.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/SpecialCaseErrorHandler.java new file mode 100644 index 00000000000..e5f236d1907 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/SpecialCaseErrorHandler.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.HashMap; + +import org.xml.sax.ErrorHandler; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +public class SpecialCaseErrorHandler implements ErrorHandler { + public static final boolean DEBUG = false; + + private HashMap errors; + + public SpecialCaseErrorHandler(String[] specialCases) { + errors = new HashMap<>(); + for (int i = 0; i < specialCases.length; ++i) { + errors.put(specialCases[i], Boolean.FALSE); + } + } + + public void reset() { + errors.keySet().stream().forEach((error) -> { + errors.put(error, Boolean.FALSE); + }); + } + + @Override + public void warning(SAXParseException arg0) throws SAXException { + if (DEBUG) { + System.err.println(arg0.getMessage()); + } + } + + @Override + public void error(SAXParseException arg0) throws SAXException { + if (DEBUG) { + System.err.println(arg0.getMessage()); + } + errors.keySet().stream().filter((error) -> (arg0.getMessage().startsWith(error))).forEach((error) -> { + errors.put(error, Boolean.TRUE); + }); + } + + public void fatalError(SAXParseException arg0) throws SAXException { + throw arg0; + } + + public boolean specialCaseFound(String key) { + return ((Boolean) errors.get(key)).booleanValue(); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/TEST.properties b/jdk/test/javax/xml/jaxp/testng/validation/8037819/TEST.properties new file mode 100644 index 00000000000..4d7d0f90d06 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/TEST.properties @@ -0,0 +1,3 @@ +# This file identifies root(s) of the test-ng hierarchy. + +TestNG.dirs = . diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/UnparsedEntityCheckingTest.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/UnparsedEntityCheckingTest.java new file mode 100644 index 00000000000..5d4faaf367a --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/UnparsedEntityCheckingTest.java @@ -0,0 +1,152 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.org.apache.xerces.internal.dom.PSVIElementNSImpl; +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class UnparsedEntityCheckingTest extends BaseTest { + public static final String UNDECLARED_ENTITY = "UndeclaredEntity"; + + protected String getXMLDocument() { + return "unparsedEntity.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + protected String[] getRelevantErrorIDs() { + return new String[] { UNDECLARED_ENTITY }; + } + + public UnparsedEntityCheckingTest(String name) { + super(name); + } + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public void testDefaultValid() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkDefault(); + } + + @Test + public void testSetFalseValid() { + try { + reset(); + fValidator.setFeature(UNPARSED_ENTITY_CHECKING, false); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkDefault(); + } + + @Test + public void testSetTrueValid() { + try { + reset(); + fValidator.setFeature(UNPARSED_ENTITY_CHECKING, true); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkDefault(); + } + + @Test + public void testDefaultInvalid() { + try { + reset(); + ((PSVIElementNSImpl) fRootNode).setAttributeNS(null, + "unparsedEntityAttr", "invalid"); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkInvalid(); + } + + @Test + public void testSetFalseInvalid() { + try { + reset(); + ((PSVIElementNSImpl) fRootNode).setAttributeNS(null, + "unparsedEntityAttr", "invalid"); + fValidator.setFeature(UNPARSED_ENTITY_CHECKING, false); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkDefault(); + } + + @Test + public void testSetTrueInvalid() { + try { + reset(); + ((PSVIElementNSImpl) fRootNode).setAttributeNS(null, + "unparsedEntityAttr", "invalid"); + fValidator.setFeature(UNPARSED_ENTITY_CHECKING, true); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + checkInvalid(); + } + + private void checkDefault() { + assertNoError(UNDECLARED_ENTITY); + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementName("A", fRootNode.getElementDeclaration().getName()); + assertTypeName("X", fRootNode.getTypeDefinition().getName()); + } + + private void checkInvalid() { + assertError(UNDECLARED_ENTITY); + assertValidity(ItemPSVI.VALIDITY_INVALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementName("A", fRootNode.getElementDeclaration().getName()); + assertTypeName("X", fRootNode.getTypeDefinition().getName()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/UseGrammarPoolOnlyTest_False.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/UseGrammarPoolOnlyTest_False.java new file mode 100644 index 00000000000..22c58567688 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/UseGrammarPoolOnlyTest_False.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class UseGrammarPoolOnlyTest_False extends BaseTest { + private final static String UNKNOWN_TYPE_ERROR = "cvc-type.1"; + + private final static String INVALID_DERIVATION_ERROR = "cvc-elt.4.3"; + + protected String getXMLDocument() { + return "otherNamespace.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + protected String[] getRelevantErrorIDs() { + return new String[] { UNKNOWN_TYPE_ERROR, INVALID_DERIVATION_ERROR }; + } + + protected boolean getUseGrammarPoolOnly() { + return false; + } + + public UseGrammarPoolOnlyTest_False(String name) { + super(name); + } + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + /** + * The purpose of this test is to check if setting the USE_GRAMMAR_POOL_ONLY + * feature to true causes external schemas to not be read. This + * functionality already existed prior to adding the XSLT 2.0 validation + * features; however, because the class that controlled it changed, this + * test simply ensures that the existing functionality did not disappear. + * -PM + */ + @Test + public void testUsingOnlyGrammarPool() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + assertValidity(ItemPSVI.VALIDITY_VALID, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_FULL, fRootNode + .getValidationAttempted()); + assertElementName("A", fRootNode.getElementDeclaration().getName()); + assertElementNamespace("xslt.unittests", fRootNode + .getElementDeclaration().getNamespace()); + assertTypeName("W", fRootNode.getTypeDefinition().getName()); + assertTypeNamespace("xslt.unittests", fRootNode.getTypeDefinition() + .getNamespace()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/UseGrammarPoolOnlyTest_True.java b/jdk/test/javax/xml/jaxp/testng/validation/8037819/UseGrammarPoolOnlyTest_True.java new file mode 100644 index 00000000000..3a41320b71a --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/UseGrammarPoolOnlyTest_True.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.org.apache.xerces.internal.xs.ItemPSVI; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class UseGrammarPoolOnlyTest_True extends BaseTest { + + protected String getXMLDocument() { + return "otherNamespace.xml"; + } + + protected String getSchemaFile() { + return "base.xsd"; + } + + protected boolean getUseGrammarPoolOnly() { + return true; + } + + public UseGrammarPoolOnlyTest_True(String name) { + super(name); + } + + @BeforeClass + protected void setUp() throws Exception { + super.setUp(); + } + + @AfterClass + protected void tearDown() throws Exception { + super.tearDown(); + } + + /** + * The purpose of this test is to check if setting the USE_GRAMMAR_POOL_ONLY + * feature to true causes external schemas to not be read. This + * functionality already existed prior to adding the XSLT 2.0 validation + * features; however, because the class that controlled it changed, this + * test simply ensures that the existing functionality did not disappear. + * -PM + */ + @Test + public void testUsingOnlyGrammarPool() { + try { + reset(); + validateDocument(); + } catch (Exception e) { + fail("Validation failed: " + e.getMessage()); + } + + assertValidity(ItemPSVI.VALIDITY_NOTKNOWN, fRootNode.getValidity()); + assertValidationAttempted(ItemPSVI.VALIDATION_NONE, fRootNode + .getValidationAttempted()); + assertElementNull(fRootNode.getElementDeclaration()); + assertAnyType(fRootNode.getTypeDefinition()); + } +} diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/base.xml b/jdk/test/javax/xml/jaxp/testng/validation/8037819/base.xml new file mode 100644 index 00000000000..e83adee70f5 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/base.xml @@ -0,0 +1,3 @@ + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/base.xsd b/jdk/test/javax/xml/jaxp/testng/validation/8037819/base.xsd new file mode 100644 index 00000000000..89f59c9f106 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/base.xsd @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/fixedAttr.xml b/jdk/test/javax/xml/jaxp/testng/validation/8037819/fixedAttr.xml new file mode 100644 index 00000000000..c9c8182a0f5 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/fixedAttr.xml @@ -0,0 +1,5 @@ + + + howdy + hey + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/idIdref.xml b/jdk/test/javax/xml/jaxp/testng/validation/8037819/idIdref.xml new file mode 100644 index 00000000000..f15efb4012f --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/idIdref.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/idc.xml b/jdk/test/javax/xml/jaxp/testng/validation/8037819/idc.xml new file mode 100644 index 00000000000..559888c3e13 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/idc.xml @@ -0,0 +1,7 @@ + + + 1 + 2 + 2 + 3 + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/idc.xsd b/jdk/test/javax/xml/jaxp/testng/validation/8037819/idc.xsd new file mode 100644 index 00000000000..1fe839819a6 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/idc.xsd @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/otherNamespace.xml b/jdk/test/javax/xml/jaxp/testng/validation/8037819/otherNamespace.xml new file mode 100644 index 00000000000..8c9f5a2e796 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/otherNamespace.xml @@ -0,0 +1,6 @@ + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/otherNamespace.xsd b/jdk/test/javax/xml/jaxp/testng/validation/8037819/otherNamespace.xsd new file mode 100644 index 00000000000..171d405e834 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/otherNamespace.xsd @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/unparsedEntity.dtd b/jdk/test/javax/xml/jaxp/testng/validation/8037819/unparsedEntity.dtd new file mode 100644 index 00000000000..62484e37cd4 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/unparsedEntity.dtd @@ -0,0 +1,3 @@ + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/unparsedEntity.xml b/jdk/test/javax/xml/jaxp/testng/validation/8037819/unparsedEntity.xml new file mode 100644 index 00000000000..91fb9ace10d --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/unparsedEntity.xml @@ -0,0 +1,4 @@ + + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_A_A.xml b/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_A_A.xml new file mode 100644 index 00000000000..2692aefe7ea --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_A_A.xml @@ -0,0 +1,6 @@ + + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_A_C.xml b/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_A_C.xml new file mode 100644 index 00000000000..049c0e7650e --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_A_C.xml @@ -0,0 +1,6 @@ + + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_A.xml b/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_A.xml new file mode 100644 index 00000000000..88cf49032f7 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_A.xml @@ -0,0 +1,6 @@ + + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_AC.xml b/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_AC.xml new file mode 100644 index 00000000000..dfc64aac23f --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_AC.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_C.xml b/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_C.xml new file mode 100644 index 00000000000..f7508138c80 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_C.xml @@ -0,0 +1,6 @@ + + + + diff --git a/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_CA.xml b/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_CA.xml new file mode 100644 index 00000000000..6b809d17e86 --- /dev/null +++ b/jdk/test/javax/xml/jaxp/testng/validation/8037819/xsitype_C_CA.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/jdk/test/com/sun/net/httpserver/SimpleSSLContext.java b/jdk/test/lib/testlibrary/jdk/testlibrary/SimpleSSLContext.java similarity index 55% rename from jdk/test/com/sun/net/httpserver/SimpleSSLContext.java rename to jdk/test/lib/testlibrary/jdk/testlibrary/SimpleSSLContext.java index 5f1a4606142..57a74fcf794 100644 --- a/jdk/test/com/sun/net/httpserver/SimpleSSLContext.java +++ b/jdk/test/lib/testlibrary/jdk/testlibrary/SimpleSSLContext.java @@ -21,6 +21,8 @@ * questions. */ +package jdk.testlibrary; + import com.sun.net.httpserver.*; import java.util.*; @@ -31,16 +33,64 @@ import java.security.*; import java.security.cert.*; import javax.net.ssl.*; +/** + * Creates a simple usable SSLContext for SSLSocketFactory + * or a HttpsServer using either a given keystore or a default + * one in the test tree. + * + * Using this class with a security manager requires the following + * permissions to be granted: + * + * permission "java.util.PropertyPermission" "test.src.path", "read"; + * permission java.io.FilePermission + * "${test.src}/../../../lib/testlibrary/jdk/testlibrary/testkeys", "read"; + * The exact path above depends on the location of the test. + */ public class SimpleSSLContext { SSLContext ssl; - SimpleSSLContext (String dir) throws IOException { + /** + * loads default keystore from SimpleSSLContext + * source directory + */ + public SimpleSSLContext () throws IOException { + String paths = System.getProperty("test.src.path"); + StringTokenizer st = new StringTokenizer(paths,":"); + boolean securityExceptions = false; + while (st.hasMoreTokens()) { + String path = st.nextToken(); + try { + File f = new File(path, "jdk/testlibrary/testkeys"); + if (f.exists()) { + init (new FileInputStream(f)); + return; + } + } catch (SecurityException e) { + // catch and ignore because permission only required + // for one entry on path (at most) + securityExceptions = true; + } + } + if (securityExceptions) { + System.err.println("SecurityExceptions thrown on loading testkeys"); + } + } + + /** + * loads default keystore from given directory + */ + public SimpleSSLContext (String dir) throws IOException { + String file = dir+"/testkeys"; + FileInputStream fis = new FileInputStream(file); + init(fis); + } + + private void init (InputStream i) throws IOException { try { - String file = dir+"/testkeys"; char[] passphrase = "passphrase".toCharArray(); KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(new FileInputStream(file), passphrase); + ks.load(i, passphrase); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, passphrase); @@ -63,7 +113,7 @@ public class SimpleSSLContext { } } - SSLContext get () { + public SSLContext get () { return ssl; } } diff --git a/jdk/test/com/sun/net/httpserver/testkeys b/jdk/test/lib/testlibrary/jdk/testlibrary/testkeys similarity index 100% rename from jdk/test/com/sun/net/httpserver/testkeys rename to jdk/test/lib/testlibrary/jdk/testlibrary/testkeys diff --git a/jdk/test/sun/net/www/protocol/http/RedirectOnPost.java b/jdk/test/sun/net/www/protocol/http/RedirectOnPost.java index ebbbadb27e3..6582a67744f 100644 --- a/jdk/test/sun/net/www/protocol/http/RedirectOnPost.java +++ b/jdk/test/sun/net/www/protocol/http/RedirectOnPost.java @@ -23,7 +23,9 @@ /** * @test - * @compile ../../../../../com/sun/net/httpserver/SimpleSSLContext.java RedirectOnPost.java + * @library /lib/testlibrary/ + * @build jdk.testlibrary.SimpleSSLContext + * @compile RedirectOnPost.java * @run main/othervm RedirectOnPost * @bug 8029127 * @summary A redirect POST request does not work and illegalStateException on HttpURLConnection.getInputStream @@ -35,17 +37,16 @@ import java.util.*; import com.sun.net.httpserver.*; import java.util.concurrent.*; import javax.net.ssl.*; +import jdk.testlibrary.SimpleSSLContext; public class RedirectOnPost { public static void main(String[] args) throws Exception { - ExecutorService e= Executors.newFixedThreadPool(5); - String keysdir = System.getProperty("test.src") - + "/../../../../../com/sun/net/httpserver/"; - SSLContext ctx = new SimpleSSLContext(keysdir).get(); - HttpServer httpServer = getHttpServer(e); - HttpsServer httpsServer = getHttpsServer(e, ctx); + ExecutorService e= Executors.newFixedThreadPool(5); + SSLContext ctx = new SimpleSSLContext().get(); + HttpServer httpServer = getHttpServer(e); + HttpsServer httpsServer = getHttpsServer(e, ctx); try { // take the keystore from elsewhere in test hierarchy diff --git a/jdk/test/sun/tools/jstatd/JstatdTest.java b/jdk/test/sun/tools/jstatd/JstatdTest.java index 5d01eb2397d..9cb1f60561e 100644 --- a/jdk/test/sun/tools/jstatd/JstatdTest.java +++ b/jdk/test/sun/tools/jstatd/JstatdTest.java @@ -148,11 +148,12 @@ public final class JstatdTest { private OutputAnalyzer waitForJstatdRMI(ProcessBuilder pb) throws IOException, InterruptedException { OutputAnalyzer output = new OutputAnalyzer(pb.start()); + String remoteHost = (serverName != null) ? serverName : "JStatRemoteHost"; while (output.getExitValue() != 0) { String out = output.getOutput(); if (out.contains("RMI Registry not available") || - out.contains("RMI Server JStatRemoteHost not available")) { + out.contains("RMI Server " + remoteHost + " not available")) { Thread.sleep(100); output = new OutputAnalyzer(pb.start()); } else {