diff --git a/.hgtags b/.hgtags index 38cd5dae51c..a3b11dde7f7 100644 --- a/.hgtags +++ b/.hgtags @@ -77,3 +77,7 @@ c4c8a5bc54f66abc68cd185d9294042121922154 jdk7-b99 2d6ba7a221915bdf0311acc5641c7f3875cb793e jdk7-b100 2548ac036b8fca3326d058d758e6df8355a42469 jdk7-b101 88db80c8e49cea352c2900f689600dc410761c1f jdk7-b102 +64770970865839b0443066370e7d476ef47e90cd jdk7-b103 +10bc903a228d3a8efdf46fb8c3fcf82a59b88bc5 jdk7-b104 +1ce7938efb03224ccc8b3cdd7803eb39e889539c jdk7-b105 +6bdae472f77205046703b685eff2ac4f7a0ecf4e jdk7-b106 diff --git a/.hgtags-top-repo b/.hgtags-top-repo index 95f8b4a541a..418fc6684b3 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -77,3 +77,7 @@ e7f18db469a3e947b7096bfd12e87380e5a042cd jdk7-b99 b218a53ec7d3d42be61d31d6917a6c5c037b6f56 jdk7-b100 4193eaf5f1b82794c6a0fb1a8d11af43d1b1d611 jdk7-b101 a136a51f5113da4dad3853b74a8536ab583ab112 jdk7-b102 +be2aedc4e3b1751c1310f334242ba69e90867f38 jdk7-b103 +f8be576feefce0c6695f188ef97ec16b73ad9cfd jdk7-b104 +9f96a4269d7727dad68864eaab795eafce270311 jdk7-b105 +43096cccf1cee749c2f4e7714ee71f4e9e0f4d7f jdk7-b106 diff --git a/corba/.hgtags b/corba/.hgtags index 81316616c47..b8c20cf4aff 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -77,3 +77,7 @@ edc2a2659c77dabc55cb55bb617bad89e3a05bb3 jdk7-b96 a56d734a1e970e1a21a8f4feb13053e9a33674c7 jdk7-b100 86a239832646a74811695428984b6947c0bd6dc8 jdk7-b101 78561a95779090b5106c8d0f1a75360a027ef087 jdk7-b102 +11e7678c3eb169b77d9a9892fe5e3dfa1d1a0d51 jdk7-b103 +9607213481d400ac477183191cc080e1bef6f475 jdk7-b104 +6f21b030092fb61244cc8a0aedf8058f7c022b81 jdk7-b105 +519daea48888196af76a975a3b31258efa860bad jdk7-b106 diff --git a/hotspot/.hgtags b/hotspot/.hgtags index 3d13f93a4be..f512e918032 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -107,3 +107,10 @@ ad1977f08c4d69162a0775fe3f9576b9fd521d10 jdk7-b100 6c3a919105b68c15b7db923ec9a00006e9560910 jdk7-b101 ad1977f08c4d69162a0775fe3f9576b9fd521d10 hs19-b03 c5cadf1a07717955cf60dbaec16e35b529fd2cb0 jdk7-b102 +cb4250ef73b21de6c487ea14e2b0b99eed67b4b6 jdk7-b103 +e55900b5c1b865cac17e18abc639c7dc50de7fd8 hs19-b04 +b4acf10eb134fe930802c97e36db65e7ccb544b5 jdk7-b104 +6709c14587c2cc6faca208767335afeb01e33de5 jdk7-b105 +1b81ca701fa5fc30adc4cfdaa4bdd153df5e6c86 jdk7-b106 +cc3fdfeb54b049f18edcf3463e6ab051d0b7b609 hs19-b05 +688a538aa65412178286ae2a6b0c00b6711e121b hs19-b06 diff --git a/hotspot/agent/src/os/linux/ps_proc.c b/hotspot/agent/src/os/linux/ps_proc.c index ef3ab89e6b6..5ad3ff7f367 100644 --- a/hotspot/agent/src/os/linux/ps_proc.c +++ b/hotspot/agent/src/os/linux/ps_proc.c @@ -253,7 +253,11 @@ static bool read_lib_info(struct ps_prochandle* ph) { if (nwords > 5 && find_lib(ph, word[5]) == false) { intptr_t base; lib_info* lib; +#ifdef _LP64 sscanf(word[0], "%lx", &base); +#else + sscanf(word[0], "%x", &base); +#endif if ((lib = add_lib_info(ph, word[5], (uintptr_t)base)) == NULL) continue; // ignore, add_lib_info prints error diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/ConstantPool.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/ConstantPool.java index 58e199089ef..27872450487 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/ConstantPool.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/ConstantPool.java @@ -297,6 +297,7 @@ public class ConstantPool extends Oop implements ClassConstants { case JVM_CONSTANT_NameAndType: return "JVM_CONSTANT_NameAndType"; case JVM_CONSTANT_MethodHandle: return "JVM_CONSTANT_MethodHandle"; case JVM_CONSTANT_MethodType: return "JVM_CONSTANT_MethodType"; + case JVM_CONSTANT_InvokeDynamic: return "JVM_CONSTANT_InvokeDynamic"; case JVM_CONSTANT_Invalid: return "JVM_CONSTANT_Invalid"; case JVM_CONSTANT_UnresolvedClass: return "JVM_CONSTANT_UnresolvedClass"; case JVM_CONSTANT_UnresolvedClassInError: return "JVM_CONSTANT_UnresolvedClassInError"; @@ -355,6 +356,7 @@ public class ConstantPool extends Oop implements ClassConstants { case JVM_CONSTANT_NameAndType: case JVM_CONSTANT_MethodHandle: case JVM_CONSTANT_MethodType: + case JVM_CONSTANT_InvokeDynamic: visitor.doInt(new IntField(new NamedFieldIdentifier(nameForTag(ctag)), indexOffset(index), true), true); break; } @@ -517,6 +519,18 @@ public class ConstantPool extends Oop implements ClassConstants { + ", type = " + signatureIndex); break; } + + case JVM_CONSTANT_InvokeDynamic: { + dos.writeByte(cpConstType); + int value = getIntAt(ci); + short bootstrapMethodIndex = (short) extractLowShortFromInt(value); + short nameAndTypeIndex = (short) extractHighShortFromInt(value); + dos.writeShort(bootstrapMethodIndex); + dos.writeShort(nameAndTypeIndex); + if (DEBUG) debugMessage("CP[" + ci + "] = indy BSM = " + bootstrapMethodIndex + + ", N&T = " + nameAndTypeIndex); + break; + } default: throw new InternalError("unknown tag: " + cpConstType); } // switch diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/ClassConstants.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/ClassConstants.java index 889e9dc08b7..ff7db309fe9 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/ClassConstants.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/ClassConstants.java @@ -42,6 +42,7 @@ public interface ClassConstants public static final int JVM_CONSTANT_NameAndType = 12; public static final int JVM_CONSTANT_MethodHandle = 15; public static final int JVM_CONSTANT_MethodType = 16; + public static final int JVM_CONSTANT_InvokeDynamic = 17; // JVM_CONSTANT_MethodHandle subtypes public static final int JVM_REF_getField = 1; diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/jcore/ClassWriter.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/jcore/ClassWriter.java index 99ffaedc8eb..31f37a5df46 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/jcore/ClassWriter.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/jcore/ClassWriter.java @@ -303,12 +303,12 @@ public class ClassWriter implements /* imports */ ClassConstants case JVM_CONSTANT_MethodHandle: { dos.writeByte(cpConstType); int value = cpool.getIntAt(ci); - short refIndex = (short) extractHighShortFromInt(value); - byte refKind = (byte) extractLowShortFromInt(value); - dos.writeByte(refKind); - dos.writeShort(refIndex); - if (DEBUG) debugMessage("CP[" + ci + "] = MH index = " + refIndex - + ", kind = " + refKind); + short bootstrapMethodIndex = (short) extractLowShortFromInt(value); + short nameAndTypeIndex = (short) extractHighShortFromInt(value); + dos.writeShort(bootstrapMethodIndex); + dos.writeShort(nameAndTypeIndex); + if (DEBUG) debugMessage("CP[" + ci + "] = indy BSM = " + + bootstrapMethodIndex + ", N&T = " + nameAndTypeIndex); break; } @@ -321,6 +321,15 @@ public class ClassWriter implements /* imports */ ClassConstants break; } + case JVM_CONSTANT_InvokeDynamic: { + dos.writeByte(cpConstType); + int value = cpool.getIntAt(ci); + short refIndex = (short) value; + dos.writeShort(refIndex); + if (DEBUG) debugMessage("CP[" + ci + "] = MT index = " + refIndex); + break; + } + default: throw new InternalError("Unknown tag: " + cpConstType); } // switch diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ui/classbrowser/HTMLGenerator.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ui/classbrowser/HTMLGenerator.java index 8ef0d8c4d42..d594404f414 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ui/classbrowser/HTMLGenerator.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ui/classbrowser/HTMLGenerator.java @@ -582,6 +582,11 @@ public class HTMLGenerator implements /* imports */ ClassConstants { buf.cell(Integer.toString(cpool.getIntAt(index))); break; + case JVM_CONSTANT_InvokeDynamic: + buf.cell("JVM_CONSTANT_InvokeDynamic"); + buf.cell(genLowHighShort(cpool.getIntAt(index))); + break; + default: throw new InternalError("unknown tag: " + ctag); } diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/utilities/ConstantTag.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/utilities/ConstantTag.java index 2a710c2a002..3f2baf3d9cc 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/utilities/ConstantTag.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/utilities/ConstantTag.java @@ -40,6 +40,7 @@ public class ConstantTag { private static int JVM_CONSTANT_NameAndType = 12; private static int JVM_CONSTANT_MethodHandle = 15; // JSR 292 private static int JVM_CONSTANT_MethodType = 16; // JSR 292 + private static int JVM_CONSTANT_InvokeDynamic = 17; // JSR 292 private static int JVM_CONSTANT_Invalid = 0; // For bad value initialization private static int JVM_CONSTANT_UnresolvedClass = 100; // Temporary tag until actual use private static int JVM_CONSTANT_ClassIndex = 101; // Temporary tag while constructing constant pool @@ -78,6 +79,7 @@ public class ConstantTag { public boolean isUtf8() { return tag == JVM_CONSTANT_Utf8; } public boolean isMethodHandle() { return tag == JVM_CONSTANT_MethodHandle; } public boolean isMethodType() { return tag == JVM_CONSTANT_MethodType; } + public boolean isInvokeDynamic() { return tag == JVM_CONSTANT_InvokeDynamic; } public boolean isInvalid() { return tag == JVM_CONSTANT_Invalid; } diff --git a/hotspot/make/Makefile b/hotspot/make/Makefile index 130a73cdb2c..e55408cc484 100644 --- a/hotspot/make/Makefile +++ b/hotspot/make/Makefile @@ -85,14 +85,21 @@ C1_VM_TARGETS=product1 fastdebug1 optimized1 jvmg1 C2_VM_TARGETS=product fastdebug optimized jvmg KERNEL_VM_TARGETS=productkernel fastdebugkernel optimizedkernel jvmgkernel ZERO_VM_TARGETS=productzero fastdebugzero optimizedzero jvmgzero +SHARK_VM_TARGETS=productshark fastdebugshark optimizedshark jvmgshark # JDK directory list JDK_DIRS=bin include jre lib demo all: all_product all_fastdebug +ifndef BUILD_CLIENT_ONLY all_product: product product1 productkernel docs export_product all_fastdebug: fastdebug fastdebug1 fastdebugkernel docs export_fastdebug all_debug: jvmg jvmg1 jvmgkernel docs export_debug +else +all_product: product1 docs export_product +all_fastdebug: fastdebug1 docs export_fastdebug +all_debug: jvmg1 docs export_debug +endif all_optimized: optimized optimized1 optimizedkernel docs export_optimized allzero: all_productzero all_fastdebugzero @@ -101,6 +108,12 @@ all_fastdebugzero: fastdebugzero docs export_fastdebug all_debugzero: jvmgzero docs export_debug all_optimizedzero: optimizedzero docs export_optimized +allshark: all_productshark all_fastdebugshark +all_productshark: productshark docs export_product +all_fastdebugshark: fastdebugshark docs export_fastdebug +all_debugshark: jvmgshark docs export_debug +all_optimizedshark: optimizedshark docs export_optimized + # Do everything world: all create_jdk @@ -131,6 +144,10 @@ $(ZERO_VM_TARGETS): $(CD) $(GAMMADIR)/make; \ $(MAKE) VM_TARGET=$@ generic_buildzero $(ALT_OUT) +$(SHARK_VM_TARGETS): + $(CD) $(GAMMADIR)/make; \ + $(MAKE) VM_TARGET=$@ generic_buildshark $(ALT_OUT) + # Build compiler1 (client) rule, different for platforms generic_build1: $(MKDIR) -p $(OUTPUTDIR) @@ -197,6 +214,12 @@ generic_buildzero: $(MAKE) -f $(ABS_OS_MAKEFILE) \ $(MAKE_ARGS) $(VM_TARGET) +generic_buildshark: + $(MKDIR) -p $(OUTPUTDIR) + $(CD) $(OUTPUTDIR); \ + $(MAKE) -f $(ABS_OS_MAKEFILE) \ + $(MAKE_ARGS) $(VM_TARGET) + # Export file rule generic_export: $(EXPORT_LIST) export_product: @@ -228,15 +251,22 @@ C1_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_compiler1 C2_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_compiler2 KERNEL_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_kernel ZERO_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_zero +SHARK_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_shark C1_DIR=$(C1_BASE_DIR)/$(VM_SUBDIR) C2_DIR=$(C2_BASE_DIR)/$(VM_SUBDIR) KERNEL_DIR=$(KERNEL_BASE_DIR)/$(VM_SUBDIR) ZERO_DIR=$(ZERO_BASE_DIR)/$(VM_SUBDIR) +SHARK_DIR=$(SHARK_BASE_DIR)/$(VM_SUBDIR) # Misc files and generated files need to come from C1 or C2 area ifeq ($(ZERO_BUILD), true) +ifeq ($(SHARK_BUILD), true) + MISC_DIR=$(SHARK_DIR) + GEN_DIR=$(SHARK_BASE_DIR)/generated +else MISC_DIR=$(ZERO_DIR) GEN_DIR=$(ZERO_BASE_DIR)/generated +endif else ifeq ($(ARCH_DATA_MODEL), 32) MISC_DIR=$(C1_DIR) @@ -290,11 +320,20 @@ endif # Shared Library ifneq ($(OSNAME),windows) ifeq ($(ZERO_BUILD), true) + ifeq ($(SHARK_BUILD), true) +$(EXPORT_JRE_LIB_ARCH_DIR)/%.so: $(SHARK_DIR)/%.so + $(install-file) +$(EXPORT_SERVER_DIR)/%.so: $(SHARK_DIR)/%.so + $(install-file) + else $(EXPORT_JRE_LIB_ARCH_DIR)/%.so: $(ZERO_DIR)/%.so $(install-file) $(EXPORT_SERVER_DIR)/%.so: $(ZERO_DIR)/%.so $(install-file) + endif else +$(EXPORT_JRE_LIB_ARCH_DIR)/%.so: $(C1_DIR)/%.so + $(install-file) $(EXPORT_JRE_LIB_ARCH_DIR)/%.so: $(C2_DIR)/%.so $(install-file) $(EXPORT_CLIENT_DIR)/%.so: $(C1_DIR)/%.so @@ -348,6 +387,7 @@ clean_build: $(RM) -r $(C2_DIR) $(RM) -r $(KERNEL_DIR) $(RM) -r $(ZERO_DIR) + $(RM) -r $(SHARK_DIR) clean_export: $(RM) -r $(EXPORT_PATH) clean_jdk: diff --git a/hotspot/make/defs.make b/hotspot/make/defs.make index be4eda0f1c5..528d9405bf8 100644 --- a/hotspot/make/defs.make +++ b/hotspot/make/defs.make @@ -192,13 +192,16 @@ ifneq ($(OSNAME),windows) # Use uname output for SRCARCH, but deal with platform differences. If ARCH # is not explicitly listed below, it is treated as x86. - SRCARCH = $(ARCH/$(filter sparc sparc64 ia64 amd64 x86_64 zero,$(ARCH))) + SRCARCH = $(ARCH/$(filter sparc sparc64 ia64 amd64 x86_64 arm ppc zero,$(ARCH))) ARCH/ = x86 ARCH/sparc = sparc ARCH/sparc64= sparc ARCH/ia64 = ia64 ARCH/amd64 = x86 ARCH/x86_64 = x86 + ARCH/ppc64 = ppc + ARCH/ppc = ppc + ARCH/arm = arm ARCH/zero = zero # BUILDARCH is usually the same as SRCARCH, except for sparcv9 @@ -223,6 +226,9 @@ ifneq ($(OSNAME),windows) LIBARCH/sparc = sparc LIBARCH/sparcv9 = sparcv9 LIBARCH/ia64 = ia64 + LIBARCH/ppc64 = ppc + LIBARCH/ppc = ppc + LIBARCH/arm = arm LIBARCH/zero = $(ZERO_LIBARCH) LP64_ARCH = sparcv9 amd64 ia64 zero diff --git a/hotspot/make/hotspot_version b/hotspot/make/hotspot_version index 170bf0414cc..dae71d920fb 100644 --- a/hotspot/make/hotspot_version +++ b/hotspot/make/hotspot_version @@ -35,7 +35,7 @@ HOTSPOT_VM_COPYRIGHT=Copyright 2010 HS_MAJOR_VER=19 HS_MINOR_VER=0 -HS_BUILD_NUMBER=04 +HS_BUILD_NUMBER=06 JDK_MAJOR_VER=1 JDK_MINOR_VER=7 diff --git a/hotspot/make/linux/Makefile b/hotspot/make/linux/Makefile index 6d6a1cf4e50..e671c4bf94a 100644 --- a/hotspot/make/linux/Makefile +++ b/hotspot/make/linux/Makefile @@ -1,5 +1,5 @@ # -# Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1999, 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 @@ -168,6 +168,13 @@ VARIANTARCH = $(subst i386,i486,$(ZERO_LIBARCH)) # profiledzero zero __zero/profiled # productzero zero __zero/product # +# debugshark shark __shark/debug +# fastdebugshark shark __shark/fastdebug +# jvmgshark shark __shark/jvmg +# optimizedshark shark __shark/optimized +# profiledshark shark __shark/profiled +# productshark shark __shark/product +# # What you get with each target: # # debug* - "thin" libjvm_g - debug info linked into the gamma_g launcher @@ -191,12 +198,14 @@ SUBDIRS_C2 = $(addprefix $(OSNAME)_$(BUILDARCH)_compiler2/,$(TARGETS)) SUBDIRS_TIERED = $(addprefix $(OSNAME)_$(BUILDARCH)_tiered/,$(TARGETS)) SUBDIRS_CORE = $(addprefix $(OSNAME)_$(BUILDARCH)_core/,$(TARGETS)) SUBDIRS_ZERO = $(addprefix $(OSNAME)_$(VARIANTARCH)_zero/,$(TARGETS)) +SUBDIRS_SHARK = $(addprefix $(OSNAME)_$(VARIANTARCH)_shark/,$(TARGETS)) TARGETS_C2 = $(TARGETS) TARGETS_C1 = $(addsuffix 1,$(TARGETS)) TARGETS_TIERED = $(addsuffix tiered,$(TARGETS)) TARGETS_CORE = $(addsuffix core,$(TARGETS)) TARGETS_ZERO = $(addsuffix zero,$(TARGETS)) +TARGETS_SHARK = $(addsuffix shark,$(TARGETS)) BUILDTREE_MAKE = $(GAMMADIR)/make/$(OSNAME)/makefiles/buildtree.make BUILDTREE_VARS = GAMMADIR=$(GAMMADIR) OS_FAMILY=$(OSNAME) ARCH=$(SRCARCH) BUILDARCH=$(BUILDARCH) LIBARCH=$(LIBARCH) @@ -213,6 +222,7 @@ all: @echo " $(TARGETS_C1)" @echo " $(TARGETS_CORE)" @echo " $(TARGETS_ZERO)" + @echo " $(TARGETS_SHARK)" checks: check_os_version check_j2se_version @@ -266,6 +276,10 @@ $(SUBDIRS_ZERO): $(BUILDTREE_MAKE) platform_zero $(QUIETLY) $(MAKE) -f $(GAMMADIR)/make/$(OSNAME)/Makefile checks $(BUILDTREE) VARIANT=zero VARIANTARCH=$(VARIANTARCH) +$(SUBDIRS_SHARK): $(BUILDTREE_MAKE) platform_zero + $(QUIETLY) $(MAKE) -f $(GAMMADIR)/make/$(OSNAME)/Makefile checks + $(BUILDTREE) VARIANT=shark VARIANTARCH=$(VARIANTARCH) + platform_zero: $(GAMMADIR)/make/$(OSNAME)/platform_zero.in $(SED) 's/@ZERO_ARCHDEF@/$(ZERO_ARCHDEF)/g;s/@ZERO_LIBARCH@/$(ZERO_LIBARCH)/g;' < $< > $@ @@ -306,11 +320,19 @@ ifdef INSTALL cd $(OSNAME)_$(VARIANTARCH)_zero/$(patsubst %zero,%,$@) && $(MAKE) $(MFLAGS) install endif +$(TARGETS_SHARK): $(SUBDIRS_SHARK) + cd $(OSNAME)_$(VARIANTARCH)_shark/$(patsubst %shark,%,$@) && $(MAKE) $(MFLAGS) + cd $(OSNAME)_$(VARIANTARCH)_shark/$(patsubst %shark,%,$@) && ./test_gamma +ifdef INSTALL + cd $(OSNAME)_$(VARIANTARCH)_shark/$(patsubst %shark,%,$@) && $(MAKE) $(MFLAGS) install +endif + # Just build the tree, and nothing else: tree: $(SUBDIRS_C2) tree1: $(SUBDIRS_C1) treecore: $(SUBDIRS_CORE) treezero: $(SUBDIRS_ZERO) +treeshark: $(SUBDIRS_SHARK) # Doc target. This is the same for all build options. # Hence create a docs directory beside ...$(ARCH)_[...] @@ -327,20 +349,22 @@ core: jvmgcore productcore zero: jvmgzero productzero +shark: jvmgshark productshark + clean_docs: rm -rf $(SUBDIR_DOCS) -clean_compiler1 clean_compiler2 clean_core clean_zero: +clean_compiler1 clean_compiler2 clean_core clean_zero clean_shark: rm -rf $(OSNAME)_$(BUILDARCH)_$(subst clean_,,$@) -clean: clean_compiler2 clean_compiler1 clean_core clean_zero clean_docs +clean: clean_compiler2 clean_compiler1 clean_core clean_zero clean_shark clean_docs include $(GAMMADIR)/make/$(OSNAME)/makefiles/cscope.make #------------------------------------------------------------------------------- -.PHONY: $(TARGETS_C2) $(TARGETS_C1) $(TARGETS_CORE) $(TARGETS_ZERO) -.PHONY: tree tree1 treecore treezero -.PHONY: all compiler1 compiler2 core zero -.PHONY: clean clean_compiler1 clean_compiler2 clean_core clean_zero docs clean_docs +.PHONY: $(TARGETS_C2) $(TARGETS_C1) $(TARGETS_CORE) $(TARGETS_ZERO) $(TARGETS_SHARK) +.PHONY: tree tree1 treecore treezero treeshark +.PHONY: all compiler1 compiler2 core zero shark +.PHONY: clean clean_compiler1 clean_compiler2 clean_core clean_zero clean_shark docs clean_docs .PHONY: checks check_os_version check_j2se_version diff --git a/hotspot/make/linux/makefiles/build_vm_def.sh b/hotspot/make/linux/makefiles/build_vm_def.sh index 51a07b9bfa2..2b6f906eee8 100644 --- a/hotspot/make/linux/makefiles/build_vm_def.sh +++ b/hotspot/make/linux/makefiles/build_vm_def.sh @@ -1,5 +1,12 @@ #!/bin/sh -nm --defined-only $* | awk ' +# If we're cross compiling use that path for nm +if [ "$ALT_COMPILER_PATH" != "" ]; then +NM=$ALT_COMPILER_PATH/nm +else +NM=nm +fi + +$NM --defined-only $* | awk ' { if ($3 ~ /^_ZTV/ || $3 ~ /^gHotSpotVM/) print "\t" $3 ";" } ' diff --git a/hotspot/make/linux/makefiles/buildtree.make b/hotspot/make/linux/makefiles/buildtree.make index b7ce6513c98..af34617f46c 100644 --- a/hotspot/make/linux/makefiles/buildtree.make +++ b/hotspot/make/linux/makefiles/buildtree.make @@ -339,12 +339,16 @@ JAVA_FLAG/64 = -d64 WRONG_DATA_MODE_MSG = \ echo "JAVA_HOME must point to $(DATA_MODE)bit JDK." +CROSS_COMPILING_MSG = \ + echo "Cross compiling for ARCH $(CROSS_COMPILE_ARCH), skipping gamma run." + test_gamma: $(BUILDTREE_MAKE) $(GAMMADIR)/make/test/Queens.java @echo Creating $@ ... $(QUIETLY) ( \ echo '#!/bin/sh'; \ $(BUILDTREE_COMMENT); \ echo '. ./env.sh'; \ + echo "if [ \"$(CROSS_COMPILE_ARCH)\" != \"\" ]; then { $(CROSS_COMPILING_MSG); exit 0; }; fi"; \ echo "if [ -z \$$JAVA_HOME ]; then { $(NO_JAVA_HOME_MSG); exit 0; }; fi"; \ echo "if ! \$${JAVA_HOME}/bin/java $(JAVA_FLAG) -fullversion 2>&1 > /dev/null"; \ echo "then"; \ diff --git a/hotspot/make/linux/makefiles/defs.make b/hotspot/make/linux/makefiles/defs.make index 29ef407adb1..561f7f58107 100644 --- a/hotspot/make/linux/makefiles/defs.make +++ b/hotspot/make/linux/makefiles/defs.make @@ -98,6 +98,22 @@ ifeq ($(ARCH), i686) HS_ARCH = x86 endif +# ARM +ifeq ($(ARCH), arm) + ARCH_DATA_MODEL = 32 + PLATFORM = linux-arm + VM_PLATFORM = linux_arm + HS_ARCH = arm +endif + +# PPC +ifeq ($(ARCH), ppc) + ARCH_DATA_MODEL = 32 + PLATFORM = linux-ppc + VM_PLATFORM = linux_ppc + HS_ARCH = ppc +endif + JDK_INCLUDE_SUBDIR=linux # FIXUP: The subdirectory for a debug build is NOT the same on all platforms @@ -107,22 +123,32 @@ EXPORT_LIST += $(EXPORT_DOCS_DIR)/platform/jvmti/jvmti.html # client and server subdirectories have symbolic links to ../libjsig.so EXPORT_LIST += $(EXPORT_JRE_LIB_ARCH_DIR)/libjsig.so - EXPORT_SERVER_DIR = $(EXPORT_JRE_LIB_ARCH_DIR)/server + +ifndef BUILD_CLIENT_ONLY EXPORT_LIST += $(EXPORT_SERVER_DIR)/Xusage.txt EXPORT_LIST += $(EXPORT_SERVER_DIR)/libjvm.so +endif + ifneq ($(ZERO_BUILD), true) ifeq ($(ARCH_DATA_MODEL), 32) EXPORT_CLIENT_DIR = $(EXPORT_JRE_LIB_ARCH_DIR)/client EXPORT_LIST += $(EXPORT_CLIENT_DIR)/Xusage.txt EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm.so - EXPORT_LIST += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.so - EXPORT_LIST += $(EXPORT_LIB_DIR)/sa-jdi.jar - else - ifeq ($(ARCH),ia64) - else - EXPORT_LIST += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.so - EXPORT_LIST += $(EXPORT_LIB_DIR)/sa-jdi.jar - endif endif endif + +# Serviceability Binaries +# No SA Support for PPC, IA64, ARM or zero +ADD_SA_BINARIES/x86 = $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.so \ + $(EXPORT_LIB_DIR)/sa-jdi.jar +ADD_SA_BINARIES/sparc = $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.so \ + $(EXPORT_LIB_DIR)/sa-jdi.jar +ADD_SA_BINARIES/ppc = +ADD_SA_BINARIES/ia64 = +ADD_SA_BINARIES/arm = +ADD_SA_BINARIES/zero = + +EXPORT_LIST += $(ADD_SA_BINARIES/$(HS_ARCH)) + + diff --git a/hotspot/make/linux/makefiles/gcc.make b/hotspot/make/linux/makefiles/gcc.make index e7ed00e9137..7107858f7d9 100644 --- a/hotspot/make/linux/makefiles/gcc.make +++ b/hotspot/make/linux/makefiles/gcc.make @@ -1,5 +1,5 @@ # -# Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1999, 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 @@ -25,8 +25,14 @@ #------------------------------------------------------------------------ # CC, CPP & AS +ifdef ALT_COMPILER_PATH +CPP = $(ALT_COMPILER_PATH)/g++ +CC = $(ALT_COMPILER_PATH)/gcc +else CPP = g++ CC = gcc +endif + AS = $(CC) -c # -dumpversion in gcc-2.91 shows "egcs-2.91.66". In later version, it only @@ -55,6 +61,9 @@ VM_PICFLAG = $(VM_PICFLAG/$(LINK_INTO)) ifeq ($(ZERO_BUILD), true) CFLAGS += $(LIBFFI_CFLAGS) endif +ifeq ($(SHARK_BUILD), true) +CFLAGS += $(LLVM_CFLAGS) +endif CFLAGS += $(VM_PICFLAG) CFLAGS += -fno-rtti CFLAGS += -fno-exceptions @@ -67,18 +76,31 @@ ARCHFLAG/amd64 = -m64 ARCHFLAG/ia64 = ARCHFLAG/sparc = -m32 -mcpu=v9 ARCHFLAG/sparcv9 = -m64 -mcpu=v9 +ARCHFLAG/arm = -fsigned-char ARCHFLAG/zero = $(ZERO_ARCHFLAG) +ifndef E500V2 +ARCHFLAG/ppc = -mcpu=powerpc +endif CFLAGS += $(ARCHFLAG) AOUT_FLAGS += $(ARCHFLAG) LFLAGS += $(ARCHFLAG) ASFLAGS += $(ARCHFLAG) +ifdef E500V2 +CFLAGS += -DE500V2 +endif + # Use C++ Interpreter ifdef CC_INTERP CFLAGS += -DCC_INTERP endif +# Build for embedded targets +ifdef JAVASE_EMBEDDED + CFLAGS += -DJAVASE_EMBEDDED +endif + # Keep temporary files (.ii, .s) ifdef NEED_ASM CFLAGS += -save-temps @@ -171,6 +193,8 @@ AOUT_FLAGS += -export-dynamic # Note: The Itanium gcc compiler crashes when using -gstabs. DEBUG_CFLAGS/ia64 = -g DEBUG_CFLAGS/amd64 = -g +DEBUG_CFLAGS/arm = -g +DEBUG_CFLAGS/ppc = -g DEBUG_CFLAGS += $(DEBUG_CFLAGS/$(BUILDARCH)) ifeq ($(DEBUG_CFLAGS/$(BUILDARCH)),) DEBUG_CFLAGS += -gstabs @@ -181,3 +205,15 @@ ifeq ($(DEBUG_BINARIES), true) DEBUG_CFLAGS = -g CFLAGS += $(DEBUG_CFLAGS) endif + +# If we are building HEADLESS, pass on to VM +# so it can set the java.awt.headless property +ifdef HEADLESS +CFLAGS += -DHEADLESS +endif + +# We are building Embedded for a small device +# favor code space over speed +ifdef MINIMIZE_RAM_USAGE +CFLAGS += -DMINIMIZE_RAM_USAGE +endif diff --git a/hotspot/make/linux/makefiles/product.make b/hotspot/make/linux/makefiles/product.make index 82ed58a1fcd..ff768b6a6bd 100644 --- a/hotspot/make/linux/makefiles/product.make +++ b/hotspot/make/linux/makefiles/product.make @@ -46,7 +46,11 @@ VERSION = optimized # use -g to strip library as -x will discard its symbol table; -x is fine for # executables. -STRIP = strip +ifdef CROSS_COMPILE_ARCH + STRIP = $(ALT_COMPILER_PATH)/strip +else + STRIP = strip +endif STRIP_LIBJVM = $(STRIP) -g $@ || exit 1; STRIP_AOUT = $(STRIP) -x $@ || exit 1; diff --git a/hotspot/make/linux/makefiles/sa.make b/hotspot/make/linux/makefiles/sa.make index f7a1a208ba7..19d68083ede 100644 --- a/hotspot/make/linux/makefiles/sa.make +++ b/hotspot/make/linux/makefiles/sa.make @@ -55,10 +55,13 @@ SA_BUILD_VERSION_PROP = "sun.jvm.hotspot.runtime.VM.saBuildVersion=$(SA_BUILD_VE SA_PROPERTIES = $(SA_CLASSDIR)/sa.properties # if $(AGENT_DIR) does not exist, we don't build SA -# also, we don't build SA on Itanium or zero. +# also, we don't build SA on Itanium, PowerPC, ARM or zero. all: - if [ -d $(AGENT_DIR) -a "$(SRCARCH)" != "ia64" -a "$(SRCARCH)" != "zero" ] ; then \ + if [ -d $(AGENT_DIR) -a "$(SRCARCH)" != "ia64" \ + -a "$(SRCARCH)" != "arm" \ + -a "$(SRCARCH)" != "ppc" \ + -a "$(SRCARCH)" != "zero" ] ; then \ $(MAKE) -f sa.make $(GENERATED)/sa-jdi.jar; \ fi diff --git a/hotspot/make/linux/makefiles/saproc.make b/hotspot/make/linux/makefiles/saproc.make index 1da5c217d07..bc4fc66c5fa 100644 --- a/hotspot/make/linux/makefiles/saproc.make +++ b/hotspot/make/linux/makefiles/saproc.make @@ -53,10 +53,10 @@ ifeq ($(DEBUG_BINARIES), true) endif # if $(AGENT_DIR) does not exist, we don't build SA -# also, we don't build SA on Itanium or zero. +# also, we don't build SA on Itanium, PPC, ARM or zero. checkAndBuildSA: - $(QUIETLY) if [ -d $(AGENT_DIR) -a "$(SRCARCH)" != "ia64" -a "$(SRCARCH)" != "zero" ] ; then \ + $(QUIETLY) if [ -d $(AGENT_DIR) -a "$(SRCARCH)" != "ia64" -a "$(SRCARCH)" != "arm" -a "$(SRCARCH)" != "ppc" -a "$(SRCARCH)" != "zero" ] ; then \ $(MAKE) -f vm.make $(LIBSAPROC); \ fi diff --git a/hotspot/make/linux/makefiles/shark.make b/hotspot/make/linux/makefiles/shark.make new file mode 100644 index 00000000000..f767a805039 --- /dev/null +++ b/hotspot/make/linux/makefiles/shark.make @@ -0,0 +1,32 @@ +# +# Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved. +# Copyright 2008, 2010 Red Hat, Inc. +# 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. +# +# + +# Sets make macros for making Shark version of VM + +TYPE = SHARK + +VM_SUBDIR = server + +CFLAGS += -DSHARK diff --git a/hotspot/make/linux/makefiles/top.make b/hotspot/make/linux/makefiles/top.make index 393040d7e0d..c9988f6aba7 100644 --- a/hotspot/make/linux/makefiles/top.make +++ b/hotspot/make/linux/makefiles/top.make @@ -1,5 +1,5 @@ # -# Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1999, 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 @@ -75,6 +75,7 @@ Include_DBs/COMPILER1 = $(Include_DBs/CORE) $(VM)/includeDB_compiler1 Include_DBs/COMPILER2 = $(Include_DBs/CORE) $(VM)/includeDB_compiler2 Include_DBs/TIERED = $(Include_DBs/CORE) $(VM)/includeDB_compiler1 $(VM)/includeDB_compiler2 Include_DBs/ZERO = $(Include_DBs/CORE) $(VM)/includeDB_zero +Include_DBs/SHARK = $(Include_DBs/ZERO) $(VM)/includeDB_shark Include_DBs = $(Include_DBs/$(TYPE)) Cached_plat = $(GENERATED)/platform.current diff --git a/hotspot/make/linux/makefiles/vm.make b/hotspot/make/linux/makefiles/vm.make index 0f8bccd2a16..92add561f09 100644 --- a/hotspot/make/linux/makefiles/vm.make +++ b/hotspot/make/linux/makefiles/vm.make @@ -1,5 +1,5 @@ # -# Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1999, 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 @@ -98,6 +98,7 @@ CFLAGS += $(CFLAGS/NOEX) # Extra flags from gnumake's invocation or environment CFLAGS += $(EXTRA_CFLAGS) +LFLAGS += $(EXTRA_CFLAGS) LIBS += -lm -ldl -lpthread @@ -136,10 +137,14 @@ mapfile_reorder : mapfile $(REORDERFILE) vm.def: $(Res_Files) $(Obj_Files) sh $(GAMMADIR)/make/linux/makefiles/build_vm_def.sh *.o > $@ -ifeq ($(ZERO_LIBARCH), ppc64) +ifeq ($(SHARK_BUILD), true) STATIC_CXX = false else - STATIC_CXX = true + ifeq ($(ZERO_LIBARCH), ppc64) + STATIC_CXX = false + else + STATIC_CXX = true + endif endif ifeq ($(LINK_INTO),AOUT) @@ -167,6 +172,10 @@ endif ifeq ($(ZERO_BUILD), true) LIBS_VM += $(LIBFFI_LIBS) endif +ifeq ($(SHARK_BUILD), true) + LFLAGS_VM += $(LLVM_LDFLAGS) + LIBS_VM += $(LLVM_LIBS) +endif LINK_VM = $(LINK_LIB.c) @@ -210,15 +219,17 @@ $(LIBJVM): $(LIBJVM.o) $(LIBJVM_MAPFILE) $(LD_SCRIPT) $(LINK_LIB.CC/POST_HOOK) \ rm -f $@.1; ln -s $@ $@.1; \ [ -f $(LIBJVM_G) ] || { ln -s $@ $(LIBJVM_G); ln -s $@.1 $(LIBJVM_G).1; }; \ - if [ -x /usr/sbin/selinuxenabled ] ; then \ - /usr/sbin/selinuxenabled; \ - if [ $$? = 0 ] ; then \ - /usr/bin/chcon -t textrel_shlib_t $@; \ - if [ $$? != 0 ]; then \ - echo "ERROR: Cannot chcon $@"; \ - fi \ - fi \ - fi \ + if [ \"$(CROSS_COMPILE_ARCH)\" = \"\" ] ; then \ + if [ -x /usr/sbin/selinuxenabled ] ; then \ + /usr/sbin/selinuxenabled; \ + if [ $$? = 0 ] ; then \ + /usr/bin/chcon -t textrel_shlib_t $@; \ + if [ $$? != 0 ]; then \ + echo "ERROR: Cannot chcon $@"; \ + fi \ + fi \ + fi \ + fi \ } DEST_JVM = $(JDK_LIBDIR)/$(VM_SUBDIR)/$(LIBJVM) diff --git a/hotspot/make/solaris/makefiles/defs.make b/hotspot/make/solaris/makefiles/defs.make index 9e1d981cee0..637b3b49c54 100644 --- a/hotspot/make/solaris/makefiles/defs.make +++ b/hotspot/make/solaris/makefiles/defs.make @@ -70,20 +70,24 @@ EXPORT_LIST += $(EXPORT_DOCS_DIR)/platform/jvmti/jvmti.html EXPORT_LIST += $(EXPORT_JRE_LIB_ARCH_DIR)/libjsig.so EXPORT_SERVER_DIR = $(EXPORT_JRE_LIB_ARCH_DIR)/server +ifneq ($(BUILD_CLIENT_ONLY),true) EXPORT_LIST += $(EXPORT_SERVER_DIR)/Xusage.txt EXPORT_LIST += $(EXPORT_SERVER_DIR)/libjvm.so EXPORT_LIST += $(EXPORT_SERVER_DIR)/libjvm_db.so EXPORT_LIST += $(EXPORT_SERVER_DIR)/libjvm_dtrace.so +endif ifeq ($(ARCH_DATA_MODEL), 32) EXPORT_CLIENT_DIR = $(EXPORT_JRE_LIB_ARCH_DIR)/client EXPORT_LIST += $(EXPORT_CLIENT_DIR)/Xusage.txt EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm.so EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm_db.so - EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm_dtrace.so - EXPORT_LIST += $(EXPORT_SERVER_DIR)/64/libjvm_db.so + EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm_dtrace.so EXPORT_LIST += $(EXPORT_CLIENT_DIR)/64/libjvm_db.so - EXPORT_LIST += $(EXPORT_SERVER_DIR)/64/libjvm_dtrace.so EXPORT_LIST += $(EXPORT_CLIENT_DIR)/64/libjvm_dtrace.so + ifneq ($(BUILD_CLIENT_ONLY), true) + EXPORT_LIST += $(EXPORT_SERVER_DIR)/64/libjvm_db.so + EXPORT_LIST += $(EXPORT_SERVER_DIR)/64/libjvm_dtrace.so + endif endif EXPORT_LIST += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.so diff --git a/hotspot/make/solaris/makefiles/sparcWorks.make b/hotspot/make/solaris/makefiles/sparcWorks.make index a8beca11226..34b279b7266 100644 --- a/hotspot/make/solaris/makefiles/sparcWorks.make +++ b/hotspot/make/solaris/makefiles/sparcWorks.make @@ -145,11 +145,20 @@ OPT_CFLAGS/SLOWER=-xO3 OPT_CFLAGS/O2=-xO2 OPT_CFLAGS/NOOPT=-xO1 +################################################# +# Begin current (>=5.9) Forte compiler options # +################################################# + ifeq ($(shell expr $(COMPILER_REV_NUMERIC) \>= 509), 1) ifeq ($(Platform_arch), x86) OPT_CFLAGS/NO_TAIL_CALL_OPT = -Wu,-O~yz OPT_CCFLAGS/NO_TAIL_CALL_OPT = -Qoption ube -O~yz +OPT_CFLAGS/stubGenerator_x86_32.o = $(OPT_CFLAGS) -xspace +OPT_CFLAGS/stubGenerator_x86_64.o = $(OPT_CFLAGS) -xspace endif # Platform_arch == x86 +ifeq ("${Platform_arch}", "sparc") +OPT_CFLAGS/stubGenerator_sparc.o = $(OPT_CFLAGS) -xspace +endif endif # COMPILER_REV_NUMERIC >= 509 ################################################# diff --git a/hotspot/src/cpu/sparc/vm/assembler_sparc.cpp b/hotspot/src/cpu/sparc/vm/assembler_sparc.cpp index e9e55062627..1239483966c 100644 --- a/hotspot/src/cpu/sparc/vm/assembler_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/assembler_sparc.cpp @@ -626,7 +626,7 @@ void MacroAssembler::jmp(Register r1, int offset, const char* file, int line ) { } // This code sequence is relocatable to any address, even on LP64. -void MacroAssembler::jumpl(AddressLiteral& addrlit, Register temp, Register d, int offset, const char* file, int line) { +void MacroAssembler::jumpl(const AddressLiteral& addrlit, Register temp, Register d, int offset, const char* file, int line) { assert_not_delayed(); // Force fixed length sethi because NativeJump and NativeFarCall don't handle // variable length instruction streams. @@ -672,7 +672,7 @@ void MacroAssembler::jumpl(AddressLiteral& addrlit, Register temp, Register d, i } } -void MacroAssembler::jump(AddressLiteral& addrlit, Register temp, int offset, const char* file, int line) { +void MacroAssembler::jump(const AddressLiteral& addrlit, Register temp, int offset, const char* file, int line) { jumpl(addrlit, temp, G0, offset, file, line); } diff --git a/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp b/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp index 2f95cb9e8bd..4592ed81fea 100644 --- a/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp +++ b/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp @@ -1974,12 +1974,12 @@ public: // address pseudos: make these names unlike instruction names to avoid confusion inline intptr_t load_pc_address( Register reg, int bytes_to_skip ); - inline void load_contents(AddressLiteral& addrlit, Register d, int offset = 0); - inline void load_ptr_contents(AddressLiteral& addrlit, Register d, int offset = 0); - inline void store_contents(Register s, AddressLiteral& addrlit, Register temp, int offset = 0); - inline void store_ptr_contents(Register s, AddressLiteral& addrlit, Register temp, int offset = 0); - inline void jumpl_to(AddressLiteral& addrlit, Register temp, Register d, int offset = 0); - inline void jump_to(AddressLiteral& addrlit, Register temp, int offset = 0); + inline void load_contents(const AddressLiteral& addrlit, Register d, int offset = 0); + inline void load_ptr_contents(const AddressLiteral& addrlit, Register d, int offset = 0); + inline void store_contents(Register s, const AddressLiteral& addrlit, Register temp, int offset = 0); + inline void store_ptr_contents(Register s, const AddressLiteral& addrlit, Register temp, int offset = 0); + inline void jumpl_to(const AddressLiteral& addrlit, Register temp, Register d, int offset = 0); + inline void jump_to(const AddressLiteral& addrlit, Register temp, int offset = 0); inline void jump_indirect_to(Address& a, Register temp, int ld_offset = 0, int jmp_offset = 0); // ring buffer traceable jumps @@ -1987,8 +1987,8 @@ public: void jmp2( Register r1, Register r2, const char* file, int line ); void jmp ( Register r1, int offset, const char* file, int line ); - void jumpl(AddressLiteral& addrlit, Register temp, Register d, int offset, const char* file, int line); - void jump (AddressLiteral& addrlit, Register temp, int offset, const char* file, int line); + void jumpl(const AddressLiteral& addrlit, Register temp, Register d, int offset, const char* file, int line); + void jump (const AddressLiteral& addrlit, Register temp, int offset, const char* file, int line); // argument pseudos: diff --git a/hotspot/src/cpu/sparc/vm/assembler_sparc.inline.hpp b/hotspot/src/cpu/sparc/vm/assembler_sparc.inline.hpp index 3ebf9c1c091..88cf8f5eee0 100644 --- a/hotspot/src/cpu/sparc/vm/assembler_sparc.inline.hpp +++ b/hotspot/src/cpu/sparc/vm/assembler_sparc.inline.hpp @@ -650,28 +650,28 @@ inline intptr_t MacroAssembler::load_pc_address( Register reg, int bytes_to_skip } -inline void MacroAssembler::load_contents(AddressLiteral& addrlit, Register d, int offset) { +inline void MacroAssembler::load_contents(const AddressLiteral& addrlit, Register d, int offset) { assert_not_delayed(); sethi(addrlit, d); ld(d, addrlit.low10() + offset, d); } -inline void MacroAssembler::load_ptr_contents(AddressLiteral& addrlit, Register d, int offset) { +inline void MacroAssembler::load_ptr_contents(const AddressLiteral& addrlit, Register d, int offset) { assert_not_delayed(); sethi(addrlit, d); ld_ptr(d, addrlit.low10() + offset, d); } -inline void MacroAssembler::store_contents(Register s, AddressLiteral& addrlit, Register temp, int offset) { +inline void MacroAssembler::store_contents(Register s, const AddressLiteral& addrlit, Register temp, int offset) { assert_not_delayed(); sethi(addrlit, temp); st(s, temp, addrlit.low10() + offset); } -inline void MacroAssembler::store_ptr_contents(Register s, AddressLiteral& addrlit, Register temp, int offset) { +inline void MacroAssembler::store_ptr_contents(Register s, const AddressLiteral& addrlit, Register temp, int offset) { assert_not_delayed(); sethi(addrlit, temp); st_ptr(s, temp, addrlit.low10() + offset); @@ -679,7 +679,7 @@ inline void MacroAssembler::store_ptr_contents(Register s, AddressLiteral& addrl // This code sequence is relocatable to any address, even on LP64. -inline void MacroAssembler::jumpl_to(AddressLiteral& addrlit, Register temp, Register d, int offset) { +inline void MacroAssembler::jumpl_to(const AddressLiteral& addrlit, Register temp, Register d, int offset) { assert_not_delayed(); // Force fixed length sethi because NativeJump and NativeFarCall don't handle // variable length instruction streams. @@ -688,7 +688,7 @@ inline void MacroAssembler::jumpl_to(AddressLiteral& addrlit, Register temp, Reg } -inline void MacroAssembler::jump_to(AddressLiteral& addrlit, Register temp, int offset) { +inline void MacroAssembler::jump_to(const AddressLiteral& addrlit, Register temp, int offset) { jumpl_to(addrlit, temp, G0, offset); } diff --git a/hotspot/src/cpu/sparc/vm/bytecodeInterpreter_sparc.inline.hpp b/hotspot/src/cpu/sparc/vm/bytecodeInterpreter_sparc.inline.hpp index c143939d401..6bd42a8ec84 100644 --- a/hotspot/src/cpu/sparc/vm/bytecodeInterpreter_sparc.inline.hpp +++ b/hotspot/src/cpu/sparc/vm/bytecodeInterpreter_sparc.inline.hpp @@ -236,19 +236,19 @@ inline jint BytecodeInterpreter::VMintRem(jint op1, jint op2) { } inline jint BytecodeInterpreter::VMintShl(jint op1, jint op2) { - return op1 << op2; + return op1 << (op2 & 0x1f); } inline jint BytecodeInterpreter::VMintShr(jint op1, jint op2) { - return op1 >> op2; // QQ op2 & 0x1f?? + return op1 >> (op2 & 0x1f); } inline jint BytecodeInterpreter::VMintSub(jint op1, jint op2) { return op1 - op2; } -inline jint BytecodeInterpreter::VMintUshr(jint op1, jint op2) { - return ((juint) op1) >> op2; // QQ op2 & 0x1f?? +inline juint BytecodeInterpreter::VMintUshr(jint op1, jint op2) { + return ((juint) op1) >> (op2 & 0x1f); } inline jint BytecodeInterpreter::VMintXor(jint op1, jint op2) { diff --git a/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp b/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp index a8b7b08154d..04a8be9c431 100644 --- a/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp @@ -409,7 +409,7 @@ void LIRGenerator::do_MonitorExit(MonitorExit* x) { LIR_Opr lock = FrameMap::G1_opr; LIR_Opr hdr = FrameMap::G3_opr; LIR_Opr obj_temp = FrameMap::G4_opr; - monitor_exit(obj_temp, lock, hdr, x->monitor_no()); + monitor_exit(obj_temp, lock, hdr, LIR_OprFact::illegalOpr, x->monitor_no()); } diff --git a/hotspot/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp b/hotspot/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp index e1e4c3ac17e..3a4ebb94e58 100644 --- a/hotspot/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp @@ -1031,3 +1031,7 @@ void Runtime1::generate_handle_exception(StubAssembler* sasm, OopMapSet* oop_map #undef __ #define __ masm-> + +const char *Runtime1::pd_name_for_address(address entry) { + return ""; +} diff --git a/hotspot/src/cpu/sparc/vm/interpreterRT_sparc.cpp b/hotspot/src/cpu/sparc/vm/interpreterRT_sparc.cpp index 9bd6e0b0732..fb95f8ad4a3 100644 --- a/hotspot/src/cpu/sparc/vm/interpreterRT_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/interpreterRT_sparc.cpp @@ -56,14 +56,18 @@ void InterpreterRuntime::SignatureHandlerGenerator::pass_long() { } -#ifdef _LP64 void InterpreterRuntime::SignatureHandlerGenerator::pass_float() { Argument jni_arg(jni_offset(), false); +#ifdef _LP64 FloatRegister Rtmp = F0; __ ldf(FloatRegisterImpl::S, Llocals, Interpreter::local_offset_in_bytes(offset()), Rtmp); __ store_float_argument(Rtmp, jni_arg); -} +#else + Register Rtmp = O0; + __ ld(Llocals, Interpreter::local_offset_in_bytes(offset()), Rtmp); + __ store_argument(Rtmp, jni_arg); #endif +} void InterpreterRuntime::SignatureHandlerGenerator::pass_double() { @@ -185,6 +189,13 @@ class SlowSignatureHandler: public NativeSignatureIterator { _from -= 2*Interpreter::stackElementSize; add_signature( non_float ); } + + virtual void pass_float() { + *_to++ = *(jint *)(_from+Interpreter::local_offset_in_bytes(0)); + _from -= Interpreter::stackElementSize; + add_signature( non_float ); + } + #endif // _LP64 virtual void add_signature( intptr_t sig_type ) { diff --git a/hotspot/src/cpu/sparc/vm/javaFrameAnchor_sparc.hpp b/hotspot/src/cpu/sparc/vm/javaFrameAnchor_sparc.hpp index 783f099f834..f9607f8fede 100644 --- a/hotspot/src/cpu/sparc/vm/javaFrameAnchor_sparc.hpp +++ b/hotspot/src/cpu/sparc/vm/javaFrameAnchor_sparc.hpp @@ -76,6 +76,8 @@ public: void set_last_Java_sp(intptr_t* sp) { _last_Java_sp = sp; } + address last_Java_pc(void) { return _last_Java_pc; } + // These are only used by friends private: diff --git a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp index 65404a44d66..99a7eebf4c4 100644 --- a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp @@ -1007,9 +1007,9 @@ class StubGenerator: public StubCodeGenerator { __ brx(Assembler::lessEqualUnsigned, false, Assembler::pt, (*NOLp)); __ delayed()->cmp(to_from, byte_count); if (NOLp == NULL) - __ brx(Assembler::greaterEqual, false, Assembler::pt, no_overlap_target); + __ brx(Assembler::greaterEqualUnsigned, false, Assembler::pt, no_overlap_target); else - __ brx(Assembler::greaterEqual, false, Assembler::pt, (*NOLp)); + __ brx(Assembler::greaterEqualUnsigned, false, Assembler::pt, (*NOLp)); __ delayed()->nop(); } diff --git a/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp b/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp index fbb4d0b557e..7a45489be40 100644 --- a/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp @@ -3236,12 +3236,14 @@ void TemplateTable::_new() { __ get_2_byte_integer_at_bcp(1, Rscratch, Roffset, InterpreterMacroAssembler::Unsigned); __ get_cpool_and_tags(Rscratch, G3_scratch); // make sure the class we're about to instantiate has been resolved + // This is done before loading instanceKlass to be consistent with the order + // how Constant Pool is updated (see constantPoolOopDesc::klass_at_put) __ add(G3_scratch, typeArrayOopDesc::header_size(T_BYTE) * wordSize, G3_scratch); __ ldub(G3_scratch, Roffset, G3_scratch); __ cmp(G3_scratch, JVM_CONSTANT_Class); __ br(Assembler::notEqual, false, Assembler::pn, slow_case); __ delayed()->sll(Roffset, LogBytesPerWord, Roffset); - + // get instanceKlass //__ sll(Roffset, LogBytesPerWord, Roffset); // executed in delay slot __ add(Roffset, sizeof(constantPoolOopDesc), Roffset); __ ld_ptr(Rscratch, Roffset, RinstanceKlass); diff --git a/hotspot/src/cpu/x86/vm/assembler_x86.cpp b/hotspot/src/cpu/x86/vm/assembler_x86.cpp index ab758216c57..bb7517f533d 100644 --- a/hotspot/src/cpu/x86/vm/assembler_x86.cpp +++ b/hotspot/src/cpu/x86/vm/assembler_x86.cpp @@ -7151,7 +7151,7 @@ void MacroAssembler::tlab_refill(Label& retry, subptr(t1, typeArrayOopDesc::header_size(T_INT)); addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve()); shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint))); - movptr(Address(top, arrayOopDesc::length_offset_in_bytes()), t1); + movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1); // set klass to intArrayKlass // dubious reloc why not an oop reloc? movptr(t1, ExternalAddress((address) Universe::intArrayKlassObj_addr())); @@ -7568,21 +7568,27 @@ void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass, // Scan RCX words at [RDI] for an occurrence of RAX. // Set NZ/Z based on last compare. + // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does + // not change flags (only scas instruction which is repeated sets flags). + // Set Z = 0 (not equal) before 'repne' to indicate that class was not found. #ifdef _LP64 // This part is tricky, as values in supers array could be 32 or 64 bit wide // and we store values in objArrays always encoded, thus we need to encode // the value of rax before repne. Note that rax is dead after the repne. if (UseCompressedOops) { - encode_heap_oop_not_null(rax); + encode_heap_oop_not_null(rax); // Changes flags. // The superclass is never null; it would be a basic system error if a null // pointer were to sneak in here. Note that we have already loaded the // Klass::super_check_offset from the super_klass in the fast path, // so if there is a null in that register, we are already in the afterlife. + testl(rax,rax); // Set Z = 0 repne_scanl(); } else #endif // _LP64 + { + testptr(rax,rax); // Set Z = 0 repne_scan(); - + } // Unspill the temp. registers: if (pushed_rdi) pop(rdi); if (pushed_rcx) pop(rcx); @@ -8257,30 +8263,35 @@ void MacroAssembler::store_heap_oop_null(Address dst) { } } -// Algorithm must match oop.inline.hpp encode_heap_oop. -void MacroAssembler::encode_heap_oop(Register r) { +#ifdef ASSERT +void MacroAssembler::verify_heapbase(const char* msg) { assert (UseCompressedOops, "should be compressed"); assert (Universe::heap() != NULL, "java heap should be initialized"); + if (CheckCompressedOops) { + Label ok; + push(rscratch1); // cmpptr trashes rscratch1 + cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_oop_base_addr())); + jcc(Assembler::equal, ok); + stop(msg); + bind(ok); + pop(rscratch1); + } +} +#endif + +// Algorithm must match oop.inline.hpp encode_heap_oop. +void MacroAssembler::encode_heap_oop(Register r) { +#ifdef ASSERT + verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?"); +#endif + verify_oop(r, "broken oop in encode_heap_oop"); if (Universe::narrow_oop_base() == NULL) { - verify_oop(r, "broken oop in encode_heap_oop"); if (Universe::narrow_oop_shift() != 0) { assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong"); shrq(r, LogMinObjAlignmentInBytes); } return; } -#ifdef ASSERT - if (CheckCompressedOops) { - Label ok; - push(rscratch1); // cmpptr trashes rscratch1 - cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_oop_base_addr())); - jcc(Assembler::equal, ok); - stop("MacroAssembler::encode_heap_oop: heap base corrupted?"); - bind(ok); - pop(rscratch1); - } -#endif - verify_oop(r, "broken oop in encode_heap_oop"); testq(r, r); cmovq(Assembler::equal, r, r12_heapbase); subq(r, r12_heapbase); @@ -8288,9 +8299,8 @@ void MacroAssembler::encode_heap_oop(Register r) { } void MacroAssembler::encode_heap_oop_not_null(Register r) { - assert (UseCompressedOops, "should be compressed"); - assert (Universe::heap() != NULL, "java heap should be initialized"); #ifdef ASSERT + verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?"); if (CheckCompressedOops) { Label ok; testq(r, r); @@ -8310,9 +8320,8 @@ void MacroAssembler::encode_heap_oop_not_null(Register r) { } void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) { - assert (UseCompressedOops, "should be compressed"); - assert (Universe::heap() != NULL, "java heap should be initialized"); #ifdef ASSERT + verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?"); if (CheckCompressedOops) { Label ok; testq(src, src); @@ -8335,40 +8344,21 @@ void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) { } void MacroAssembler::decode_heap_oop(Register r) { - assert (UseCompressedOops, "should be compressed"); - assert (Universe::heap() != NULL, "java heap should be initialized"); +#ifdef ASSERT + verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?"); +#endif if (Universe::narrow_oop_base() == NULL) { if (Universe::narrow_oop_shift() != 0) { assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong"); shlq(r, LogMinObjAlignmentInBytes); } - verify_oop(r, "broken oop in decode_heap_oop"); - return; + } else { + Label done; + shlq(r, LogMinObjAlignmentInBytes); + jccb(Assembler::equal, done); + addq(r, r12_heapbase); + bind(done); } -#ifdef ASSERT - if (CheckCompressedOops) { - Label ok; - push(rscratch1); - cmpptr(r12_heapbase, - ExternalAddress((address)Universe::narrow_oop_base_addr())); - jcc(Assembler::equal, ok); - stop("MacroAssembler::decode_heap_oop: heap base corrupted?"); - bind(ok); - pop(rscratch1); - } -#endif - - Label done; - shlq(r, LogMinObjAlignmentInBytes); - jccb(Assembler::equal, done); - addq(r, r12_heapbase); -#if 0 - // alternate decoding probably a wash. - testq(r, r); - jccb(Assembler::equal, done); - leaq(r, Address(r12_heapbase, r, Address::times_8, 0)); -#endif - bind(done); verify_oop(r, "broken oop in decode_heap_oop"); } @@ -8410,9 +8400,11 @@ void MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) { addq(dst, r12_heapbase); } } - } else if (dst != src) { + } else { assert (Universe::narrow_oop_base() == NULL, "sanity"); - movq(dst, src); + if (dst != src) { + movq(dst, src); + } } } diff --git a/hotspot/src/cpu/x86/vm/assembler_x86.hpp b/hotspot/src/cpu/x86/vm/assembler_x86.hpp index 5384f6bf46b..2ee35280959 100644 --- a/hotspot/src/cpu/x86/vm/assembler_x86.hpp +++ b/hotspot/src/cpu/x86/vm/assembler_x86.hpp @@ -1714,6 +1714,9 @@ class MacroAssembler: public Assembler { // if heap base register is used - reinit it with the correct value void reinit_heapbase(); + + DEBUG_ONLY(void verify_heapbase(const char* msg);) + #endif // _LP64 // Int division/remainder for Java diff --git a/hotspot/src/cpu/x86/vm/bytecodeInterpreter_x86.inline.hpp b/hotspot/src/cpu/x86/vm/bytecodeInterpreter_x86.inline.hpp index a8e600db946..1c5616aa352 100644 --- a/hotspot/src/cpu/x86/vm/bytecodeInterpreter_x86.inline.hpp +++ b/hotspot/src/cpu/x86/vm/bytecodeInterpreter_x86.inline.hpp @@ -236,11 +236,11 @@ inline jint BytecodeInterpreter::VMintRem(jint op1, jint op2) { } inline jint BytecodeInterpreter::VMintShl(jint op1, jint op2) { - return op1 << op2; + return op1 << op2; } inline jint BytecodeInterpreter::VMintShr(jint op1, jint op2) { - return op1 >> op2; // QQ op2 & 0x1f?? + return op1 >> (op2 & 0x1f); } inline jint BytecodeInterpreter::VMintSub(jint op1, jint op2) { @@ -248,7 +248,7 @@ inline jint BytecodeInterpreter::VMintSub(jint op1, jint op2) { } inline jint BytecodeInterpreter::VMintUshr(jint op1, jint op2) { - return ((juint) op1) >> op2; // QQ op2 & 0x1f?? + return ((juint) op1) >> (op2 & 0x1f); } inline jint BytecodeInterpreter::VMintXor(jint op1, jint op2) { diff --git a/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp b/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp index a37aab25aa6..df92163cca4 100644 --- a/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp +++ b/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp @@ -349,7 +349,7 @@ void LIRGenerator::do_MonitorExit(MonitorExit* x) { LIR_Opr lock = new_register(T_INT); LIR_Opr obj_temp = new_register(T_INT); set_no_result(x); - monitor_exit(obj_temp, lock, syncTempOpr(), x->monitor_no()); + monitor_exit(obj_temp, lock, syncTempOpr(), LIR_OprFact::illegalOpr, x->monitor_no()); } diff --git a/hotspot/src/cpu/x86/vm/c1_Runtime1_x86.cpp b/hotspot/src/cpu/x86/vm/c1_Runtime1_x86.cpp index 4bfcdb84f33..230c4b28ea3 100644 --- a/hotspot/src/cpu/x86/vm/c1_Runtime1_x86.cpp +++ b/hotspot/src/cpu/x86/vm/c1_Runtime1_x86.cpp @@ -1779,3 +1779,7 @@ OopMapSet* Runtime1::generate_code_for(StubID id, StubAssembler* sasm) { } #undef __ + +const char *Runtime1::pd_name_for_address(address entry) { + return ""; +} diff --git a/hotspot/src/cpu/x86/vm/frame_x86.cpp b/hotspot/src/cpu/x86/vm/frame_x86.cpp index 95a69f3d724..cfc20539783 100644 --- a/hotspot/src/cpu/x86/vm/frame_x86.cpp +++ b/hotspot/src/cpu/x86/vm/frame_x86.cpp @@ -575,8 +575,8 @@ bool frame::is_interpreted_frame_valid(JavaThread* thread) const { BasicType frame::interpreter_frame_result(oop* oop_result, jvalue* value_result) { #ifdef CC_INTERP - // Needed for JVMTI. The result should always be in the interpreterState object - assert(false, "NYI"); + // Needed for JVMTI. The result should always be in the + // interpreterState object interpreterState istate = get_interpreterState(); #endif // CC_INTERP assert(is_interpreted_frame(), "interpreted frame expected"); diff --git a/hotspot/src/cpu/x86/vm/interpreterRT_x86_32.cpp b/hotspot/src/cpu/x86/vm/interpreterRT_x86_32.cpp index bfa03b1cef2..ab70515a69f 100644 --- a/hotspot/src/cpu/x86/vm/interpreterRT_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/interpreterRT_x86_32.cpp @@ -34,6 +34,10 @@ void InterpreterRuntime::SignatureHandlerGenerator::pass_int() { move(offset(), jni_offset() + 1); } +void InterpreterRuntime::SignatureHandlerGenerator::pass_float() { + move(offset(), jni_offset() + 1); +} + void InterpreterRuntime::SignatureHandlerGenerator::pass_long() { move(offset(), jni_offset() + 2); move(offset() + 1, jni_offset() + 1); @@ -91,6 +95,11 @@ class SlowSignatureHandler: public NativeSignatureIterator { _from -= Interpreter::stackElementSize; } + virtual void pass_float() { + *_to++ = *(jint *)(_from+Interpreter::local_offset_in_bytes(0)); + _from -= Interpreter::stackElementSize; + } + virtual void pass_long() { _to[0] = *(intptr_t*)(_from+Interpreter::local_offset_in_bytes(1)); _to[1] = *(intptr_t*)(_from+Interpreter::local_offset_in_bytes(0)); diff --git a/hotspot/src/cpu/x86/vm/javaFrameAnchor_x86.hpp b/hotspot/src/cpu/x86/vm/javaFrameAnchor_x86.hpp index 9f4a9aae56d..d78bead14cb 100644 --- a/hotspot/src/cpu/x86/vm/javaFrameAnchor_x86.hpp +++ b/hotspot/src/cpu/x86/vm/javaFrameAnchor_x86.hpp @@ -66,6 +66,8 @@ public: intptr_t* last_Java_sp(void) const { return _last_Java_sp; } + address last_Java_pc(void) { return _last_Java_pc; } + private: static ByteSize last_Java_fp_offset() { return byte_offset_of(JavaFrameAnchor, _last_Java_fp); } diff --git a/hotspot/src/cpu/x86/vm/templateTable_x86_32.cpp b/hotspot/src/cpu/x86/vm/templateTable_x86_32.cpp index d21646c1628..b41c646c755 100644 --- a/hotspot/src/cpu/x86/vm/templateTable_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/templateTable_x86_32.cpp @@ -3112,22 +3112,25 @@ void TemplateTable::_new() { transition(vtos, atos); __ get_unsigned_2_byte_index_at_bcp(rdx, 1); Label slow_case; + Label slow_case_no_pop; Label done; Label initialize_header; Label initialize_object; // including clearing the fields Label allocate_shared; __ get_cpool_and_tags(rcx, rax); + + // Make sure the class we're about to instantiate has been resolved. + // This is done before loading instanceKlass to be consistent with the order + // how Constant Pool is updated (see constantPoolOopDesc::klass_at_put) + const int tags_offset = typeArrayOopDesc::header_size(T_BYTE) * wordSize; + __ cmpb(Address(rax, rdx, Address::times_1, tags_offset), JVM_CONSTANT_Class); + __ jcc(Assembler::notEqual, slow_case_no_pop); + // get instanceKlass __ movptr(rcx, Address(rcx, rdx, Address::times_ptr, sizeof(constantPoolOopDesc))); __ push(rcx); // save the contexts of klass for initializing the header - // make sure the class we're about to instantiate has been resolved. - // Note: slow_case does a pop of stack, which is why we loaded class/pushed above - const int tags_offset = typeArrayOopDesc::header_size(T_BYTE) * wordSize; - __ cmpb(Address(rax, rdx, Address::times_1, tags_offset), JVM_CONSTANT_Class); - __ jcc(Assembler::notEqual, slow_case); - // make sure klass is initialized & doesn't have finalizer // make sure klass is fully initialized __ cmpl(Address(rcx, instanceKlass::init_state_offset_in_bytes() + sizeof(oopDesc)), instanceKlass::fully_initialized); @@ -3255,6 +3258,7 @@ void TemplateTable::_new() { // slow case __ bind(slow_case); __ pop(rcx); // restore stack pointer to what it was when we came in. + __ bind(slow_case_no_pop); __ get_constant_pool(rax); __ get_unsigned_2_byte_index_at_bcp(rdx, 1); call_VM(rax, CAST_FROM_FN_PTR(address, InterpreterRuntime::_new), rax, rdx); diff --git a/hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp b/hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp index 8c623d33e3b..832e96bd458 100644 --- a/hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/templateTable_x86_64.cpp @@ -3126,18 +3126,18 @@ void TemplateTable::_new() { Label allocate_shared; __ get_cpool_and_tags(rsi, rax); - // get instanceKlass - __ movptr(rsi, Address(rsi, rdx, - Address::times_8, sizeof(constantPoolOopDesc))); - - // make sure the class we're about to instantiate has been - // resolved. Note: slow_case does a pop of stack, which is why we - // loaded class/pushed above + // Make sure the class we're about to instantiate has been resolved. + // This is done before loading instanceKlass to be consistent with the order + // how Constant Pool is updated (see constantPoolOopDesc::klass_at_put) const int tags_offset = typeArrayOopDesc::header_size(T_BYTE) * wordSize; __ cmpb(Address(rax, rdx, Address::times_1, tags_offset), JVM_CONSTANT_Class); __ jcc(Assembler::notEqual, slow_case); + // get instanceKlass + __ movptr(rsi, Address(rsi, rdx, + Address::times_8, sizeof(constantPoolOopDesc))); + // make sure klass is initialized & doesn't have finalizer // make sure klass is fully initialized __ cmpl(Address(rsi, diff --git a/hotspot/src/cpu/zero/vm/disassembler_zero.hpp b/hotspot/src/cpu/zero/vm/disassembler_zero.hpp index 76eea60aa65..c488cf8e765 100644 --- a/hotspot/src/cpu/zero/vm/disassembler_zero.hpp +++ b/hotspot/src/cpu/zero/vm/disassembler_zero.hpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. - * Copyright 2007 Red Hat, Inc. + * Copyright 2007, 2010 Red Hat, Inc. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,13 +23,10 @@ * */ -// The disassembler prints out zero code annotated -// with Java specific information. - static int pd_instruction_alignment() { - ShouldNotCallThis(); + return 1; } static const char* pd_cpu_opts() { - ShouldNotCallThis(); + return ""; } diff --git a/hotspot/src/cpu/zero/vm/shark_globals_zero.hpp b/hotspot/src/cpu/zero/vm/shark_globals_zero.hpp new file mode 100644 index 00000000000..30151973840 --- /dev/null +++ b/hotspot/src/cpu/zero/vm/shark_globals_zero.hpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * 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. + * + */ + +// Set the default values for platform dependent flags used by the +// Shark compiler. See globals.hpp for details of what they do. + +define_pd_global(bool, BackgroundCompilation, true ); +define_pd_global(bool, UseTLAB, true ); +define_pd_global(bool, ResizeTLAB, true ); +define_pd_global(bool, InlineIntrinsics, false); +define_pd_global(bool, PreferInterpreterNativeStubs, false); +define_pd_global(bool, ProfileTraps, false); +define_pd_global(bool, UseOnStackReplacement, true ); +define_pd_global(bool, TieredCompilation, false); + +define_pd_global(intx, CompileThreshold, 1500); +define_pd_global(intx, Tier2CompileThreshold, 1500); +define_pd_global(intx, Tier3CompileThreshold, 2500); +define_pd_global(intx, Tier4CompileThreshold, 4500); + +define_pd_global(intx, BackEdgeThreshold, 100000); +define_pd_global(intx, Tier2BackEdgeThreshold, 100000); +define_pd_global(intx, Tier3BackEdgeThreshold, 100000); +define_pd_global(intx, Tier4BackEdgeThreshold, 100000); + +define_pd_global(intx, OnStackReplacePercentage, 933 ); +define_pd_global(intx, FreqInlineSize, 325 ); +define_pd_global(intx, InlineSmallCode, 1000 ); +define_pd_global(intx, NewRatio, 12 ); +define_pd_global(intx, NewSizeThreadIncrease, 4*K ); +define_pd_global(intx, InitialCodeCacheSize, 160*K); +define_pd_global(intx, ReservedCodeCacheSize, 32*M ); +define_pd_global(bool, ProfileInterpreter, false); +define_pd_global(intx, CodeCacheExpansionSize, 32*K ); +define_pd_global(uintx, CodeCacheMinBlockLength, 1 ); +define_pd_global(uintx, PermSize, 12*M ); +define_pd_global(uintx, MaxPermSize, 64*M ); +define_pd_global(bool, NeverActAsServerClassMachine, true ); +define_pd_global(uint64_t, MaxRAM, 1ULL*G); +define_pd_global(bool, CICompileOSR, true ); diff --git a/hotspot/src/os/linux/launcher/java_md.c b/hotspot/src/os/linux/launcher/java_md.c index baa328523eb..3308ff62df3 100644 --- a/hotspot/src/os/linux/launcher/java_md.c +++ b/hotspot/src/os/linux/launcher/java_md.c @@ -79,6 +79,10 @@ # define ARCH "i386" # elif defined(__sparc) # define ARCH "sparc" +# elif defined(arm) +# define ARCH "arm" +# elif defined(PPC) +# define ARCH "ppc" # endif #endif /* _LP64 */ diff --git a/hotspot/src/os/linux/vm/attachListener_linux.cpp b/hotspot/src/os/linux/vm/attachListener_linux.cpp index 222ffa5acb2..837410ab3bd 100644 --- a/hotspot/src/os/linux/vm/attachListener_linux.cpp +++ b/hotspot/src/os/linux/vm/attachListener_linux.cpp @@ -32,11 +32,15 @@ #include #include +#ifndef UNIX_PATH_MAX +#define UNIX_PATH_MAX sizeof(((struct sockaddr_un *)0)->sun_path) +#endif + // The attach mechanism on Linux uses a UNIX domain socket. An attach listener // thread is created at startup or is created on-demand via a signal from // the client tool. The attach listener creates a socket and binds it to a file // in the filesystem. The attach listener then acts as a simple (single- -// threaded) server - tt waits for a client to connect, reads the request, +// threaded) server - it waits for a client to connect, reads the request, // executes it, and returns the response to the client via the socket // connection. // @@ -54,7 +58,7 @@ class LinuxAttachOperation; class LinuxAttachListener: AllStatic { private: // the path to which we bind the UNIX domain socket - static char _path[PATH_MAX+1]; + static char _path[UNIX_PATH_MAX]; static bool _has_path; // the file descriptor for the listening socket @@ -64,8 +68,8 @@ class LinuxAttachListener: AllStatic { if (path == NULL) { _has_path = false; } else { - strncpy(_path, path, PATH_MAX); - _path[PATH_MAX] = '\0'; + strncpy(_path, path, UNIX_PATH_MAX); + _path[UNIX_PATH_MAX-1] = '\0'; _has_path = true; } } @@ -113,7 +117,7 @@ class LinuxAttachOperation: public AttachOperation { }; // statics -char LinuxAttachListener::_path[PATH_MAX+1]; +char LinuxAttachListener::_path[UNIX_PATH_MAX]; bool LinuxAttachListener::_has_path; int LinuxAttachListener::_listener = -1; @@ -163,54 +167,53 @@ extern "C" { // Initialization - create a listener socket and bind it to a file int LinuxAttachListener::init() { - char path[PATH_MAX+1]; // socket file - int listener; // listener socket (file descriptor) + char path[UNIX_PATH_MAX]; // socket file + char initial_path[UNIX_PATH_MAX]; // socket file during setup + int listener; // listener socket (file descriptor) // register function to cleanup ::atexit(listener_cleanup); + int n = snprintf(path, UNIX_PATH_MAX, "%s/.java_pid%d", + os::get_temp_directory(), os::current_process_id()); + if (n <= (int)UNIX_PATH_MAX) { + n = snprintf(initial_path, UNIX_PATH_MAX, "%s.tmp", path); + } + if (n > (int)UNIX_PATH_MAX) { + return -1; + } + // create the listener socket listener = ::socket(PF_UNIX, SOCK_STREAM, 0); if (listener == -1) { return -1; } - int res = -1; + // bind socket struct sockaddr_un addr; addr.sun_family = AF_UNIX; - - // FIXME: Prior to b39 the tool-side API expected to find the well - // known file in the working directory. To allow this libjvm.so work with - // a pre-b39 SDK we create it in the working directory if - // +StartAttachListener is used is used. All unit tests for this feature - // currently used this flag. Once b39 SDK has been promoted we can remove - // this code. - if (StartAttachListener) { - sprintf(path, ".java_pid%d", os::current_process_id()); - strcpy(addr.sun_path, path); - ::unlink(path); - res = ::bind(listener, (struct sockaddr*)&addr, sizeof(addr)); - } + strcpy(addr.sun_path, initial_path); + ::unlink(initial_path); + int res = ::bind(listener, (struct sockaddr*)&addr, sizeof(addr)); if (res == -1) { - snprintf(path, PATH_MAX+1, "%s/.java_pid%d", - os::get_temp_directory(), os::current_process_id()); - strcpy(addr.sun_path, path); - ::unlink(path); - res = ::bind(listener, (struct sockaddr*)&addr, sizeof(addr)); + RESTARTABLE(::close(listener), res); + return -1; + } + + // put in listen mode, set permissions, and rename into place + res = ::listen(listener, 5); + if (res == 0) { + RESTARTABLE(::chmod(initial_path, S_IREAD|S_IWRITE), res); + if (res == 0) { + res = ::rename(initial_path, path); + } } if (res == -1) { RESTARTABLE(::close(listener), res); + ::unlink(initial_path); return -1; } set_path(path); - - // put in listen mode and set permission - if ((::listen(listener, 5) == -1) || (::chmod(path, S_IREAD|S_IWRITE) == -1)) { - RESTARTABLE(::close(listener), res); - ::unlink(path); - set_path(NULL); - return -1; - } set_listener(listener); return 0; diff --git a/hotspot/src/os/linux/vm/globals_linux.hpp b/hotspot/src/os/linux/vm/globals_linux.hpp index 14b22bf7ce8..75b31373703 100644 --- a/hotspot/src/os/linux/vm/globals_linux.hpp +++ b/hotspot/src/os/linux/vm/globals_linux.hpp @@ -29,9 +29,10 @@ product(bool, UseOprofile, false, \ "enable support for Oprofile profiler") \ \ - product(bool, UseLinuxPosixThreadCPUClocks, false, \ - "enable fast Linux Posix clocks where available") \ - + product(bool, UseLinuxPosixThreadCPUClocks, true, \ + "enable fast Linux Posix clocks where available") +// NB: The default value of UseLinuxPosixThreadCPUClocks may be +// overridden in Arguments::parse_each_vm_init_arg. // // Defines Linux-specific default values. The flags are available on all diff --git a/hotspot/src/os/linux/vm/os_linux.cpp b/hotspot/src/os/linux/vm/os_linux.cpp index 9648b72500a..8635a3d411f 100644 --- a/hotspot/src/os/linux/vm/os_linux.cpp +++ b/hotspot/src/os/linux/vm/os_linux.cpp @@ -30,6 +30,8 @@ // put OS-includes here # include # include +# include +# include # include # include # include @@ -188,6 +190,10 @@ static char cpu_arch[] = "ia64"; static char cpu_arch[] = "i386"; #elif defined(AMD64) static char cpu_arch[] = "amd64"; +#elif defined(ARM) +static char cpu_arch[] = "arm"; +#elif defined(PPC) +static char cpu_arch[] = "ppc"; #elif defined(SPARC) # ifdef _LP64 static char cpu_arch[] = "sparcv9"; @@ -1137,8 +1143,8 @@ void os::Linux::capture_initial_stack(size_t max_size) { long it_real; uintptr_t start; uintptr_t vsize; - uintptr_t rss; - unsigned long rsslim; + intptr_t rss; + uintptr_t rsslim; uintptr_t scodes; uintptr_t ecode; int i; @@ -1168,12 +1174,12 @@ void os::Linux::capture_initial_stack(size_t max_size) { // Skip blank chars do s++; while (isspace(*s)); - /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 */ - /* 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 */ - i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " - UINTX_FORMAT UINTX_FORMAT UINTX_FORMAT - " %lu " - UINTX_FORMAT UINTX_FORMAT UINTX_FORMAT, +#define _UFM UINTX_FORMAT +#define _DFM INTX_FORMAT + + /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 */ + /* 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 */ + i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " _UFM _UFM _DFM _UFM _UFM _UFM _UFM, &state, /* 3 %c */ &ppid, /* 4 %d */ &pgrp, /* 5 %d */ @@ -1193,15 +1199,18 @@ void os::Linux::capture_initial_stack(size_t max_size) { &nice, /* 19 %ld */ &junk, /* 20 %ld */ &it_real, /* 21 %ld */ - &start, /* 22 UINTX_FORMAT */ - &vsize, /* 23 UINTX_FORMAT */ - &rss, /* 24 UINTX_FORMAT */ - &rsslim, /* 25 %lu */ - &scodes, /* 26 UINTX_FORMAT */ - &ecode, /* 27 UINTX_FORMAT */ - &stack_start); /* 28 UINTX_FORMAT */ + &start, /* 22 UINTX_FORMAT */ + &vsize, /* 23 UINTX_FORMAT */ + &rss, /* 24 INTX_FORMAT */ + &rsslim, /* 25 UINTX_FORMAT */ + &scodes, /* 26 UINTX_FORMAT */ + &ecode, /* 27 UINTX_FORMAT */ + &stack_start); /* 28 UINTX_FORMAT */ } +#undef _UFM +#undef _DFM + if (i != 28 - 2) { assert(false, "Bad conversion from /proc/self/stat"); // product mode - assume we are the initial thread, good luck in the @@ -1336,13 +1345,15 @@ void os::Linux::clock_init() { #if defined(IA32) || defined(AMD64) #define SYS_clock_getres IA32_ONLY(266) AMD64_ONLY(229) -#else -#error Value of SYS_clock_getres not known on this platform -#endif - -#endif - #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y) +#else +#warning "SYS_clock_getres not defined for this platform, disabling fast_thread_cpu_time" +#define sys_clock_getres(x,y) -1 +#endif + +#else +#define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y) +#endif void os::Linux::fast_thread_clock_init() { if (!UseLinuxPosixThreadCPUClocks) { @@ -1905,7 +1916,9 @@ void os::print_os_info(outputStream* st) { !_print_ascii_file("/etc/SuSE-release", st) && !_print_ascii_file("/etc/turbolinux-release", st) && !_print_ascii_file("/etc/gentoo-release", st) && - !_print_ascii_file("/etc/debian_version", st)) { + !_print_ascii_file("/etc/debian_version", st) && + !_print_ascii_file("/etc/ltib-release", st) && + !_print_ascii_file("/etc/angstrom-version", st)) { st->print("Linux"); } st->cr(); @@ -1971,6 +1984,11 @@ void os::print_os_info(outputStream* st) { os::loadavg(loadavg, 3); st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]); st->cr(); + + // meminfo + st->print("\n/proc/meminfo:\n"); + _print_ascii_file("/proc/meminfo", st); + st->cr(); } void os::print_memory_info(outputStream* st) { @@ -2097,7 +2115,8 @@ void os::jvm_path(char *buf, jint buflen) { CAST_FROM_FN_PTR(address, os::jvm_path), dli_fname, sizeof(dli_fname), NULL); assert(ret != 0, "cannot locate libjvm"); - if (realpath(dli_fname, buf) == NULL) + char *rp = realpath(dli_fname, buf); + if (rp == NULL) return; if (strcmp(Arguments::sun_java_launcher(), "gamma") == 0) { @@ -2125,7 +2144,8 @@ void os::jvm_path(char *buf, jint buflen) { assert(strstr(p, "/libjvm") == p, "invalid library name"); p = strstr(p, "_g") ? "_g" : ""; - if (realpath(java_home_var, buf) == NULL) + rp = realpath(java_home_var, buf); + if (rp == NULL) return; // determine if this is a legacy image or modules image @@ -2147,7 +2167,8 @@ void os::jvm_path(char *buf, jint buflen) { snprintf(buf + len, buflen-len, "/hotspot/libjvm%s.so", p); } else { // Go back to path of .so - if (realpath(dli_fname, buf) == NULL) + rp = realpath(dli_fname, buf); + if (rp == NULL) return; } } @@ -2508,9 +2529,9 @@ os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory; unsigned long* os::Linux::_numa_all_nodes; bool os::uncommit_memory(char* addr, size_t size) { - return ::mmap(addr, size, PROT_NONE, - MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0) - != MAP_FAILED; + uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE, + MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0); + return res != (uintptr_t) MAP_FAILED; } // Linux uses a growable mapping for the stack, and if the mapping for @@ -2718,7 +2739,8 @@ bool os::large_page_init() { // the processor. #ifndef ZERO - _large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M); + _large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M) + ARM_ONLY(2 * M) PPC_ONLY(4 * M); #endif // ZERO FILE *fp = fopen("/proc/meminfo", "r"); @@ -3981,6 +4003,9 @@ jint os::init_2(void) return JNI_OK; } +// this is called at the end of vm_initialization +void os::init_3(void) { } + // Mark the polling page as unreadable void os::make_polling_page_unreadable(void) { if( !guard_memory((char*)_polling_page, Linux::page_size()) ) @@ -4061,7 +4086,6 @@ int os::Linux::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mute //////////////////////////////////////////////////////////////////////////////// // debug support -#ifndef PRODUCT static address same_page(address x, address y) { int page_bits = -os::vm_page_size(); if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits)) @@ -4072,26 +4096,26 @@ static address same_page(address x, address y) { return (address)(intptr_t(y) & page_bits); } -bool os::find(address addr) { +bool os::find(address addr, outputStream* st) { Dl_info dlinfo; memset(&dlinfo, 0, sizeof(dlinfo)); if (dladdr(addr, &dlinfo)) { - tty->print(PTR_FORMAT ": ", addr); + st->print(PTR_FORMAT ": ", addr); if (dlinfo.dli_sname != NULL) { - tty->print("%s+%#x", dlinfo.dli_sname, + st->print("%s+%#x", dlinfo.dli_sname, addr - (intptr_t)dlinfo.dli_saddr); } else if (dlinfo.dli_fname) { - tty->print("", addr - (intptr_t)dlinfo.dli_fbase); + st->print("", addr - (intptr_t)dlinfo.dli_fbase); } else { - tty->print(""); + st->print(""); } if (dlinfo.dli_fname) { - tty->print(" in %s", dlinfo.dli_fname); + st->print(" in %s", dlinfo.dli_fname); } if (dlinfo.dli_fbase) { - tty->print(" at " PTR_FORMAT, dlinfo.dli_fbase); + st->print(" at " PTR_FORMAT, dlinfo.dli_fbase); } - tty->cr(); + st->cr(); if (Verbose) { // decode some bytes around the PC @@ -4104,15 +4128,13 @@ bool os::find(address addr) { if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) end = (address) dlinfo2.dli_saddr; - Disassembler::decode(begin, end); + Disassembler::decode(begin, end, st); } return true; } return false; } -#endif - //////////////////////////////////////////////////////////////////////////////// // misc @@ -4321,6 +4343,7 @@ static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { int count; long sys_time, user_time; char string[64]; + char cdummy; int idummy; long ldummy; FILE *fp; @@ -4381,11 +4404,11 @@ static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { // Skip blank chars do s++; while (isspace(*s)); - count = sscanf(s,"%*c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu", - &idummy, &idummy, &idummy, &idummy, &idummy, + count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu", + &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy, &ldummy, &ldummy, &ldummy, &ldummy, &ldummy, &user_time, &sys_time); - if ( count != 12 ) return -1; + if ( count != 13 ) return -1; if (user_sys_cpu_time) { return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec); } else { @@ -4980,3 +5003,43 @@ int os::fork_and_exec(char* cmd) { } } } + +// is_headless_jre() +// +// Test for the existence of libmawt in motif21 or xawt directories +// in order to report if we are running in a headless jre +// +bool os::is_headless_jre() { + struct stat statbuf; + char buf[MAXPATHLEN]; + char libmawtpath[MAXPATHLEN]; + const char *xawtstr = "/xawt/libmawt.so"; + const char *motifstr = "/motif21/libmawt.so"; + char *p; + + // Get path to libjvm.so + os::jvm_path(buf, sizeof(buf)); + + // Get rid of libjvm.so + p = strrchr(buf, '/'); + if (p == NULL) return false; + else *p = '\0'; + + // Get rid of client or server + p = strrchr(buf, '/'); + if (p == NULL) return false; + else *p = '\0'; + + // check xawt/libmawt.so + strcpy(libmawtpath, buf); + strcat(libmawtpath, xawtstr); + if (::stat(libmawtpath, &statbuf) == 0) return false; + + // check motif21/libmawt.so + strcpy(libmawtpath, buf); + strcat(libmawtpath, motifstr); + if (::stat(libmawtpath, &statbuf) == 0) return false; + + return true; +} + diff --git a/hotspot/src/os/solaris/vm/attachListener_solaris.cpp b/hotspot/src/os/solaris/vm/attachListener_solaris.cpp index a88f8861fbd..9ae81cb53d5 100644 --- a/hotspot/src/os/solaris/vm/attachListener_solaris.cpp +++ b/hotspot/src/os/solaris/vm/attachListener_solaris.cpp @@ -364,6 +364,7 @@ extern "C" { // Create the door int SolarisAttachListener::create_door() { char door_path[PATH_MAX+1]; + char initial_path[PATH_MAX+1]; int fd, res; // register exit function @@ -375,36 +376,46 @@ int SolarisAttachListener::create_door() { return -1; } + // create initial file to attach door descriptor snprintf(door_path, sizeof(door_path), "%s/.java_pid%d", os::get_temp_directory(), os::current_process_id()); - RESTARTABLE(::creat(door_path, S_IRUSR | S_IWUSR), fd); - + snprintf(initial_path, sizeof(initial_path), "%s.tmp", door_path); + RESTARTABLE(::creat(initial_path, S_IRUSR | S_IWUSR), fd); if (fd == -1) { - debug_only(warning("attempt to create %s failed", door_path)); + debug_only(warning("attempt to create %s failed", initial_path)); + ::door_revoke(dd); return -1; } assert(fd >= 0, "bad file descriptor"); - set_door_path(door_path); RESTARTABLE(::close(fd), res); // attach the door descriptor to the file - if ((res = ::fattach(dd, door_path)) == -1) { + if ((res = ::fattach(dd, initial_path)) == -1) { // if busy then detach and try again if (errno == EBUSY) { - ::fdetach(door_path); - res = ::fattach(dd, door_path); + ::fdetach(initial_path); + res = ::fattach(dd, initial_path); } if (res == -1) { ::door_revoke(dd); dd = -1; } } + + // rename file so that clients can attach + if (dd >= 0) { + if (::rename(initial_path, door_path) == -1) { + RESTARTABLE(::close(dd), res); + ::fdetach(initial_path); + dd = -1; + } + } if (dd >= 0) { set_door_descriptor(dd); + set_door_path(door_path); } else { - // unable to create door or attach it to the file - ::unlink(door_path); - set_door_path(NULL); + // unable to create door, attach it to file, or rename file into place + ::unlink(initial_path); return -1; } diff --git a/hotspot/src/os/solaris/vm/os_solaris.cpp b/hotspot/src/os/solaris/vm/os_solaris.cpp index 9a51d167a38..0245d6f609d 100644 --- a/hotspot/src/os/solaris/vm/os_solaris.cpp +++ b/hotspot/src/os/solaris/vm/os_solaris.cpp @@ -1839,8 +1839,8 @@ void os::dll_build_name(char* buffer, size_t buflen, // Quietly truncate on buffer overflow. Should be an error. if (pnamelen + strlen(fname) + 10 > (size_t) buflen) { - *buffer = '\0'; - return; + *buffer = '\0'; + return; } if (pnamelen == 0) { @@ -2051,7 +2051,8 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"}, {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"}, - {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"} + {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"}, + {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM 32"} }; #if (defined IA32) @@ -2068,9 +2069,11 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) static Elf32_Half running_arch_code=EM_PPC64; #elif (defined __powerpc__) static Elf32_Half running_arch_code=EM_PPC; + #elif (defined ARM) + static Elf32_Half running_arch_code=EM_ARM; #else #error Method os::dll_load requires that one of following is defined:\ - IA32, AMD64, IA64, __sparc, __powerpc__ + IA32, AMD64, IA64, __sparc, __powerpc__, ARM, ARM #endif // Identify compatability class for VM's architecture and library's architecture @@ -3149,7 +3152,8 @@ bool os::Solaris::ism_sanity_check(bool warn, size_t * page_size) { // ISM is only recommended on old Solaris where there is no MPSS support. // Simply choose a conservative value as default. *page_size = LargePageSizeInBytes ? LargePageSizeInBytes : - SPARC_ONLY(4 * M) IA32_ONLY(4 * M) AMD64_ONLY(2 * M); + SPARC_ONLY(4 * M) IA32_ONLY(4 * M) AMD64_ONLY(2 * M) + ARM_ONLY(2 * M); // ISM is available on all supported Solaris versions return true; @@ -5007,6 +5011,9 @@ jint os::init_2(void) { return JNI_OK; } +void os::init_3(void) { + return; +} // Mark the polling page as unreadable void os::make_polling_page_unreadable(void) { @@ -5412,7 +5419,6 @@ int os::loadavg(double loadavg[], int nelem) { } //--------------------------------------------------------------------------------- -#ifndef PRODUCT static address same_page(address x, address y) { intptr_t page_bits = -os::vm_page_size(); @@ -5424,28 +5430,28 @@ static address same_page(address x, address y) { return (address)(intptr_t(y) & page_bits); } -bool os::find(address addr) { +bool os::find(address addr, outputStream* st) { Dl_info dlinfo; memset(&dlinfo, 0, sizeof(dlinfo)); if (dladdr(addr, &dlinfo)) { #ifdef _LP64 - tty->print("0x%016lx: ", addr); + st->print("0x%016lx: ", addr); #else - tty->print("0x%08x: ", addr); + st->print("0x%08x: ", addr); #endif if (dlinfo.dli_sname != NULL) - tty->print("%s+%#lx", dlinfo.dli_sname, addr-(intptr_t)dlinfo.dli_saddr); + st->print("%s+%#lx", dlinfo.dli_sname, addr-(intptr_t)dlinfo.dli_saddr); else if (dlinfo.dli_fname) - tty->print("", addr-(intptr_t)dlinfo.dli_fbase); + st->print("", addr-(intptr_t)dlinfo.dli_fbase); else - tty->print(""); - if (dlinfo.dli_fname) tty->print(" in %s", dlinfo.dli_fname); + st->print(""); + if (dlinfo.dli_fname) st->print(" in %s", dlinfo.dli_fname); #ifdef _LP64 - if (dlinfo.dli_fbase) tty->print(" at 0x%016lx", dlinfo.dli_fbase); + if (dlinfo.dli_fbase) st->print(" at 0x%016lx", dlinfo.dli_fbase); #else - if (dlinfo.dli_fbase) tty->print(" at 0x%08x", dlinfo.dli_fbase); + if (dlinfo.dli_fbase) st->print(" at 0x%08x", dlinfo.dli_fbase); #endif - tty->cr(); + st->cr(); if (Verbose) { // decode some bytes around the PC @@ -5458,16 +5464,13 @@ bool os::find(address addr) { if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) end = (address) dlinfo2.dli_saddr; - Disassembler::decode(begin, end); + Disassembler::decode(begin, end, st); } return true; } return false; } -#endif - - // Following function has been added to support HotSparc's libjvm.so running // under Solaris production JDK 1.2.2 / 1.3.0. These came from // src/solaris/hpi/native_threads in the EVM codebase. @@ -5910,7 +5913,6 @@ void Parker::park(bool isAbsolute, jlong time) { if (jt->handle_special_suspend_equivalent_condition()) { jt->java_suspend_self(); } - OrderAccess::fence(); } @@ -5997,3 +5999,44 @@ int os::fork_and_exec(char* cmd) { } } } + +// is_headless_jre() +// +// Test for the existence of libmawt in motif21 or xawt directories +// in order to report if we are running in a headless jre +// +bool os::is_headless_jre() { + struct stat statbuf; + char buf[MAXPATHLEN]; + char libmawtpath[MAXPATHLEN]; + const char *xawtstr = "/xawt/libmawt.so"; + const char *motifstr = "/motif21/libmawt.so"; + char *p; + + // Get path to libjvm.so + os::jvm_path(buf, sizeof(buf)); + + // Get rid of libjvm.so + p = strrchr(buf, '/'); + if (p == NULL) return false; + else *p = '\0'; + + // Get rid of client or server + p = strrchr(buf, '/'); + if (p == NULL) return false; + else *p = '\0'; + + // check xawt/libmawt.so + strcpy(libmawtpath, buf); + strcat(libmawtpath, xawtstr); + if (::stat(libmawtpath, &statbuf) == 0) return false; + + // check motif21/libmawt.so + strcpy(libmawtpath, buf); + strcat(libmawtpath, motifstr); + if (::stat(libmawtpath, &statbuf) == 0) return false; + + return true; +} + + diff --git a/hotspot/src/os/windows/vm/os_windows.cpp b/hotspot/src/os/windows/vm/os_windows.cpp index 2e5cee6c5f4..f2b7eedcb5e 100644 --- a/hotspot/src/os/windows/vm/os_windows.cpp +++ b/hotspot/src/os/windows/vm/os_windows.cpp @@ -3444,6 +3444,9 @@ jint os::init_2(void) { return JNI_OK; } +void os::init_3(void) { + return; +} // Mark the polling page as unreadable void os::make_polling_page_unreadable(void) { @@ -4105,12 +4108,10 @@ bool os::check_heap(bool force) { } -#ifndef PRODUCT -bool os::find(address addr) { +bool os::find(address addr, outputStream* st) { // Nothing yet return false; } -#endif LONG WINAPI os::win32::serialize_fault_filter(struct _EXCEPTION_POINTERS* e) { DWORD exception_code = e->ExceptionRecord->ExceptionCode; @@ -4164,3 +4165,8 @@ static int getLastErrorString(char *buf, size_t len) } return 0; } + + +// We don't build a headless jre for Windows +bool os::is_headless_jre() { return false; } + diff --git a/hotspot/src/os_cpu/linux_sparc/vm/thread_linux_sparc.cpp b/hotspot/src/os_cpu/linux_sparc/vm/thread_linux_sparc.cpp index 5d1bdac4a1d..7b44e39eee7 100644 --- a/hotspot/src/os_cpu/linux_sparc/vm/thread_linux_sparc.cpp +++ b/hotspot/src/os_cpu/linux_sparc/vm/thread_linux_sparc.cpp @@ -105,3 +105,6 @@ bool JavaThread::pd_get_top_frame_for_signal_handler(frame* fr_addr, // nothing else to try return false; } + +void JavaThread::cache_global_variables() { } + diff --git a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp index 6877c5ad00d..29b93ec6dd4 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp +++ b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp @@ -718,6 +718,11 @@ void os::print_context(outputStream *st, void *context) { ucontext_t *uc = (ucontext_t*)context; st->print_cr("Registers:"); + + // this is horrendously verbose but the layout of the registers in the + // context does not match how we defined our abstract Register set, so + // we can't just iterate through the gregs area + #ifdef AMD64 st->print( "RAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RAX]); st->print(", RBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RBX]); @@ -745,6 +750,63 @@ void os::print_context(outputStream *st, void *context) { st->print(", ERR=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_ERR]); st->cr(); st->print(" TRAPNO=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_TRAPNO]); + + st->cr(); + st->cr(); + + st->print_cr("Register to memory mapping:"); + st->cr(); + + // this is only for the "general purpose" registers + + st->print_cr("RAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RAX]); + print_location(st, uc->uc_mcontext.gregs[REG_RAX]); + st->cr(); + st->print_cr("RBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RBX]); + print_location(st, uc->uc_mcontext.gregs[REG_RBX]); + st->cr(); + st->print_cr("RCX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RCX]); + print_location(st, uc->uc_mcontext.gregs[REG_RCX]); + st->cr(); + st->print_cr("RDX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RDX]); + print_location(st, uc->uc_mcontext.gregs[REG_RDX]); + st->cr(); + st->print_cr("RSP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RSP]); + print_location(st, uc->uc_mcontext.gregs[REG_RSP]); + st->cr(); + st->print_cr("RBP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RBP]); + print_location(st, uc->uc_mcontext.gregs[REG_RBP]); + st->cr(); + st->print_cr("RSI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RSI]); + print_location(st, uc->uc_mcontext.gregs[REG_RSI]); + st->cr(); + st->print_cr("RDI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RDI]); + print_location(st, uc->uc_mcontext.gregs[REG_RDI]); + st->cr(); + st->print_cr("R8 =" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R8]); + print_location(st, uc->uc_mcontext.gregs[REG_R8]); + st->cr(); + st->print_cr("R9 =" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R9]); + print_location(st, uc->uc_mcontext.gregs[REG_R9]); + st->cr(); + st->print_cr("R10=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R10]); + print_location(st, uc->uc_mcontext.gregs[REG_R10]); + st->cr(); + st->print_cr("R11=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R11]); + print_location(st, uc->uc_mcontext.gregs[REG_R11]); + st->cr(); + st->print_cr("R12=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R12]); + print_location(st, uc->uc_mcontext.gregs[REG_R12]); + st->cr(); + st->print_cr("R13=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R13]); + print_location(st, uc->uc_mcontext.gregs[REG_R13]); + st->cr(); + st->print_cr("R14=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R14]); + print_location(st, uc->uc_mcontext.gregs[REG_R14]); + st->cr(); + st->print_cr("R15=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R15]); + print_location(st, uc->uc_mcontext.gregs[REG_R15]); + #else st->print( "EAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EAX]); st->print(", EBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EBX]); @@ -759,6 +821,39 @@ void os::print_context(outputStream *st, void *context) { st->print( "EIP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EIP]); st->print(", CR2=" INTPTR_FORMAT, uc->uc_mcontext.cr2); st->print(", EFLAGS=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EFL]); + + st->cr(); + st->cr(); + + st->print_cr("Register to memory mapping:"); + st->cr(); + + // this is only for the "general purpose" registers + + st->print_cr("EAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EAX]); + print_location(st, uc->uc_mcontext.gregs[REG_EAX]); + st->cr(); + st->print_cr("EBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EBX]); + print_location(st, uc->uc_mcontext.gregs[REG_EBX]); + st->cr(); + st->print_cr("ECX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_ECX]); + print_location(st, uc->uc_mcontext.gregs[REG_ECX]); + st->cr(); + st->print_cr("EDX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EDX]); + print_location(st, uc->uc_mcontext.gregs[REG_EDX]); + st->cr(); + st->print_cr("ESP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_ESP]); + print_location(st, uc->uc_mcontext.gregs[REG_ESP]); + st->cr(); + st->print_cr("EBP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EBP]); + print_location(st, uc->uc_mcontext.gregs[REG_EBP]); + st->cr(); + st->print_cr("ESI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_ESI]); + print_location(st, uc->uc_mcontext.gregs[REG_ESI]); + st->cr(); + st->print_cr("EDI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EDI]); + print_location(st, uc->uc_mcontext.gregs[REG_EDI]); + #endif // AMD64 st->cr(); st->cr(); diff --git a/hotspot/src/os_cpu/linux_x86/vm/thread_linux_x86.cpp b/hotspot/src/os_cpu/linux_x86/vm/thread_linux_x86.cpp index 8347bcccd9a..b3089810813 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/thread_linux_x86.cpp +++ b/hotspot/src/os_cpu/linux_x86/vm/thread_linux_x86.cpp @@ -79,3 +79,6 @@ bool JavaThread::pd_get_top_frame_for_signal_handler(frame* fr_addr, // nothing else to try return false; } + +void JavaThread::cache_global_variables() { } + diff --git a/hotspot/src/os_cpu/linux_zero/vm/thread_linux_zero.cpp b/hotspot/src/os_cpu/linux_zero/vm/thread_linux_zero.cpp index 1e7f6703a71..15dba5fff97 100644 --- a/hotspot/src/os_cpu/linux_zero/vm/thread_linux_zero.cpp +++ b/hotspot/src/os_cpu/linux_zero/vm/thread_linux_zero.cpp @@ -24,3 +24,5 @@ */ // This file is intentionally empty + +void JavaThread::cache_global_variables() { } diff --git a/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp b/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp index 8ca2aeb425c..91ae05ace11 100644 --- a/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp +++ b/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp @@ -587,6 +587,61 @@ void os::print_context(outputStream *st, void *context) { st->print_cr(" PC=" INTPTR_FORMAT " nPC=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_PC], uc->uc_mcontext.gregs[REG_nPC]); + + st->cr(); + st->cr(); + + st->print_cr("Register to memory mapping:"); + st->cr(); + + // this is only for the "general purpose" registers + + st->print_cr("O0=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_O0]); + print_location(st, uc->uc_mcontext.gregs[REG_O0]); + st->cr(); + st->print_cr("O1=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_O1]); + print_location(st, uc->uc_mcontext.gregs[REG_O1]); + st->cr(); + st->print_cr("O2=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_O2]); + print_location(st, uc->uc_mcontext.gregs[REG_O2]); + st->cr(); + st->print_cr("O3=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_O3]); + print_location(st, uc->uc_mcontext.gregs[REG_O3]); + st->cr(); + st->print_cr("O4=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_O4]); + print_location(st, uc->uc_mcontext.gregs[REG_O4]); + st->cr(); + st->print_cr("O5=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_O5]); + print_location(st, uc->uc_mcontext.gregs[REG_O5]); + st->cr(); + st->print_cr("O6=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_O6]); + print_location(st, uc->uc_mcontext.gregs[REG_O6]); + st->cr(); + st->print_cr("O7=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_O7]); + print_location(st, uc->uc_mcontext.gregs[REG_O7]); + st->cr(); + + st->print_cr("G1=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_G1]); + print_location(st, uc->uc_mcontext.gregs[REG_G1]); + st->cr(); + st->print_cr("G2=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_G2]); + print_location(st, uc->uc_mcontext.gregs[REG_G2]); + st->cr(); + st->print_cr("G3=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_G3]); + print_location(st, uc->uc_mcontext.gregs[REG_G3]); + st->cr(); + st->print_cr("G4=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_G4]); + print_location(st, uc->uc_mcontext.gregs[REG_G4]); + st->cr(); + st->print_cr("G5=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_G5]); + print_location(st, uc->uc_mcontext.gregs[REG_G5]); + st->cr(); + st->print_cr("G6=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_G6]); + print_location(st, uc->uc_mcontext.gregs[REG_G6]); + st->cr(); + st->print_cr("G7=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_G7]); + print_location(st, uc->uc_mcontext.gregs[REG_G7]); + st->cr(); st->cr(); diff --git a/hotspot/src/os_cpu/solaris_sparc/vm/thread_solaris_sparc.cpp b/hotspot/src/os_cpu/solaris_sparc/vm/thread_solaris_sparc.cpp index 6b8bc2a3656..84efd5e76d1 100644 --- a/hotspot/src/os_cpu/solaris_sparc/vm/thread_solaris_sparc.cpp +++ b/hotspot/src/os_cpu/solaris_sparc/vm/thread_solaris_sparc.cpp @@ -140,3 +140,6 @@ bool JavaThread::pd_get_top_frame_for_signal_handler(frame* fr_addr, *fr_addr = ret_frame; return true; } + +void JavaThread::cache_global_variables() { } + diff --git a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp index 96c95448ab2..a80374a0095 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp +++ b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp @@ -719,6 +719,11 @@ void os::print_context(outputStream *st, void *context) { ucontext_t *uc = (ucontext_t*)context; st->print_cr("Registers:"); + + // this is horrendously verbose but the layout of the registers in the + // context does not match how we defined our abstract Register set, so + // we can't just iterate through the gregs area + #ifdef AMD64 st->print( "RAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RAX]); st->print(", RBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RBX]); @@ -742,6 +747,63 @@ void os::print_context(outputStream *st, void *context) { st->cr(); st->print( "RIP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RIP]); st->print(", RFLAGS=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RFL]); + + st->cr(); + st->cr(); + + st->print_cr("Register to memory mapping:"); + st->cr(); + + // this is only for the "general purpose" registers + + st->print_cr("RAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RAX]); + print_location(st, uc->uc_mcontext.gregs[REG_RAX]); + st->cr(); + st->print_cr("RBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RBX]); + print_location(st, uc->uc_mcontext.gregs[REG_RBX]); + st->cr(); + st->print_cr("RCX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RCX]); + print_location(st, uc->uc_mcontext.gregs[REG_RCX]); + st->cr(); + st->print_cr("RDX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RDX]); + print_location(st, uc->uc_mcontext.gregs[REG_RDX]); + st->cr(); + st->print_cr("RSP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RSP]); + print_location(st, uc->uc_mcontext.gregs[REG_RSP]); + st->cr(); + st->print_cr("RBP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RBP]); + print_location(st, uc->uc_mcontext.gregs[REG_RSP]); + st->cr(); + st->print_cr("RSI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RSI]); + print_location(st, uc->uc_mcontext.gregs[REG_RSI]); + st->cr(); + st->print_cr("RDI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_RDI]); + print_location(st, uc->uc_mcontext.gregs[REG_RDI]); + st->cr(); + st->print_cr("R8 =" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R8]); + print_location(st, uc->uc_mcontext.gregs[REG_R8]); + st->cr(); + st->print_cr("R9 =" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R9]); + print_location(st, uc->uc_mcontext.gregs[REG_R9]); + st->cr(); + st->print_cr("R10=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R10]); + print_location(st, uc->uc_mcontext.gregs[REG_R10]); + st->cr(); + st->print_cr("R11=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R11]); + print_location(st, uc->uc_mcontext.gregs[REG_R11]); + st->cr(); + st->print_cr("R12=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R12]); + print_location(st, uc->uc_mcontext.gregs[REG_R12]); + st->cr(); + st->print_cr("R13=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R13]); + print_location(st, uc->uc_mcontext.gregs[REG_R13]); + st->cr(); + st->print_cr("R14=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R14]); + print_location(st, uc->uc_mcontext.gregs[REG_R14]); + st->cr(); + st->print_cr("R15=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_R15]); + print_location(st, uc->uc_mcontext.gregs[REG_R15]); + #else st->print( "EAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EAX]); st->print(", EBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EBX]); @@ -755,6 +817,39 @@ void os::print_context(outputStream *st, void *context) { st->cr(); st->print( "EIP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EIP]); st->print(", EFLAGS=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EFL]); + + st->cr(); + st->cr(); + + st->print_cr("Register to memory mapping:"); + st->cr(); + + // this is only for the "general purpose" registers + + st->print_cr("EAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EAX]); + print_location(st, uc->uc_mcontext.gregs[EAX]); + st->cr(); + st->print_cr("EBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EBX]); + print_location(st, uc->uc_mcontext.gregs[EBX]); + st->cr(); + st->print_cr("ECX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[ECX]); + print_location(st, uc->uc_mcontext.gregs[ECX]); + st->cr(); + st->print_cr("EDX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EDX]); + print_location(st, uc->uc_mcontext.gregs[EDX]); + st->cr(); + st->print_cr("ESP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[UESP]); + print_location(st, uc->uc_mcontext.gregs[UESP]); + st->cr(); + st->print_cr("EBP=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EBP]); + print_location(st, uc->uc_mcontext.gregs[EBP]); + st->cr(); + st->print_cr("ESI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[ESI]); + print_location(st, uc->uc_mcontext.gregs[ESI]); + st->cr(); + st->print_cr("EDI=" INTPTR_FORMAT, uc->uc_mcontext.gregs[EDI]); + print_location(st, uc->uc_mcontext.gregs[EDI]); + #endif // AMD64 st->cr(); st->cr(); @@ -773,6 +868,7 @@ void os::print_context(outputStream *st, void *context) { print_hex_dump(st, pc - 16, pc + 16, sizeof(char)); } + #ifdef AMD64 void os::Solaris::init_thread_fpu_state(void) { // Nothing to do diff --git a/hotspot/src/os_cpu/solaris_x86/vm/thread_solaris_x86.cpp b/hotspot/src/os_cpu/solaris_x86/vm/thread_solaris_x86.cpp index 115f27fa013..fa308d54630 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/thread_solaris_x86.cpp +++ b/hotspot/src/os_cpu/solaris_x86/vm/thread_solaris_x86.cpp @@ -82,3 +82,6 @@ bool JavaThread::pd_get_top_frame_for_signal_handler(frame* fr_addr, return true; } + +void JavaThread::cache_global_variables() { } + diff --git a/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp b/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp index f22821311e8..8cc55b78c3d 100644 --- a/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp +++ b/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp @@ -377,18 +377,84 @@ void os::print_context(outputStream *st, void *context) { st->print_cr("Registers:"); #ifdef AMD64 - st->print( "EAX=" INTPTR_FORMAT, uc->Rax); - st->print(", EBX=" INTPTR_FORMAT, uc->Rbx); - st->print(", ECX=" INTPTR_FORMAT, uc->Rcx); - st->print(", EDX=" INTPTR_FORMAT, uc->Rdx); + st->print( "RAX=" INTPTR_FORMAT, uc->Rax); + st->print(", RBX=" INTPTR_FORMAT, uc->Rbx); + st->print(", RCX=" INTPTR_FORMAT, uc->Rcx); + st->print(", RDX=" INTPTR_FORMAT, uc->Rdx); st->cr(); - st->print( "ESP=" INTPTR_FORMAT, uc->Rsp); - st->print(", EBP=" INTPTR_FORMAT, uc->Rbp); - st->print(", ESI=" INTPTR_FORMAT, uc->Rsi); - st->print(", EDI=" INTPTR_FORMAT, uc->Rdi); + st->print( "RSP=" INTPTR_FORMAT, uc->Rsp); + st->print(", RBP=" INTPTR_FORMAT, uc->Rbp); + st->print(", RSI=" INTPTR_FORMAT, uc->Rsi); + st->print(", RDI=" INTPTR_FORMAT, uc->Rdi); st->cr(); - st->print( "EIP=" INTPTR_FORMAT, uc->Rip); + st->print( "R8=" INTPTR_FORMAT, uc->R8); + st->print(", R9=" INTPTR_FORMAT, uc->R9); + st->print(", R10=" INTPTR_FORMAT, uc->R10); + st->print(", R11=" INTPTR_FORMAT, uc->R11); + st->cr(); + st->print( "R12=" INTPTR_FORMAT, uc->R12); + st->print(", R13=" INTPTR_FORMAT, uc->R13); + st->print(", R14=" INTPTR_FORMAT, uc->R14); + st->print(", R15=" INTPTR_FORMAT, uc->R15); + st->cr(); + st->print( "RIP=" INTPTR_FORMAT, uc->Rip); st->print(", EFLAGS=" INTPTR_FORMAT, uc->EFlags); + + st->cr(); + st->cr(); + + st->print_cr("Register to memory mapping:"); + st->cr(); + + // this is only for the "general purpose" registers + + st->print_cr("RAX=" INTPTR_FORMAT, uc->Rax); + print_location(st, uc->Rax); + st->cr(); + st->print_cr("RBX=" INTPTR_FORMAT, uc->Rbx); + print_location(st, uc->Rbx); + st->cr(); + st->print_cr("RCX=" INTPTR_FORMAT, uc->Rcx); + print_location(st, uc->Rcx); + st->cr(); + st->print_cr("RDX=" INTPTR_FORMAT, uc->Rdx); + print_location(st, uc->Rdx); + st->cr(); + st->print_cr("RSP=" INTPTR_FORMAT, uc->Rsp); + print_location(st, uc->Rsp); + st->cr(); + st->print_cr("RBP=" INTPTR_FORMAT, uc->Rbp); + print_location(st, uc->Rbp); + st->cr(); + st->print_cr("RSI=" INTPTR_FORMAT, uc->Rsi); + print_location(st, uc->Rsi); + st->cr(); + st->print_cr("RDI=" INTPTR_FORMAT, uc->Rdi); + print_location(st, uc->Rdi); + st->cr(); + st->print_cr("R8 =" INTPTR_FORMAT, uc->R8); + print_location(st, uc->R8); + st->cr(); + st->print_cr("R9 =" INTPTR_FORMAT, uc->R9); + print_location(st, uc->R9); + st->cr(); + st->print_cr("R10=" INTPTR_FORMAT, uc->R10); + print_location(st, uc->R10); + st->cr(); + st->print_cr("R11=" INTPTR_FORMAT, uc->R11); + print_location(st, uc->R11); + st->cr(); + st->print_cr("R12=" INTPTR_FORMAT, uc->R12); + print_location(st, uc->R12); + st->cr(); + st->print_cr("R13=" INTPTR_FORMAT, uc->R13); + print_location(st, uc->R13); + st->cr(); + st->print_cr("R14=" INTPTR_FORMAT, uc->R14); + print_location(st, uc->R14); + st->cr(); + st->print_cr("R15=" INTPTR_FORMAT, uc->R15); + print_location(st, uc->R15); #else st->print( "EAX=" INTPTR_FORMAT, uc->Eax); st->print(", EBX=" INTPTR_FORMAT, uc->Ebx); @@ -402,6 +468,38 @@ void os::print_context(outputStream *st, void *context) { st->cr(); st->print( "EIP=" INTPTR_FORMAT, uc->Eip); st->print(", EFLAGS=" INTPTR_FORMAT, uc->EFlags); + + st->cr(); + st->cr(); + + st->print_cr("Register to memory mapping:"); + st->cr(); + + // this is only for the "general purpose" registers + + st->print_cr("EAX=" INTPTR_FORMAT, uc->Eax); + print_location(st, uc->Eax); + st->cr(); + st->print_cr("EBX=" INTPTR_FORMAT, uc->Ebx); + print_location(st, uc->Ebx); + st->cr(); + st->print_cr("ECX=" INTPTR_FORMAT, uc->Ecx); + print_location(st, uc->Ecx); + st->cr(); + st->print_cr("EDX=" INTPTR_FORMAT, uc->Edx); + print_location(st, uc->Edx); + st->cr(); + st->print_cr("ESP=" INTPTR_FORMAT, uc->Esp); + print_location(st, uc->Esp); + st->cr(); + st->print_cr("EBP=" INTPTR_FORMAT, uc->Ebp); + print_location(st, uc->Ebp); + st->cr(); + st->print_cr("ESI=" INTPTR_FORMAT, uc->Esi); + print_location(st, uc->Esi); + st->cr(); + st->print_cr("EDI=" INTPTR_FORMAT, uc->Edi); + print_location(st, uc->Edi); #endif // AMD64 st->cr(); st->cr(); diff --git a/hotspot/src/os_cpu/windows_x86/vm/thread_windows_x86.cpp b/hotspot/src/os_cpu/windows_x86/vm/thread_windows_x86.cpp index 43716368f56..7334845c3d9 100644 --- a/hotspot/src/os_cpu/windows_x86/vm/thread_windows_x86.cpp +++ b/hotspot/src/os_cpu/windows_x86/vm/thread_windows_x86.cpp @@ -84,3 +84,6 @@ bool JavaThread::pd_get_top_frame_for_signal_handler(frame* fr_addr, // nothing else to try return false; } + +void JavaThread::cache_global_variables() { } + diff --git a/hotspot/src/share/vm/asm/codeBuffer.cpp b/hotspot/src/share/vm/asm/codeBuffer.cpp index 4c7aab94d58..77e7cdb8727 100644 --- a/hotspot/src/share/vm/asm/codeBuffer.cpp +++ b/hotspot/src/share/vm/asm/codeBuffer.cpp @@ -128,7 +128,11 @@ CodeBuffer::~CodeBuffer() { delete _overflow_arena; #ifdef ASSERT + // Save allocation type to execute assert in ~ResourceObj() + // which is called after this destructor. + ResourceObj::allocation_type at = _default_oop_recorder.get_allocation_type(); Copy::fill_to_bytes(this, sizeof(*this), badResourceValue); + ResourceObj::set_allocation_type((address)(&_default_oop_recorder), at); #endif } diff --git a/hotspot/src/share/vm/asm/codeBuffer.hpp b/hotspot/src/share/vm/asm/codeBuffer.hpp index 2f1a8d3c8fe..8e4a4ea323c 100644 --- a/hotspot/src/share/vm/asm/codeBuffer.hpp +++ b/hotspot/src/share/vm/asm/codeBuffer.hpp @@ -102,7 +102,7 @@ class CodeSection VALUE_OBJ_CLASS_SPEC { _locs_point = NULL; _locs_own = false; _frozen = false; - debug_only(_index = -1); + debug_only(_index = (char)-1); debug_only(_outer = (CodeBuffer*)badAddress); } @@ -278,7 +278,7 @@ class CodeBuffer: public StackObj { // special case during expansion which is handled internally. This // is done to guarantee proper cleanup of resources. void* operator new(size_t size) { return ResourceObj::operator new(size); } - void operator delete(void* p) { ResourceObj::operator delete(p); } + void operator delete(void* p) { ShouldNotCallThis(); } public: typedef int csize_t; // code size type; would be size_t except for history diff --git a/hotspot/src/share/vm/c1/c1_CodeStubs.hpp b/hotspot/src/share/vm/c1/c1_CodeStubs.hpp index 547e2d70a82..07ed4302dd9 100644 --- a/hotspot/src/share/vm/c1/c1_CodeStubs.hpp +++ b/hotspot/src/share/vm/c1/c1_CodeStubs.hpp @@ -448,6 +448,10 @@ class SimpleExceptionStub: public CodeStub { _obj(obj), _info(info), _stub(stub) { } + void set_obj(LIR_Opr obj) { + _obj = obj; + } + virtual void emit_code(LIR_Assembler* e); virtual CodeEmitInfo* info() const { return _info; } virtual bool is_exception_throw_stub() const { return true; } diff --git a/hotspot/src/share/vm/c1/c1_Compilation.cpp b/hotspot/src/share/vm/c1/c1_Compilation.cpp index ac47342f45a..d9156c1b307 100644 --- a/hotspot/src/share/vm/c1/c1_Compilation.cpp +++ b/hotspot/src/share/vm/c1/c1_Compilation.cpp @@ -220,11 +220,13 @@ void Compilation::emit_code_epilog(LIR_Assembler* assembler) { code_offsets->set_value(CodeOffsets::Deopt, assembler->emit_deopt_handler()); CHECK_BAILOUT(); - // Generate code for MethodHandle deopt handler. We can use the - // same code as for the normal deopt handler, we just need a - // different entry point address. - code_offsets->set_value(CodeOffsets::DeoptMH, assembler->emit_deopt_handler()); - CHECK_BAILOUT(); + // Emit the MethodHandle deopt handler code (if required). + if (has_method_handle_invokes()) { + // We can use the same code as for the normal deopt handler, we + // just need a different entry point address. + code_offsets->set_value(CodeOffsets::DeoptMH, assembler->emit_deopt_handler()); + CHECK_BAILOUT(); + } // Emit the handler to remove the activation from the stack and // dispatch to the caller. @@ -446,6 +448,7 @@ Compilation::Compilation(AbstractCompiler* compiler, ciEnv* env, ciMethod* metho , _has_exception_handlers(false) , _has_fpu_code(true) // pessimistic assumption , _has_unsafe_access(false) +, _has_method_handle_invokes(false) , _bailout_msg(NULL) , _exception_info_list(NULL) , _allocator(NULL) diff --git a/hotspot/src/share/vm/c1/c1_Compilation.hpp b/hotspot/src/share/vm/c1/c1_Compilation.hpp index 86d6cbf7a05..82c1699ea91 100644 --- a/hotspot/src/share/vm/c1/c1_Compilation.hpp +++ b/hotspot/src/share/vm/c1/c1_Compilation.hpp @@ -69,6 +69,7 @@ class Compilation: public StackObj { bool _has_exception_handlers; bool _has_fpu_code; bool _has_unsafe_access; + bool _has_method_handle_invokes; // True if this method has MethodHandle invokes. const char* _bailout_msg; ExceptionInfoList* _exception_info_list; ExceptionHandlerTable _exception_handler_table; @@ -147,6 +148,10 @@ class Compilation: public StackObj { // Statistics gathering void notice_inlined_method(ciMethod* method); + // JSR 292 + bool has_method_handle_invokes() const { return _has_method_handle_invokes; } + void set_has_method_handle_invokes(bool z) { _has_method_handle_invokes = z; } + DebugInformationRecorder* debug_info_recorder() const; // = _env->debug_info(); Dependencies* dependency_recorder() const; // = _env->dependencies() ImplicitExceptionTable* implicit_exception_table() { return &_implicit_exception_table; } @@ -168,10 +173,19 @@ class Compilation: public StackObj { const char* bailout_msg() const { return _bailout_msg; } static int desired_max_code_buffer_size() { +#ifndef PPC return (int) NMethodSizeLimit; // default 256K or 512K +#else + // conditional branches on PPC are restricted to 16 bit signed + return MAX2((unsigned int)NMethodSizeLimit,32*K); +#endif } static int desired_max_constant_size() { +#ifndef PPC return (int) NMethodSizeLimit / 10; // about 25K +#else + return (MAX2((unsigned int)NMethodSizeLimit, 32*K)) / 10; +#endif } static void setup_code_buffer(CodeBuffer* cb, int call_stub_estimate); diff --git a/hotspot/src/share/vm/c1/c1_FrameMap.cpp b/hotspot/src/share/vm/c1/c1_FrameMap.cpp index 55fd77b9809..139572dd138 100644 --- a/hotspot/src/share/vm/c1/c1_FrameMap.cpp +++ b/hotspot/src/share/vm/c1/c1_FrameMap.cpp @@ -90,7 +90,7 @@ CallingConvention* FrameMap::java_calling_convention(const BasicTypeArray* signa if (outgoing) { // update the space reserved for arguments. - update_reserved_argument_area_size(out_preserve); + update_reserved_argument_area_size(out_preserve * BytesPerWord); } return new CallingConvention(args, out_preserve); } @@ -138,7 +138,7 @@ CallingConvention* FrameMap::c_calling_convention(const BasicTypeArray* signatur } assert(args->length() == signature->length(), "size mismatch"); out_preserve += SharedRuntime::out_preserve_stack_slots(); - update_reserved_argument_area_size(out_preserve); + update_reserved_argument_area_size(out_preserve * BytesPerWord); return new CallingConvention(args, out_preserve); } diff --git a/hotspot/src/share/vm/c1/c1_FrameMap.hpp b/hotspot/src/share/vm/c1/c1_FrameMap.hpp index 4c4c99a7492..4a229d6bf7e 100644 --- a/hotspot/src/share/vm/c1/c1_FrameMap.hpp +++ b/hotspot/src/share/vm/c1/c1_FrameMap.hpp @@ -154,7 +154,6 @@ class FrameMap : public CompilationResourceObj { static LIR_Opr method_handle_invoke_SP_save_opr(); static BasicTypeArray* signature_type_array_for(const ciMethod* method); - static BasicTypeArray* signature_type_array_for(const char * signature); // for outgoing calls, these also update the reserved area to // include space for arguments and any ABI area. diff --git a/hotspot/src/share/vm/c1/c1_LIR.cpp b/hotspot/src/share/vm/c1/c1_LIR.cpp index 6aa0f5e0f22..a55ed09fc49 100644 --- a/hotspot/src/share/vm/c1/c1_LIR.cpp +++ b/hotspot/src/share/vm/c1/c1_LIR.cpp @@ -50,8 +50,7 @@ XMMRegister LIR_OprDesc::as_xmm_double_reg() const { #endif // X86 - -#ifdef SPARC +#if defined(SPARC) || defined(PPC) FloatRegister LIR_OprDesc::as_float_reg() const { return FrameMap::nr2floatreg(fpu_regnr()); @@ -63,6 +62,19 @@ FloatRegister LIR_OprDesc::as_double_reg() const { #endif +#ifdef ARM + +FloatRegister LIR_OprDesc::as_float_reg() const { + return as_FloatRegister(fpu_regnr()); +} + +FloatRegister LIR_OprDesc::as_double_reg() const { + return as_FloatRegister(fpu_regnrLo()); +} + +#endif + + LIR_Opr LIR_OprFact::illegalOpr = LIR_OprFact::illegal(); LIR_Opr LIR_OprFact::value_type(ValueType* type) { @@ -119,10 +131,14 @@ LIR_Address::Scale LIR_Address::scale(BasicType type) { #ifndef PRODUCT void LIR_Address::verify() const { -#ifdef SPARC - assert(scale() == times_1, "Scaled addressing mode not available on SPARC and should not be used"); +#if defined(SPARC) || defined(PPC) + assert(scale() == times_1, "Scaled addressing mode not available on SPARC/PPC and should not be used"); assert(disp() == 0 || index()->is_illegal(), "can't have both"); #endif +#ifdef ARM + assert(disp() == 0 || index()->is_illegal(), "can't have both"); + assert(-4096 < disp() && disp() < 4096, "architecture constraint"); +#endif #ifdef _LP64 assert(base()->is_cpu_register(), "wrong base operand"); assert(index()->is_illegal() || index()->is_double_cpu(), "wrong index operand"); @@ -173,13 +189,22 @@ void LIR_OprDesc::validate_type() const { if (!is_pointer() && !is_illegal()) { switch (as_BasicType(type_field())) { case T_LONG: - assert((kind_field() == cpu_register || kind_field() == stack_value) && size_field() == double_size, "must match"); + assert((kind_field() == cpu_register || kind_field() == stack_value) && + size_field() == double_size, "must match"); break; case T_FLOAT: - assert((kind_field() == fpu_register || kind_field() == stack_value) && size_field() == single_size, "must match"); + // FP return values can be also in CPU registers on ARM and PPC (softfp ABI) + assert((kind_field() == fpu_register || kind_field() == stack_value + ARM_ONLY(|| kind_field() == cpu_register) + PPC_ONLY(|| kind_field() == cpu_register) ) && + size_field() == single_size, "must match"); break; case T_DOUBLE: - assert((kind_field() == fpu_register || kind_field() == stack_value) && size_field() == double_size, "must match"); + // FP return values can be also in CPU registers on ARM and PPC (softfp ABI) + assert((kind_field() == fpu_register || kind_field() == stack_value + ARM_ONLY(|| kind_field() == cpu_register) + PPC_ONLY(|| kind_field() == cpu_register) ) && + size_field() == double_size, "must match"); break; case T_BOOLEAN: case T_CHAR: @@ -188,7 +213,8 @@ void LIR_OprDesc::validate_type() const { case T_INT: case T_OBJECT: case T_ARRAY: - assert((kind_field() == cpu_register || kind_field() == stack_value) && size_field() == single_size, "must match"); + assert((kind_field() == cpu_register || kind_field() == stack_value) && + size_field() == single_size, "must match"); break; case T_ILLEGAL: @@ -503,6 +529,10 @@ void LIR_OpVisitState::visit(LIR_Op* op) { assert(opConvert->_info == NULL, "must be"); if (opConvert->_opr->is_valid()) do_input(opConvert->_opr); if (opConvert->_result->is_valid()) do_output(opConvert->_result); +#ifdef PPC + if (opConvert->_tmp1->is_valid()) do_temp(opConvert->_tmp1); + if (opConvert->_tmp2->is_valid()) do_temp(opConvert->_tmp2); +#endif do_stub(opConvert->_stub); break; @@ -530,7 +560,9 @@ void LIR_OpVisitState::visit(LIR_Op* op) { LIR_OpAllocObj* opAllocObj = (LIR_OpAllocObj*)op; if (opAllocObj->_info) do_info(opAllocObj->_info); - if (opAllocObj->_opr->is_valid()) do_input(opAllocObj->_opr); + if (opAllocObj->_opr->is_valid()) { do_input(opAllocObj->_opr); + do_temp(opAllocObj->_opr); + } if (opAllocObj->_tmp1->is_valid()) do_temp(opAllocObj->_tmp1); if (opAllocObj->_tmp2->is_valid()) do_temp(opAllocObj->_tmp2); if (opAllocObj->_tmp3->is_valid()) do_temp(opAllocObj->_tmp3); @@ -826,10 +858,16 @@ void LIR_OpVisitState::visit(LIR_Op* op) { assert(op->as_OpCompareAndSwap() != NULL, "must be"); LIR_OpCompareAndSwap* opCompareAndSwap = (LIR_OpCompareAndSwap*)op; + assert(opCompareAndSwap->_addr->is_valid(), "used"); + assert(opCompareAndSwap->_cmp_value->is_valid(), "used"); + assert(opCompareAndSwap->_new_value->is_valid(), "used"); if (opCompareAndSwap->_info) do_info(opCompareAndSwap->_info); - if (opCompareAndSwap->_addr->is_valid()) do_input(opCompareAndSwap->_addr); - if (opCompareAndSwap->_cmp_value->is_valid()) do_input(opCompareAndSwap->_cmp_value); - if (opCompareAndSwap->_new_value->is_valid()) do_input(opCompareAndSwap->_new_value); + do_input(opCompareAndSwap->_addr); + do_temp(opCompareAndSwap->_addr); + do_input(opCompareAndSwap->_cmp_value); + do_temp(opCompareAndSwap->_cmp_value); + do_input(opCompareAndSwap->_new_value); + do_temp(opCompareAndSwap->_new_value); if (opCompareAndSwap->_tmp1->is_valid()) do_temp(opCompareAndSwap->_tmp1); if (opCompareAndSwap->_tmp2->is_valid()) do_temp(opCompareAndSwap->_tmp2); if (opCompareAndSwap->_result->is_valid()) do_output(opCompareAndSwap->_result); @@ -1303,13 +1341,13 @@ void LIR_List::lock_object(LIR_Opr hdr, LIR_Opr obj, LIR_Opr lock, LIR_Opr scrat info)); } -void LIR_List::unlock_object(LIR_Opr hdr, LIR_Opr obj, LIR_Opr lock, CodeStub* stub) { +void LIR_List::unlock_object(LIR_Opr hdr, LIR_Opr obj, LIR_Opr lock, LIR_Opr scratch, CodeStub* stub) { append(new LIR_OpLock( lir_unlock, hdr, obj, lock, - LIR_OprFact::illegalOpr, + scratch, stub, NULL)); } @@ -1342,22 +1380,19 @@ void LIR_List::store_check(LIR_Opr object, LIR_Opr array, LIR_Opr tmp1, LIR_Opr } -void LIR_List::cas_long(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, LIR_Opr t1, LIR_Opr t2) { - // Compare and swap produces condition code "zero" if contents_of(addr) == cmp_value, - // implying successful swap of new_value into addr - append(new LIR_OpCompareAndSwap(lir_cas_long, addr, cmp_value, new_value, t1, t2)); +void LIR_List::cas_long(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, + LIR_Opr t1, LIR_Opr t2, LIR_Opr result) { + append(new LIR_OpCompareAndSwap(lir_cas_long, addr, cmp_value, new_value, t1, t2, result)); } -void LIR_List::cas_obj(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, LIR_Opr t1, LIR_Opr t2) { - // Compare and swap produces condition code "zero" if contents_of(addr) == cmp_value, - // implying successful swap of new_value into addr - append(new LIR_OpCompareAndSwap(lir_cas_obj, addr, cmp_value, new_value, t1, t2)); +void LIR_List::cas_obj(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, + LIR_Opr t1, LIR_Opr t2, LIR_Opr result) { + append(new LIR_OpCompareAndSwap(lir_cas_obj, addr, cmp_value, new_value, t1, t2, result)); } -void LIR_List::cas_int(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, LIR_Opr t1, LIR_Opr t2) { - // Compare and swap produces condition code "zero" if contents_of(addr) == cmp_value, - // implying successful swap of new_value into addr - append(new LIR_OpCompareAndSwap(lir_cas_int, addr, cmp_value, new_value, t1, t2)); +void LIR_List::cas_int(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, + LIR_Opr t1, LIR_Opr t2, LIR_Opr result) { + append(new LIR_OpCompareAndSwap(lir_cas_int, addr, cmp_value, new_value, t1, t2, result)); } @@ -1400,6 +1435,11 @@ void LIR_OprDesc::print(outputStream* out) const { out->print("fpu%d", fpu_regnr()); } else if (is_double_fpu()) { out->print("fpu%d", fpu_regnrLo()); +#elif defined(ARM) + } else if (is_single_fpu()) { + out->print("s%d", fpu_regnr()); + } else if (is_double_fpu()) { + out->print("d%d", fpu_regnrLo() >> 1); #else } else if (is_single_fpu()) { out->print(as_float_reg()->name()); @@ -1756,6 +1796,12 @@ void LIR_OpConvert::print_instr(outputStream* out) const { print_bytecode(out, bytecode()); in_opr()->print(out); out->print(" "); result_opr()->print(out); out->print(" "); +#ifdef PPC + if(tmp1()->is_valid()) { + tmp1()->print(out); out->print(" "); + tmp2()->print(out); out->print(" "); + } +#endif } void LIR_OpConvert::print_bytecode(outputStream* out, Bytecodes::Code code) { diff --git a/hotspot/src/share/vm/c1/c1_LIR.hpp b/hotspot/src/share/vm/c1/c1_LIR.hpp index aabcfaa84f2..5c7dc4feb07 100644 --- a/hotspot/src/share/vm/c1/c1_LIR.hpp +++ b/hotspot/src/share/vm/c1/c1_LIR.hpp @@ -432,8 +432,7 @@ class LIR_OprDesc: public CompilationResourceObj { // for compatibility with RInfo int fpu () const { return lo_reg_half(); } #endif // X86 - -#ifdef SPARC +#if defined(SPARC) || defined(ARM) || defined(PPC) FloatRegister as_float_reg () const; FloatRegister as_double_reg () const; #endif @@ -519,14 +518,14 @@ class LIR_Address: public LIR_OprPtr { , _type(type) , _disp(0) { verify(); } -#ifdef X86 +#if defined(X86) || defined(ARM) LIR_Address(LIR_Opr base, LIR_Opr index, Scale scale, intx disp, BasicType type): _base(base) , _index(index) , _scale(scale) , _type(type) , _disp(disp) { verify(); } -#endif // X86 +#endif // X86 || ARM LIR_Opr base() const { return _base; } LIR_Opr index() const { return _index; } @@ -566,7 +565,11 @@ class LIR_OprFact: public AllStatic { LIR_OprDesc::float_type | LIR_OprDesc::fpu_register | LIR_OprDesc::single_size); } - +#if defined(ARM) + static LIR_Opr double_fpu(int reg1, int reg2) { return (LIR_Opr)((reg1 << LIR_OprDesc::reg1_shift) | (reg2 << LIR_OprDesc::reg2_shift) | LIR_OprDesc::double_type | LIR_OprDesc::fpu_register | LIR_OprDesc::double_size); } + static LIR_Opr single_softfp(int reg) { return (LIR_Opr)((reg << LIR_OprDesc::reg1_shift) | LIR_OprDesc::float_type | LIR_OprDesc::cpu_register | LIR_OprDesc::single_size); } + static LIR_Opr double_softfp(int reg1, int reg2) { return (LIR_Opr)((reg1 << LIR_OprDesc::reg1_shift) | (reg2 << LIR_OprDesc::reg2_shift) | LIR_OprDesc::double_type | LIR_OprDesc::cpu_register | LIR_OprDesc::double_size); } +#endif #ifdef SPARC static LIR_Opr double_fpu(int reg1, int reg2) { return (LIR_Opr)(intptr_t)((reg1 << LIR_OprDesc::reg1_shift) | (reg2 << LIR_OprDesc::reg2_shift) | @@ -593,7 +596,22 @@ class LIR_OprFact: public AllStatic { LIR_OprDesc::double_size | LIR_OprDesc::is_xmm_mask); } #endif // X86 - +#ifdef PPC + static LIR_Opr double_fpu(int reg) { return (LIR_Opr)(intptr_t)((reg << LIR_OprDesc::reg1_shift) | + (reg << LIR_OprDesc::reg2_shift) | + LIR_OprDesc::double_type | + LIR_OprDesc::fpu_register | + LIR_OprDesc::double_size); } + static LIR_Opr single_softfp(int reg) { return (LIR_Opr)((reg << LIR_OprDesc::reg1_shift) | + LIR_OprDesc::float_type | + LIR_OprDesc::cpu_register | + LIR_OprDesc::single_size); } + static LIR_Opr double_softfp(int reg1, int reg2) { return (LIR_Opr)((reg2 << LIR_OprDesc::reg1_shift) | + (reg1 << LIR_OprDesc::reg2_shift) | + LIR_OprDesc::double_type | + LIR_OprDesc::cpu_register | + LIR_OprDesc::double_size); } +#endif // PPC static LIR_Opr virtual_register(int index, BasicType type) { LIR_Opr res; @@ -623,6 +641,22 @@ class LIR_OprFact: public AllStatic { LIR_OprDesc::virtual_mask); break; +#ifdef __SOFTFP__ + case T_FLOAT: + res = (LIR_Opr)(intptr_t)((index << LIR_OprDesc::data_shift) | + LIR_OprDesc::float_type | + LIR_OprDesc::cpu_register | + LIR_OprDesc::single_size | + LIR_OprDesc::virtual_mask); + break; + case T_DOUBLE: + res = (LIR_Opr)(intptr_t)((index << LIR_OprDesc::data_shift) | + LIR_OprDesc::double_type | + LIR_OprDesc::cpu_register | + LIR_OprDesc::double_size | + LIR_OprDesc::virtual_mask); + break; +#else // __SOFTFP__ case T_FLOAT: res = (LIR_Opr)(intptr_t)((index << LIR_OprDesc::data_shift) | LIR_OprDesc::float_type | @@ -638,7 +672,7 @@ class LIR_OprFact: public AllStatic { LIR_OprDesc::double_size | LIR_OprDesc::virtual_mask); break; - +#endif // __SOFTFP__ default: ShouldNotReachHere(); res = illegalOpr; } @@ -650,11 +684,18 @@ class LIR_OprFact: public AllStatic { // old-style calculation; check if old and new method are equal LIR_OprDesc::OprType t = as_OprType(type); +#ifdef __SOFTFP__ + LIR_Opr old_res = (LIR_Opr)(intptr_t)((index << LIR_OprDesc::data_shift) | + t | + LIR_OprDesc::cpu_register | + LIR_OprDesc::size_for(type) | LIR_OprDesc::virtual_mask); +#else // __SOFTFP__ LIR_Opr old_res = (LIR_Opr)(intptr_t)((index << LIR_OprDesc::data_shift) | t | ((type == T_FLOAT || type == T_DOUBLE) ? LIR_OprDesc::fpu_register : LIR_OprDesc::cpu_register) | LIR_OprDesc::size_for(type) | LIR_OprDesc::virtual_mask); assert(res == old_res, "old and new method not equal"); -#endif +#endif // __SOFTFP__ +#endif // ASSERT return res; } @@ -1306,15 +1347,37 @@ class LIR_OpConvert: public LIR_Op1 { private: Bytecodes::Code _bytecode; ConversionStub* _stub; +#ifdef PPC + LIR_Opr _tmp1; + LIR_Opr _tmp2; +#endif public: LIR_OpConvert(Bytecodes::Code code, LIR_Opr opr, LIR_Opr result, ConversionStub* stub) : LIR_Op1(lir_convert, opr, result) , _stub(stub) +#ifdef PPC + , _tmp1(LIR_OprDesc::illegalOpr()) + , _tmp2(LIR_OprDesc::illegalOpr()) +#endif , _bytecode(code) {} +#ifdef PPC + LIR_OpConvert(Bytecodes::Code code, LIR_Opr opr, LIR_Opr result, ConversionStub* stub + ,LIR_Opr tmp1, LIR_Opr tmp2) + : LIR_Op1(lir_convert, opr, result) + , _stub(stub) + , _tmp1(tmp1) + , _tmp2(tmp2) + , _bytecode(code) {} +#endif + Bytecodes::Code bytecode() const { return _bytecode; } ConversionStub* stub() const { return _stub; } +#ifdef PPC + LIR_Opr tmp1() const { return _tmp1; } + LIR_Opr tmp2() const { return _tmp2; } +#endif virtual void emit_code(LIR_Assembler* masm); virtual LIR_OpConvert* as_OpConvert() { return this; } @@ -1502,6 +1565,9 @@ class LIR_Op2: public LIR_Op { LIR_Condition condition() const { assert(code() == lir_cmp || code() == lir_cmove, "only valid for cmp and cmove"); return _condition; } + void set_condition(LIR_Condition condition) { + assert(code() == lir_cmp || code() == lir_cmove, "only valid for cmp and cmove"); _condition = condition; + } void set_fpu_stack_size(int size) { _fpu_stack_size = size; } int fpu_stack_size() const { return _fpu_stack_size; } @@ -1650,8 +1716,9 @@ class LIR_OpCompareAndSwap : public LIR_Op { LIR_Opr _tmp2; public: - LIR_OpCompareAndSwap(LIR_Code code, LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, LIR_Opr t1, LIR_Opr t2) - : LIR_Op(code, LIR_OprFact::illegalOpr, NULL) // no result, no info + LIR_OpCompareAndSwap(LIR_Code code, LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, + LIR_Opr t1, LIR_Opr t2, LIR_Opr result) + : LIR_Op(code, result, NULL) // no result, no info , _addr(addr) , _cmp_value(cmp_value) , _new_value(new_value) @@ -1832,6 +1899,9 @@ class LIR_List: public CompilationResourceObj { void safepoint(LIR_Opr tmp, CodeEmitInfo* info) { append(new LIR_Op1(lir_safepoint, tmp, info)); } +#ifdef PPC + void convert(Bytecodes::Code code, LIR_Opr left, LIR_Opr dst, LIR_Opr tmp1, LIR_Opr tmp2) { append(new LIR_OpConvert(code, left, dst, NULL, tmp1, tmp2)); } +#endif void convert(Bytecodes::Code code, LIR_Opr left, LIR_Opr dst, ConversionStub* stub = NULL/*, bool is_32bit = false*/) { append(new LIR_OpConvert(code, left, dst, stub)); } void logical_and (LIR_Opr left, LIR_Opr right, LIR_Opr dst) { append(new LIR_Op2(lir_logic_and, left, right, dst)); } @@ -1867,9 +1937,12 @@ class LIR_List: public CompilationResourceObj { append(new LIR_Op2(lir_cmove, condition, src1, src2, dst)); } - void cas_long(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, LIR_Opr t1, LIR_Opr t2); - void cas_obj(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, LIR_Opr t1, LIR_Opr t2); - void cas_int(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, LIR_Opr t1, LIR_Opr t2); + void cas_long(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, + LIR_Opr t1, LIR_Opr t2, LIR_Opr result = LIR_OprFact::illegalOpr); + void cas_obj(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, + LIR_Opr t1, LIR_Opr t2, LIR_Opr result = LIR_OprFact::illegalOpr); + void cas_int(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value, + LIR_Opr t1, LIR_Opr t2, LIR_Opr result = LIR_OprFact::illegalOpr); void abs (LIR_Opr from, LIR_Opr to, LIR_Opr tmp) { append(new LIR_Op2(lir_abs , from, tmp, to)); } void sqrt(LIR_Opr from, LIR_Opr to, LIR_Opr tmp) { append(new LIR_Op2(lir_sqrt, from, tmp, to)); } @@ -1950,7 +2023,7 @@ class LIR_List: public CompilationResourceObj { } void load_stack_address_monitor(int monitor_ix, LIR_Opr dst) { append(new LIR_Op1(lir_monaddr, LIR_OprFact::intConst(monitor_ix), dst)); } - void unlock_object(LIR_Opr hdr, LIR_Opr obj, LIR_Opr lock, CodeStub* stub); + void unlock_object(LIR_Opr hdr, LIR_Opr obj, LIR_Opr lock, LIR_Opr scratch, CodeStub* stub); void lock_object(LIR_Opr hdr, LIR_Opr obj, LIR_Opr lock, LIR_Opr scratch, CodeStub* stub, CodeEmitInfo* info); void set_24bit_fpu() { append(new LIR_Op0(lir_24bit_FPU )); } diff --git a/hotspot/src/share/vm/c1/c1_LIRAssembler.cpp b/hotspot/src/share/vm/c1/c1_LIRAssembler.cpp index 75c713d501b..ee3c5ea8c5e 100644 --- a/hotspot/src/share/vm/c1/c1_LIRAssembler.cpp +++ b/hotspot/src/share/vm/c1/c1_LIRAssembler.cpp @@ -438,6 +438,12 @@ void LIR_Assembler::emit_call(LIR_OpJavaCall* op) { default: ShouldNotReachHere(); } + // JSR 292 + // Record if this method has MethodHandle invokes. + if (op->is_method_handle_invoke()) { + compilation()->set_has_method_handle_invokes(true); + } + #if defined(X86) && defined(TIERED) // C2 leave fpu stack dirty clean it if (UseSSE < 2) { diff --git a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp index 36b46eeaa9f..4e7605f2685 100644 --- a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp +++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp @@ -31,6 +31,12 @@ #define __ gen()->lir()-> #endif +// TODO: ARM - Use some recognizable constant which still fits architectural constraints +#ifdef ARM +#define PATCHED_ADDR (204) +#else +#define PATCHED_ADDR (max_jint) +#endif void PhiResolverState::reset(int max_vregs) { // Initialize array sizes @@ -225,13 +231,13 @@ void LIRItem::load_for_store(BasicType type) { void LIRItem::load_item_force(LIR_Opr reg) { LIR_Opr r = result(); if (r != reg) { +#if !defined(ARM) && !defined(E500V2) if (r->type() != reg->type()) { // moves between different types need an intervening spill slot - LIR_Opr tmp = _gen->force_to_spill(r, reg->type()); - __ move(tmp, reg); - } else { - __ move(r, reg); + r = _gen->force_to_spill(r, reg->type()); } +#endif + __ move(r, reg); _result = reg; } } @@ -628,14 +634,14 @@ void LIRGenerator::monitor_enter(LIR_Opr object, LIR_Opr lock, LIR_Opr hdr, LIR_ } -void LIRGenerator::monitor_exit(LIR_Opr object, LIR_Opr lock, LIR_Opr new_hdr, int monitor_no) { +void LIRGenerator::monitor_exit(LIR_Opr object, LIR_Opr lock, LIR_Opr new_hdr, LIR_Opr scratch, int monitor_no) { if (!GenerateSynchronizationCode) return; // setup registers LIR_Opr hdr = lock; lock = new_hdr; CodeStub* slow_path = new MonitorExitStub(lock, UseFastLocking, monitor_no); __ load_stack_address_monitor(monitor_no, lock); - __ unlock_object(hdr, object, lock, slow_path); + __ unlock_object(hdr, object, lock, scratch, slow_path); } @@ -1400,6 +1406,25 @@ void LIRGenerator::CardTableModRef_post_barrier(LIR_OprDesc* addr, LIR_OprDesc* } assert(addr->is_register(), "must be a register at this point"); +#ifdef ARM + // TODO: ARM - move to platform-dependent code + LIR_Opr tmp = FrameMap::R14_opr; + if (VM_Version::supports_movw()) { + __ move((LIR_Opr)card_table_base, tmp); + } else { + __ move(new LIR_Address(FrameMap::Rthread_opr, in_bytes(JavaThread::card_table_base_offset()), T_ADDRESS), tmp); + } + + CardTableModRefBS* ct = (CardTableModRefBS*)_bs; + LIR_Address *card_addr = new LIR_Address(tmp, addr, (LIR_Address::Scale) -CardTableModRefBS::card_shift, 0, T_BYTE); + if(((int)ct->byte_map_base & 0xff) == 0) { + __ move(tmp, card_addr); + } else { + LIR_Opr tmp_zero = new_register(T_INT); + __ move(LIR_OprFact::intConst(0), tmp_zero); + __ move(tmp_zero, card_addr); + } +#else // ARM LIR_Opr tmp = new_pointer_register(); if (TwoOperandLIRForm) { __ move(addr, tmp); @@ -1415,6 +1440,7 @@ void LIRGenerator::CardTableModRef_post_barrier(LIR_OprDesc* addr, LIR_OprDesc* new LIR_Address(tmp, load_constant(card_table_base), T_BYTE)); } +#endif // ARM } @@ -1507,7 +1533,7 @@ void LIRGenerator::do_StoreField(StoreField* x) { // generate_address to try to be smart about emitting the -1. // Otherwise the patching code won't know how to find the // instruction to patch. - address = new LIR_Address(object.result(), max_jint, field_type); + address = new LIR_Address(object.result(), PATCHED_ADDR, field_type); } else { address = generate_address(object.result(), x->offset(), field_type); } @@ -1584,7 +1610,7 @@ void LIRGenerator::do_LoadField(LoadField* x) { // generate_address to try to be smart about emitting the -1. // Otherwise the patching code won't know how to find the // instruction to patch. - address = new LIR_Address(object.result(), max_jint, field_type); + address = new LIR_Address(object.result(), PATCHED_ADDR, field_type); } else { address = generate_address(object.result(), x->offset(), field_type); } @@ -1844,6 +1870,8 @@ void LIRGenerator::do_UnsafeGetRaw(UnsafeGetRaw* x) { } #endif addr = new LIR_Address(base_op, index_op, LIR_Address::Scale(log2_scale), 0, dst_type); +#elif defined(ARM) + addr = generate_address(base_op, index_op, log2_scale, 0, dst_type); #else if (index_op->is_illegal() || log2_scale == 0) { #ifdef _LP64 @@ -1916,6 +1944,7 @@ void LIRGenerator::do_UnsafePutRaw(UnsafePutRaw* x) { __ convert(Bytecodes::_i2l, idx.result(), index_op); } else { #endif + // TODO: ARM also allows embedded shift in the address __ move(idx.result(), index_op); #ifdef _LP64 } @@ -2204,7 +2233,10 @@ void LIRGenerator::do_Base(Base* x) { // Assign new location to Local instruction for this local Local* local = x->state()->local_at(java_index)->as_Local(); assert(local != NULL, "Locals for incoming arguments must have been created"); +#ifndef __SOFTFP__ + // The java calling convention passes double as long and float as int. assert(as_ValueType(t)->tag() == local->type()->tag(), "check"); +#endif // __SOFTFP__ local->set_operand(dest); _instruction_for_operand.at_put_grow(dest->vreg_number(), local, NULL); java_index += type2size[t]; diff --git a/hotspot/src/share/vm/c1/c1_LIRGenerator.hpp b/hotspot/src/share/vm/c1/c1_LIRGenerator.hpp index 93d3276dd9d..4a69bd842ed 100644 --- a/hotspot/src/share/vm/c1/c1_LIRGenerator.hpp +++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.hpp @@ -314,7 +314,7 @@ class LIRGenerator: public InstructionVisitor, public BlockClosure { void logic_op (Bytecodes::Code code, LIR_Opr dst_reg, LIR_Opr left, LIR_Opr right); void monitor_enter (LIR_Opr object, LIR_Opr lock, LIR_Opr hdr, LIR_Opr scratch, int monitor_no, CodeEmitInfo* info_for_exception, CodeEmitInfo* info); - void monitor_exit (LIR_Opr object, LIR_Opr lock, LIR_Opr hdr, int monitor_no); + void monitor_exit (LIR_Opr object, LIR_Opr lock, LIR_Opr hdr, LIR_Opr scratch, int monitor_no); void new_instance (LIR_Opr dst, ciInstanceKlass* klass, LIR_Opr scratch1, LIR_Opr scratch2, LIR_Opr scratch3, LIR_Opr scratch4, LIR_Opr klass_reg, CodeEmitInfo* info); @@ -338,6 +338,9 @@ class LIRGenerator: public InstructionVisitor, public BlockClosure { } LIR_Address* emit_array_address(LIR_Opr array_opr, LIR_Opr index_opr, BasicType type, bool needs_card_mark); + // the helper for generate_address + void add_large_constant(LIR_Opr src, int c, LIR_Opr dest); + // machine preferences and characteristics bool can_inline_as_constant(Value i) const; bool can_inline_as_constant(LIR_Const* c) const; @@ -393,6 +396,10 @@ class LIRGenerator: public InstructionVisitor, public BlockClosure { return l; } +#ifdef __SOFTFP__ + void do_soft_float_compare(If *x); +#endif // __SOFTFP__ + void init(); SwitchRangeArray* create_lookup_ranges(TableSwitch* x); @@ -444,6 +451,7 @@ class LIRGenerator: public InstructionVisitor, public BlockClosure { static LIR_Opr remOutOpr(); static LIR_Opr shiftCountOpr(); LIR_Opr syncTempOpr(); + LIR_Opr atomicLockOpr(); // returns a register suitable for saving the thread in a // call_runtime_leaf if one is needed. diff --git a/hotspot/src/share/vm/c1/c1_LinearScan.cpp b/hotspot/src/share/vm/c1/c1_LinearScan.cpp index 0888bef3c01..b5adb2db479 100644 --- a/hotspot/src/share/vm/c1/c1_LinearScan.cpp +++ b/hotspot/src/share/vm/c1/c1_LinearScan.cpp @@ -169,7 +169,11 @@ bool LinearScan::is_precolored_cpu_interval(const Interval* i) { } bool LinearScan::is_virtual_cpu_interval(const Interval* i) { +#if defined(__SOFTFP__) || defined(E500V2) + return i->reg_num() >= LIR_OprDesc::vreg_base; +#else return i->reg_num() >= LIR_OprDesc::vreg_base && (i->type() != T_FLOAT && i->type() != T_DOUBLE); +#endif // __SOFTFP__ or E500V2 } bool LinearScan::is_precolored_fpu_interval(const Interval* i) { @@ -177,7 +181,11 @@ bool LinearScan::is_precolored_fpu_interval(const Interval* i) { } bool LinearScan::is_virtual_fpu_interval(const Interval* i) { +#if defined(__SOFTFP__) || defined(E500V2) + return false; +#else return i->reg_num() >= LIR_OprDesc::vreg_base && (i->type() == T_FLOAT || i->type() == T_DOUBLE); +#endif // __SOFTFP__ or E500V2 } bool LinearScan::is_in_fpu_register(const Interval* i) { @@ -2010,12 +2018,18 @@ LIR_Opr LinearScan::calc_operand_for_interval(const Interval* interval) { return LIR_OprFact::single_cpu_oop(assigned_reg); } +#ifdef __SOFTFP__ + case T_FLOAT: // fall through +#endif // __SOFTFP__ case T_INT: { assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register"); assert(interval->assigned_regHi() == any_reg, "must not have hi register"); return LIR_OprFact::single_cpu(assigned_reg); } +#ifdef __SOFTFP__ + case T_DOUBLE: // fall through +#endif // __SOFTFP__ case T_LONG: { int assigned_regHi = interval->assigned_regHi(); assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register"); @@ -2033,7 +2047,7 @@ LIR_Opr LinearScan::calc_operand_for_interval(const Interval* interval) { #ifdef _LP64 return LIR_OprFact::double_cpu(assigned_reg, assigned_reg); #else -#ifdef SPARC +#if defined(SPARC) || defined(PPC) return LIR_OprFact::double_cpu(assigned_regHi, assigned_reg); #else return LIR_OprFact::double_cpu(assigned_reg, assigned_regHi); @@ -2041,6 +2055,7 @@ LIR_Opr LinearScan::calc_operand_for_interval(const Interval* interval) { #endif // LP64 } +#ifndef __SOFTFP__ case T_FLOAT: { #ifdef X86 if (UseSSE >= 1) { @@ -2069,6 +2084,11 @@ LIR_Opr LinearScan::calc_operand_for_interval(const Interval* interval) { assert(interval->assigned_regHi() >= pd_first_fpu_reg && interval->assigned_regHi() <= pd_last_fpu_reg, "no fpu register"); assert(assigned_reg % 2 == 0 && assigned_reg + 1 == interval->assigned_regHi(), "must be sequential and even"); LIR_Opr result = LIR_OprFact::double_fpu(interval->assigned_regHi() - pd_first_fpu_reg, assigned_reg - pd_first_fpu_reg); +#elif defined(ARM) + assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register"); + assert(interval->assigned_regHi() >= pd_first_fpu_reg && interval->assigned_regHi() <= pd_last_fpu_reg, "no fpu register"); + assert(assigned_reg % 2 == 0 && assigned_reg + 1 == interval->assigned_regHi(), "must be sequential and even"); + LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg, interval->assigned_regHi() - pd_first_fpu_reg); #else assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register"); assert(interval->assigned_regHi() == any_reg, "must not have hi register (double fpu values are stored in one register on Intel)"); @@ -2076,6 +2096,7 @@ LIR_Opr LinearScan::calc_operand_for_interval(const Interval* interval) { #endif return result; } +#endif // __SOFTFP__ default: { ShouldNotReachHere(); @@ -2638,6 +2659,12 @@ int LinearScan::append_scope_value_for_operand(LIR_Opr opr, GrowableArrayfpu_regnrLo() == opr->fpu_regnrHi() + 1, "assumed in calculation (only fpu_regnrHi is used)"); #endif +#ifdef ARM + assert(opr->fpu_regnrHi() == opr->fpu_regnrLo() + 1, "assumed in calculation (only fpu_regnrLo is used)"); +#endif +#ifdef PPC + assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation (only fpu_regnrHi is used)"); +#endif VMReg rname_first = frame_map()->fpu_regname(opr->fpu_regnrHi()); #ifdef _LP64 @@ -6135,6 +6162,17 @@ void ControlFlowOptimizer::delete_unnecessary_jumps(BlockList* code) { assert(prev_op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch"); LIR_OpBranch* prev_branch = (LIR_OpBranch*)prev_op; + LIR_Op2* prev_cmp = NULL; + + for(int j = instructions->length() - 3; j >= 0 && prev_cmp == NULL; j--) { + prev_op = instructions->at(j); + if(prev_op->code() == lir_cmp) { + assert(prev_op->as_Op2() != NULL, "branch must be of type LIR_Op2"); + prev_cmp = (LIR_Op2*)prev_op; + assert(prev_branch->cond() == prev_cmp->condition(), "should be the same"); + } + } + assert(prev_cmp != NULL, "should have found comp instruction for branch"); if (prev_branch->block() == code->at(i + 1) && prev_branch->info() == NULL) { TRACE_LINEAR_SCAN(3, tty->print_cr("Negating conditional branch and deleting unconditional branch at end of block B%d", block->block_id())); @@ -6142,6 +6180,7 @@ void ControlFlowOptimizer::delete_unnecessary_jumps(BlockList* code) { // eliminate a conditional branch to the immediate successor prev_branch->change_block(last_branch->block()); prev_branch->negate_cond(); + prev_cmp->set_condition(prev_branch->cond()); instructions->truncate(instructions->length() - 1); } } diff --git a/hotspot/src/share/vm/c1/c1_Runtime1.cpp b/hotspot/src/share/vm/c1/c1_Runtime1.cpp index 924a4831410..96d4e713568 100644 --- a/hotspot/src/share/vm/c1/c1_Runtime1.cpp +++ b/hotspot/src/share/vm/c1/c1_Runtime1.cpp @@ -144,7 +144,7 @@ void Runtime1::generate_blob_for(BufferBlob* buffer_blob, StubID id) { #ifndef TIERED case counter_overflow_id: // Not generated outside the tiered world #endif -#ifdef SPARC +#if defined(SPARC) || defined(PPC) case handle_exception_nofpu_id: // Unused on sparc #endif break; @@ -240,7 +240,8 @@ const char* Runtime1::name_for_address(address entry) { #undef FUNCTION_CASE - return ""; + // Soft float adds more runtime names. + return pd_name_for_address(entry); } @@ -896,7 +897,10 @@ JRT_ENTRY(void, Runtime1::patch_code(JavaThread* thread, Runtime1::StubID stub_i } else { // patch the instruction NativeMovConstReg* n_copy = nativeMovConstReg_at(copy_buff); - assert(n_copy->data() == 0, "illegal init value"); + + assert(n_copy->data() == 0 || + n_copy->data() == (int)Universe::non_oop_word(), + "illegal init value"); assert(load_klass() != NULL, "klass not set"); n_copy->set_data((intx) (load_klass())); @@ -904,7 +908,7 @@ JRT_ENTRY(void, Runtime1::patch_code(JavaThread* thread, Runtime1::StubID stub_i Disassembler::decode(copy_buff, copy_buff + *byte_count, tty); } -#ifdef SPARC +#if defined(SPARC) || defined(PPC) // Update the oop location in the nmethod with the proper // oop. When the code was generated, a NULL was stuffed // in the oop table and that table needs to be update to @@ -934,6 +938,14 @@ JRT_ENTRY(void, Runtime1::patch_code(JavaThread* thread, Runtime1::StubID stub_i if (do_patch) { // replace instructions // first replace the tail, then the call +#ifdef ARM + if(stub_id == Runtime1::load_klass_patching_id && !VM_Version::supports_movw()) { + copy_buff -= *byte_count; + NativeMovConstReg* n_copy2 = nativeMovConstReg_at(copy_buff); + n_copy2->set_data((intx) (load_klass()), instr_pc); + } +#endif + for (int i = NativeCall::instruction_size; i < *byte_count; i++) { address ptr = copy_buff + i; int a_byte = (*ptr) & 0xFF; @@ -960,6 +972,12 @@ JRT_ENTRY(void, Runtime1::patch_code(JavaThread* thread, Runtime1::StubID stub_i RelocIterator iter2(nm, instr_pc2, instr_pc2 + 1); relocInfo::change_reloc_info_for_address(&iter2, (address) instr_pc2, relocInfo::none, relocInfo::oop_type); +#endif +#ifdef PPC + { address instr_pc2 = instr_pc + NativeMovConstReg::lo_offset; + RelocIterator iter2(nm, instr_pc2, instr_pc2 + 1); + relocInfo::change_reloc_info_for_address(&iter2, (address) instr_pc2, relocInfo::none, relocInfo::oop_type); + } #endif } diff --git a/hotspot/src/share/vm/c1/c1_Runtime1.hpp b/hotspot/src/share/vm/c1/c1_Runtime1.hpp index c2c589cc791..1f31ebfbf16 100644 --- a/hotspot/src/share/vm/c1/c1_Runtime1.hpp +++ b/hotspot/src/share/vm/c1/c1_Runtime1.hpp @@ -159,6 +159,9 @@ class Runtime1: public AllStatic { static const char* name_for (StubID id); static const char* name_for_address(address entry); + // platform might add runtime names. + static const char* pd_name_for_address(address entry); + // method tracing static void trace_block_entry(jint block_id); diff --git a/hotspot/src/share/vm/ci/ciEnv.cpp b/hotspot/src/share/vm/ci/ciEnv.cpp index a21d79a2352..de1fb564d76 100644 --- a/hotspot/src/share/vm/ci/ciEnv.cpp +++ b/hotspot/src/share/vm/ci/ciEnv.cpp @@ -728,8 +728,8 @@ ciMethod* ciEnv::get_fake_invokedynamic_method_impl(constantPoolHandle cpool, } // Get the invoker methodOop from the constant pool. - intptr_t f2_value = cpool->cache()->main_entry_at(index)->f2(); - methodOop signature_invoker = methodOop(f2_value); + oop f1_value = cpool->cache()->main_entry_at(index)->f1(); + methodOop signature_invoker = methodOop(f1_value); assert(signature_invoker != NULL && signature_invoker->is_method() && signature_invoker->is_method_handle_invoke(), "correct result from LinkResolver::resolve_invokedynamic"); diff --git a/hotspot/src/share/vm/ci/ciField.cpp b/hotspot/src/share/vm/ci/ciField.cpp index 2729d32d2f5..9851d9e2576 100644 --- a/hotspot/src/share/vm/ci/ciField.cpp +++ b/hotspot/src/share/vm/ci/ciField.cpp @@ -339,7 +339,7 @@ void ciField::print() { if (_type != NULL) _type->print_name(); else tty->print("(reference)"); tty->print(" is_constant=%s", bool_to_str(_is_constant)); - if (_is_constant) { + if (_is_constant && is_static()) { tty->print(" constant_value="); _constant_value.print(); } diff --git a/hotspot/src/share/vm/ci/ciInstanceKlass.cpp b/hotspot/src/share/vm/ci/ciInstanceKlass.cpp index c92cb3345ab..cd75fd52409 100644 --- a/hotspot/src/share/vm/ci/ciInstanceKlass.cpp +++ b/hotspot/src/share/vm/ci/ciInstanceKlass.cpp @@ -403,8 +403,9 @@ GrowableArray* ciInstanceKlass::non_static_fields() { instanceKlass* ik = get_instanceKlass(); int max_n_fields = ik->fields()->length()/instanceKlass::next_offset; + Arena* arena = curEnv->arena(); _non_static_fields = - new (curEnv->arena()) GrowableArray(max_n_fields); + new (arena) GrowableArray(arena, max_n_fields, 0, NULL); NonStaticFieldFiller filler(curEnv, _non_static_fields); ik->do_nonstatic_fields(&filler); } diff --git a/hotspot/src/share/vm/ci/ciMethod.cpp b/hotspot/src/share/vm/ci/ciMethod.cpp index 22fc4f5fb78..463c3b89dae 100644 --- a/hotspot/src/share/vm/ci/ciMethod.cpp +++ b/hotspot/src/share/vm/ci/ciMethod.cpp @@ -55,10 +55,10 @@ ciMethod::ciMethod(methodHandle h_m) : ciObject(h_m) { _exception_handlers = NULL; _liveness = NULL; _method_blocks = NULL; -#ifdef COMPILER2 +#if defined(COMPILER2) || defined(SHARK) _flow = NULL; _bcea = NULL; -#endif // COMPILER2 +#endif // COMPILER2 || SHARK ciEnv *env = CURRENT_ENV; if (env->jvmti_can_hotswap_or_post_breakpoint() && _is_compilable) { @@ -123,10 +123,10 @@ ciMethod::ciMethod(ciInstanceKlass* holder, _can_be_statically_bound = false; _method_blocks = NULL; _method_data = NULL; -#ifdef COMPILER2 +#if defined(COMPILER2) || defined(SHARK) _flow = NULL; _bcea = NULL; -#endif // COMPILER2 +#endif // COMPILER2 || SHARK } @@ -229,6 +229,20 @@ int ciMethod::vtable_index() { } +#ifdef SHARK +// ------------------------------------------------------------------ +// ciMethod::itable_index +// +// Get the position of this method's entry in the itable, if any. +int ciMethod::itable_index() { + check_is_loaded(); + assert(holder()->is_linked(), "must be linked"); + VM_ENTRY_MARK; + return klassItable::compute_itable_index(get_methodOop()); +} +#endif // SHARK + + // ------------------------------------------------------------------ // ciMethod::native_entry // @@ -294,34 +308,34 @@ bool ciMethod::has_balanced_monitors() { // ------------------------------------------------------------------ // ciMethod::get_flow_analysis ciTypeFlow* ciMethod::get_flow_analysis() { -#ifdef COMPILER2 +#if defined(COMPILER2) || defined(SHARK) if (_flow == NULL) { ciEnv* env = CURRENT_ENV; _flow = new (env->arena()) ciTypeFlow(env, this); _flow->do_flow(); } return _flow; -#else // COMPILER2 +#else // COMPILER2 || SHARK ShouldNotReachHere(); return NULL; -#endif // COMPILER2 +#endif // COMPILER2 || SHARK } // ------------------------------------------------------------------ // ciMethod::get_osr_flow_analysis ciTypeFlow* ciMethod::get_osr_flow_analysis(int osr_bci) { -#ifdef COMPILER2 +#if defined(COMPILER2) || defined(SHARK) // OSR entry points are always place after a call bytecode of some sort assert(osr_bci >= 0, "must supply valid OSR entry point"); ciEnv* env = CURRENT_ENV; ciTypeFlow* flow = new (env->arena()) ciTypeFlow(env, this, osr_bci); flow->do_flow(); return flow; -#else // COMPILER2 +#else // COMPILER2 || SHARK ShouldNotReachHere(); return NULL; -#endif // COMPILER2 +#endif // COMPILER2 || SHARK } // ------------------------------------------------------------------ @@ -694,30 +708,21 @@ int ciMethod::scale_count(int count, float prof_factor) { // ------------------------------------------------------------------ // ciMethod::is_method_handle_invoke // -// Return true if the method is a MethodHandle target. +// Return true if the method is an instance of one of the two +// signature-polymorphic MethodHandle methods, invokeExact or invokeGeneric. bool ciMethod::is_method_handle_invoke() const { - bool flag = (holder()->name() == ciSymbol::java_dyn_MethodHandle() && - methodOopDesc::is_method_handle_invoke_name(name()->sid())); -#ifdef ASSERT - if (is_loaded()) { - bool flag2 = ((flags().as_int() & JVM_MH_INVOKE_BITS) == JVM_MH_INVOKE_BITS); - { - VM_ENTRY_MARK; - bool flag3 = get_methodOop()->is_method_handle_invoke(); - assert(flag2 == flag3, "consistent"); - assert(flag == flag3, "consistent"); - } - } -#endif //ASSERT - return flag; + if (!is_loaded()) return false; + VM_ENTRY_MARK; + return get_methodOop()->is_method_handle_invoke(); } // ------------------------------------------------------------------ // ciMethod::is_method_handle_adapter // // Return true if the method is a generated MethodHandle adapter. +// These are built by MethodHandleCompiler. bool ciMethod::is_method_handle_adapter() const { - check_is_loaded(); + if (!is_loaded()) return false; VM_ENTRY_MARK; return get_methodOop()->is_method_handle_adapter(); } diff --git a/hotspot/src/share/vm/ci/ciMethod.hpp b/hotspot/src/share/vm/ci/ciMethod.hpp index 7d94b46b7e9..3a7a4a3e7f9 100644 --- a/hotspot/src/share/vm/ci/ciMethod.hpp +++ b/hotspot/src/share/vm/ci/ciMethod.hpp @@ -70,7 +70,7 @@ class ciMethod : public ciObject { // Optional liveness analyzer. MethodLiveness* _liveness; -#ifdef COMPILER2 +#if defined(COMPILER2) || defined(SHARK) ciTypeFlow* _flow; BCEscapeAnalyzer* _bcea; #endif @@ -141,6 +141,9 @@ class ciMethod : public ciObject { // Runtime information. int vtable_index(); +#ifdef SHARK + int itable_index(); +#endif // SHARK address native_entry(); address interpreter_entry(); diff --git a/hotspot/src/share/vm/ci/ciMethodBlocks.cpp b/hotspot/src/share/vm/ci/ciMethodBlocks.cpp index 31701d998d4..36bfa813a18 100644 --- a/hotspot/src/share/vm/ci/ciMethodBlocks.cpp +++ b/hotspot/src/share/vm/ci/ciMethodBlocks.cpp @@ -252,7 +252,7 @@ ciMethodBlocks::ciMethodBlocks(Arena *arena, ciMethod *meth): _method(meth), _arena(arena), _num_blocks(0), _code_size(meth->code_size()) { int block_estimate = _code_size / 8; - _blocks = new(_arena) GrowableArray(block_estimate); + _blocks = new(_arena) GrowableArray(_arena, block_estimate, 0, NULL); int b2bsize = _code_size * sizeof(ciBlock **); _bci_to_block = (ciBlock **) arena->Amalloc(b2bsize); Copy::zero_to_words((HeapWord*) _bci_to_block, b2bsize / sizeof(HeapWord)); diff --git a/hotspot/src/share/vm/ci/ciTypeFlow.cpp b/hotspot/src/share/vm/ci/ciTypeFlow.cpp index d702d38bc79..3071856b948 100644 --- a/hotspot/src/share/vm/ci/ciTypeFlow.cpp +++ b/hotspot/src/share/vm/ci/ciTypeFlow.cpp @@ -2591,7 +2591,7 @@ void ciTypeFlow::df_flow_types(Block* start, StateVector* temp_vector, JsrSet* temp_set) { int dft_len = 100; - GrowableArray stk(arena(), dft_len, 0, NULL); + GrowableArray stk(dft_len); ciBlock* dummy = _methodBlocks->make_dummy_block(); JsrSet* root_set = new JsrSet(NULL, 0); diff --git a/hotspot/src/share/vm/classfile/classFileParser.cpp b/hotspot/src/share/vm/classfile/classFileParser.cpp index 73fd78c7b98..36085a754f8 100644 --- a/hotspot/src/share/vm/classfile/classFileParser.cpp +++ b/hotspot/src/share/vm/classfile/classFileParser.cpp @@ -62,6 +62,7 @@ void ClassFileParser::parse_constant_pool_entries(constantPoolHandle cp, int len ClassFileStream cfs1 = *cfs0; ClassFileStream* cfs = &cfs1; #ifdef ASSERT + assert(cfs->allocated_on_stack(),"should be local"); u1* old_current = cfs0->current(); #endif @@ -122,7 +123,7 @@ void ClassFileParser::parse_constant_pool_entries(constantPoolHandle cp, int len if (!EnableMethodHandles || _major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) { classfile_parse_error( - (!EnableInvokeDynamic ? + (!EnableMethodHandles ? "This JVM does not support constant tag %u in class file %s" : "Class file version does not support constant tag %u in class file %s"), tag, CHECK); @@ -140,6 +141,22 @@ void ClassFileParser::parse_constant_pool_entries(constantPoolHandle cp, int len ShouldNotReachHere(); } break; + case JVM_CONSTANT_InvokeDynamic : + { + if (!EnableInvokeDynamic || + _major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) { + classfile_parse_error( + (!EnableInvokeDynamic ? + "This JVM does not support constant tag %u in class file %s" : + "Class file version does not support constant tag %u in class file %s"), + tag, CHECK); + } + cfs->guarantee_more(5, CHECK); // bsm_index, name_and_type_index, tag/access_flags + u2 bootstrap_method_index = cfs->get_u2_fast(); + u2 name_and_type_index = cfs->get_u2_fast(); + cp->invoke_dynamic_at_put(index, bootstrap_method_index, name_and_type_index); + } + break; case JVM_CONSTANT_Integer : { cfs->guarantee_more(5, CHECK); // bytes, tag/access_flags @@ -414,6 +431,24 @@ constantPoolHandle ClassFileParser::parse_constant_pool(TRAPS) { ref_index, CHECK_(nullHandle)); } break; + case JVM_CONSTANT_InvokeDynamic : + { + int bootstrap_method_ref_index = cp->invoke_dynamic_bootstrap_method_ref_index_at(index); + int name_and_type_ref_index = cp->invoke_dynamic_name_and_type_ref_index_at(index); + check_property((bootstrap_method_ref_index == 0 && AllowTransitionalJSR292) + || + (valid_cp_range(bootstrap_method_ref_index, length) && + cp->tag_at(bootstrap_method_ref_index).is_method_handle()), + "Invalid constant pool index %u in class file %s", + bootstrap_method_ref_index, + CHECK_(nullHandle)); + check_property(valid_cp_range(name_and_type_ref_index, length) && + cp->tag_at(name_and_type_ref_index).is_name_and_type(), + "Invalid constant pool index %u in class file %s", + name_and_type_ref_index, + CHECK_(nullHandle)); + break; + } default: fatal(err_msg("bad constant pool tag value %u", cp->tag_at(index).value())); diff --git a/hotspot/src/share/vm/classfile/systemDictionary.cpp b/hotspot/src/share/vm/classfile/systemDictionary.cpp index 40c81427afe..fefe4d67c96 100644 --- a/hotspot/src/share/vm/classfile/systemDictionary.cpp +++ b/hotspot/src/share/vm/classfile/systemDictionary.cpp @@ -2507,6 +2507,10 @@ Handle SystemDictionary::make_dynamic_call_site(Handle bootstrap_method, int caller_bci, TRAPS) { Handle empty; + guarantee(bootstrap_method.not_null() && + java_dyn_MethodHandle::is_instance(bootstrap_method()), + "caller must supply a valid BSM"); + Handle caller_mname = MethodHandles::new_MemberName(CHECK_(empty)); MethodHandles::init_MemberName(caller_mname(), caller_method()); @@ -2537,20 +2541,61 @@ Handle SystemDictionary::make_dynamic_call_site(Handle bootstrap_method, return call_site_oop; } -Handle SystemDictionary::find_bootstrap_method(KlassHandle caller, TRAPS) { +Handle SystemDictionary::find_bootstrap_method(methodHandle caller_method, int caller_bci, + int cache_index, TRAPS) { Handle empty; - if (!caller->oop_is_instance()) return empty; - instanceKlassHandle ik(THREAD, caller()); + constantPoolHandle pool; + { + klassOop caller = caller_method->method_holder(); + if (!Klass::cast(caller)->oop_is_instance()) return empty; + pool = constantPoolHandle(THREAD, instanceKlass::cast(caller)->constants()); + } - oop boot_method_oop = ik->bootstrap_method(); - if (boot_method_oop != NULL) { - if (TraceMethodHandles) { - tty->print_cr("bootstrap method for "PTR_FORMAT" cached as "PTR_FORMAT":", ik(), boot_method_oop); + int constant_pool_index = pool->cache()->entry_at(cache_index)->constant_pool_index(); + constantTag tag = pool->tag_at(constant_pool_index); + + if (tag.is_invoke_dynamic()) { + // JVM_CONSTANT_InvokeDynamic is an ordered pair of [bootm, name&type] + // The bootm, being a JVM_CONSTANT_MethodHandle, has its own cache entry. + int bsm_index = pool->invoke_dynamic_bootstrap_method_ref_index_at(constant_pool_index); + if (bsm_index != 0) { + int bsm_index_in_cache = pool->cache()->entry_at(cache_index)->bootstrap_method_index_in_cache(); + DEBUG_ONLY(int bsm_index_2 = pool->cache()->entry_at(bsm_index_in_cache)->constant_pool_index()); + assert(bsm_index == bsm_index_2, "BSM constant lifted to cache"); + if (TraceMethodHandles) { + tty->print_cr("resolving bootstrap method for "PTR_FORMAT" at %d at cache[%d]CP[%d]...", + (intptr_t) caller_method(), caller_bci, cache_index, constant_pool_index); + } + oop bsm_oop = pool->resolve_cached_constant_at(bsm_index_in_cache, CHECK_(empty)); + if (TraceMethodHandles) { + tty->print_cr("bootstrap method for "PTR_FORMAT" at %d retrieved as "PTR_FORMAT":", + (intptr_t) caller_method(), caller_bci, (intptr_t) bsm_oop); + } + assert(bsm_oop->is_oop() + && java_dyn_MethodHandle::is_instance(bsm_oop), "must be sane"); + return Handle(THREAD, bsm_oop); } - assert(boot_method_oop->is_oop() - && java_dyn_MethodHandle::is_instance(boot_method_oop), "must be sane"); - return Handle(THREAD, boot_method_oop); + // else null BSM; fall through + } else if (tag.is_name_and_type()) { + // JSR 292 EDR does not have JVM_CONSTANT_InvokeDynamic + // a bare name&type defaults its BSM to null, so fall through... + } else { + ShouldNotReachHere(); // verifier does not allow this + } + + // Fall through to pick up the per-class bootstrap method. + // This mechanism may go away in the PFD. + assert(AllowTransitionalJSR292, "else the verifier should have stopped us already"); + oop bsm_oop = instanceKlass::cast(caller_method->method_holder())->bootstrap_method(); + if (bsm_oop != NULL) { + if (TraceMethodHandles) { + tty->print_cr("bootstrap method for "PTR_FORMAT" registered as "PTR_FORMAT":", + (intptr_t) caller_method(), (intptr_t) bsm_oop); + } + assert(bsm_oop->is_oop() + && java_dyn_MethodHandle::is_instance(bsm_oop), "must be sane"); + return Handle(THREAD, bsm_oop); } return empty; diff --git a/hotspot/src/share/vm/classfile/systemDictionary.hpp b/hotspot/src/share/vm/classfile/systemDictionary.hpp index 56de18c42aa..11bf2257992 100644 --- a/hotspot/src/share/vm/classfile/systemDictionary.hpp +++ b/hotspot/src/share/vm/classfile/systemDictionary.hpp @@ -492,7 +492,10 @@ public: TRAPS); // coordinate with Java about bootstrap methods - static Handle find_bootstrap_method(KlassHandle caller, TRAPS); + static Handle find_bootstrap_method(methodHandle caller_method, + int caller_bci, // N.B. must be an invokedynamic + int cache_index, // must be corresponding main_entry + TRAPS); // Utility for printing loader "name" as part of tracing constraints static const char* loader_name(oop loader) { diff --git a/hotspot/src/share/vm/classfile/verificationType.cpp b/hotspot/src/share/vm/classfile/verificationType.cpp index ebb5ac85f16..7b507efa901 100644 --- a/hotspot/src/share/vm/classfile/verificationType.cpp +++ b/hotspot/src/share/vm/classfile/verificationType.cpp @@ -70,7 +70,9 @@ bool VerificationType::is_reference_assignable_from( } else if (is_array() && from.is_array()) { VerificationType comp_this = get_component(CHECK_false); VerificationType comp_from = from.get_component(CHECK_false); - return comp_this.is_assignable_from(comp_from, context, CHECK_false); + if (!comp_this.is_bogus() && !comp_from.is_bogus()) { + return comp_this.is_assignable_from(comp_from, context, CHECK_false); + } } return false; } @@ -98,7 +100,7 @@ VerificationType VerificationType::get_component(TRAPS) const { CHECK_(VerificationType::bogus_type())); return VerificationType::reference_type(component); default: - ShouldNotReachHere(); + // Met an invalid type signature, e.g. [X return VerificationType::bogus_type(); } } diff --git a/hotspot/src/share/vm/classfile/verifier.cpp b/hotspot/src/share/vm/classfile/verifier.cpp index 603d4ec3c25..6f2fd206381 100644 --- a/hotspot/src/share/vm/classfile/verifier.cpp +++ b/hotspot/src/share/vm/classfile/verifier.cpp @@ -1847,12 +1847,8 @@ void ClassVerifier::verify_invoke_init( if (type == VerificationType::uninitialized_this_type()) { // The method must be an method of either this class, or one of its // superclasses - klassOop oop = current_class()(); - Klass* klass = oop->klass_part(); - while (klass != NULL && ref_class_type.name() != klass->name()) { - klass = klass->super()->klass_part(); - } - if (klass == NULL) { + if (ref_class_type.name() != current_class()->name() && + !name_in_supers(ref_class_type.name(), current_class())) { verify_error(bci, "Bad method call"); return; } @@ -1913,7 +1909,8 @@ void ClassVerifier::verify_invoke_instructions( unsigned int types = (opcode == Bytecodes::_invokeinterface ? 1 << JVM_CONSTANT_InterfaceMethodref : opcode == Bytecodes::_invokedynamic - ? 1 << JVM_CONSTANT_NameAndType + ? (1 << JVM_CONSTANT_NameAndType + |1 << JVM_CONSTANT_InvokeDynamic) : 1 << JVM_CONSTANT_Methodref); verify_cp_type(index, cp, types, CHECK_VERIFY(this)); diff --git a/hotspot/src/share/vm/code/codeBlob.cpp b/hotspot/src/share/vm/code/codeBlob.cpp index 33b267be711..d5e4525fc83 100644 --- a/hotspot/src/share/vm/code/codeBlob.cpp +++ b/hotspot/src/share/vm/code/codeBlob.cpp @@ -202,6 +202,11 @@ void BufferBlob::free( BufferBlob *blob ) { //---------------------------------------------------------------------------------------------------- // Implementation of AdapterBlob +AdapterBlob::AdapterBlob(int size, CodeBuffer* cb) : + BufferBlob("I2C/C2I adapters", size, cb) { + CodeCache::commit(this); +} + AdapterBlob* AdapterBlob::create(CodeBuffer* cb) { ThreadInVMfromUnknown __tiv; // get to VM state in case we block on CodeCache_lock @@ -210,7 +215,6 @@ AdapterBlob* AdapterBlob::create(CodeBuffer* cb) { { MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); blob = new (size) AdapterBlob(size, cb); - CodeCache::commit(blob); } // Track memory usage statistic after releasing CodeCache_lock MemoryService::track_code_cache_memory_usage(); @@ -560,72 +564,53 @@ void CodeBlob::verify() { ShouldNotReachHere(); } -#ifndef PRODUCT - -void CodeBlob::print() const { - tty->print_cr("[CodeBlob (" INTPTR_FORMAT ")]", this); - tty->print_cr("Framesize: %d", _frame_size); +void CodeBlob::print_on(outputStream* st) const { + st->print_cr("[CodeBlob (" INTPTR_FORMAT ")]", this); + st->print_cr("Framesize: %d", _frame_size); } - void CodeBlob::print_value_on(outputStream* st) const { st->print_cr("[CodeBlob]"); } -#endif - void BufferBlob::verify() { // unimplemented } -#ifndef PRODUCT - -void BufferBlob::print() const { - CodeBlob::print(); - print_value_on(tty); +void BufferBlob::print_on(outputStream* st) const { + CodeBlob::print_on(st); + print_value_on(st); } - void BufferBlob::print_value_on(outputStream* st) const { st->print_cr("BufferBlob (" INTPTR_FORMAT ") used for %s", this, name()); } - -#endif - void RuntimeStub::verify() { // unimplemented } -#ifndef PRODUCT - -void RuntimeStub::print() const { - CodeBlob::print(); - tty->print("Runtime Stub (" INTPTR_FORMAT "): ", this); - tty->print_cr(name()); - Disassembler::decode((CodeBlob*)this); +void RuntimeStub::print_on(outputStream* st) const { + CodeBlob::print_on(st); + st->print("Runtime Stub (" INTPTR_FORMAT "): ", this); + st->print_cr(name()); + Disassembler::decode((CodeBlob*)this, st); } - void RuntimeStub::print_value_on(outputStream* st) const { st->print("RuntimeStub (" INTPTR_FORMAT "): ", this); st->print(name()); } -#endif - void SingletonBlob::verify() { // unimplemented } -#ifndef PRODUCT - -void SingletonBlob::print() const { - CodeBlob::print(); - tty->print_cr(name()); - Disassembler::decode((CodeBlob*)this); +void SingletonBlob::print_on(outputStream* st) const { + CodeBlob::print_on(st); + st->print_cr(name()); + Disassembler::decode((CodeBlob*)this, st); } - void SingletonBlob::print_value_on(outputStream* st) const { st->print_cr(name()); } @@ -633,5 +618,3 @@ void SingletonBlob::print_value_on(outputStream* st) const { void DeoptimizationBlob::print_value_on(outputStream* st) const { st->print_cr("Deoptimization (frame not available)"); } - -#endif // PRODUCT diff --git a/hotspot/src/share/vm/code/codeBlob.hpp b/hotspot/src/share/vm/code/codeBlob.hpp index 1fc0c2f0c1e..28cd68aa6ae 100644 --- a/hotspot/src/share/vm/code/codeBlob.hpp +++ b/hotspot/src/share/vm/code/codeBlob.hpp @@ -163,8 +163,9 @@ class CodeBlob VALUE_OBJ_CLASS_SPEC { // Debugging virtual void verify(); - virtual void print() const PRODUCT_RETURN; - virtual void print_value_on(outputStream* st) const PRODUCT_RETURN; + void print() const { print_on(tty); } + virtual void print_on(outputStream* st) const; + virtual void print_value_on(outputStream* st) const; // Print the comment associated with offset on stream, if there is one virtual void print_block_comment(outputStream* stream, address block_begin) { @@ -209,8 +210,8 @@ class BufferBlob: public CodeBlob { bool is_alive() const { return true; } void verify(); - void print() const PRODUCT_RETURN; - void print_value_on(outputStream* st) const PRODUCT_RETURN; + void print_on(outputStream* st) const; + void print_value_on(outputStream* st) const; }; @@ -219,8 +220,7 @@ class BufferBlob: public CodeBlob { class AdapterBlob: public BufferBlob { private: - AdapterBlob(int size) : BufferBlob("I2C/C2I adapters", size) {} - AdapterBlob(int size, CodeBuffer* cb) : BufferBlob("I2C/C2I adapters", size, cb) {} + AdapterBlob(int size, CodeBuffer* cb); public: // Creation @@ -293,8 +293,8 @@ class RuntimeStub: public CodeBlob { bool is_alive() const { return true; } void verify(); - void print() const PRODUCT_RETURN; - void print_value_on(outputStream* st) const PRODUCT_RETURN; + void print_on(outputStream* st) const; + void print_value_on(outputStream* st) const; }; @@ -318,8 +318,8 @@ class SingletonBlob: public CodeBlob { bool is_alive() const { return true; } void verify(); // does nothing - void print() const PRODUCT_RETURN; - void print_value_on(outputStream* st) const PRODUCT_RETURN; + void print_on(outputStream* st) const; + void print_value_on(outputStream* st) const; }; @@ -374,7 +374,7 @@ class DeoptimizationBlob: public SingletonBlob { void preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) { /* Nothing to do */ } // Printing - void print_value_on(outputStream* st) const PRODUCT_RETURN; + void print_value_on(outputStream* st) const; address unpack() const { return instructions_begin() + _unpack_offset; } address unpack_with_exception() const { return instructions_begin() + _unpack_with_exception; } diff --git a/hotspot/src/share/vm/code/nmethod.cpp b/hotspot/src/share/vm/code/nmethod.cpp index 3f95285af12..af0f1833368 100644 --- a/hotspot/src/share/vm/code/nmethod.cpp +++ b/hotspot/src/share/vm/code/nmethod.cpp @@ -65,6 +65,11 @@ bool nmethod::is_compiled_by_c2() const { if (is_native_method()) return false; return compiler()->is_c2(); } +bool nmethod::is_compiled_by_shark() const { + if (is_native_method()) return false; + assert(compiler() != NULL, "must be"); + return compiler()->is_shark(); +} @@ -1353,6 +1358,10 @@ void nmethod::flush() { CodeCache::remove_saved_code(this); } +#ifdef SHARK + ((SharkCompiler *) compiler())->free_compiled_method(instructions_begin()); +#endif // SHARK + ((CodeBlob*)(this))->flush(); CodeCache::free(this); @@ -1769,6 +1778,7 @@ bool nmethod::detect_scavenge_root_oops() { // Method that knows how to preserve outgoing arguments at call. This method must be // called with a frame corresponding to a Java invoke void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) { +#ifndef SHARK if (!method()->is_native()) { SimpleScopeDesc ssd(this, fr.pc()); Bytecode_invoke* call = Bytecode_invoke_at(ssd.method(), ssd.bci()); @@ -1776,6 +1786,7 @@ void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map symbolOop signature = call->signature(); fr.oops_compiled_arguments_do(signature, has_receiver, reg_map, f); } +#endif // !SHARK } @@ -2279,6 +2290,8 @@ void nmethod::print() const { tty->print("(c1) "); } else if (is_compiled_by_c2()) { tty->print("(c2) "); + } else if (is_compiled_by_shark()) { + tty->print("(shark) "); } else { tty->print("(nm) "); } @@ -2472,8 +2485,12 @@ void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) { if (block_begin == exception_begin()) stream->print_cr("[Exception Handler]"); if (block_begin == stub_begin()) stream->print_cr("[Stub Code]"); if (block_begin == deopt_handler_begin()) stream->print_cr("[Deopt Handler Code]"); - if (block_begin == deopt_mh_handler_begin()) stream->print_cr("[Deopt MH Handler Code]"); + + if (has_method_handle_invokes()) + if (block_begin == deopt_mh_handler_begin()) stream->print_cr("[Deopt MH Handler Code]"); + if (block_begin == consts_begin()) stream->print_cr("[Constants]"); + if (block_begin == entry_point()) { methodHandle m = method(); if (m.not_null()) { diff --git a/hotspot/src/share/vm/code/nmethod.hpp b/hotspot/src/share/vm/code/nmethod.hpp index 67a87a64ad8..b57cb5e3dc7 100644 --- a/hotspot/src/share/vm/code/nmethod.hpp +++ b/hotspot/src/share/vm/code/nmethod.hpp @@ -329,6 +329,7 @@ class nmethod : public CodeBlob { bool is_compiled_by_c1() const; bool is_compiled_by_c2() const; + bool is_compiled_by_shark() const; // boundaries for different parts address code_begin () const { return _entry_point; } @@ -606,6 +607,8 @@ public: void print_nul_chk_table() PRODUCT_RETURN; void print_nmethod(bool print_code); + // need to re-define this from CodeBlob else the overload hides it + virtual void print_on(outputStream* st) const { CodeBlob::print_on(st); } void print_on(outputStream* st, const char* title) const; // Logging diff --git a/hotspot/src/share/vm/code/vtableStubs.cpp b/hotspot/src/share/vm/code/vtableStubs.cpp index 3a4c5e53635..028cfe83850 100644 --- a/hotspot/src/share/vm/code/vtableStubs.cpp +++ b/hotspot/src/share/vm/code/vtableStubs.cpp @@ -67,8 +67,8 @@ void* VtableStub::operator new(size_t size, int code_size) { } -void VtableStub::print() { - tty->print("vtable stub (index = %d, receiver_location = %d, code = [" INTPTR_FORMAT ", " INTPTR_FORMAT "[)", +void VtableStub::print_on(outputStream* st) const { + st->print("vtable stub (index = %d, receiver_location = %d, code = [" INTPTR_FORMAT ", " INTPTR_FORMAT "[)", index(), receiver_location(), code_begin(), code_end()); } diff --git a/hotspot/src/share/vm/code/vtableStubs.hpp b/hotspot/src/share/vm/code/vtableStubs.hpp index 526aa648ecf..e74582f98bf 100644 --- a/hotspot/src/share/vm/code/vtableStubs.hpp +++ b/hotspot/src/share/vm/code/vtableStubs.hpp @@ -86,7 +86,9 @@ class VtableStub { bool is_abstract_method_error(address epc) { return epc == code_begin()+_ame_offset; } bool is_null_pointer_exception(address epc) { return epc == code_begin()+_npe_offset; } - void print(); + void print_on(outputStream* st) const; + void print() const { print_on(tty); } + }; diff --git a/hotspot/src/share/vm/compiler/abstractCompiler.hpp b/hotspot/src/share/vm/compiler/abstractCompiler.hpp index fc54c9836db..720ded6ebe9 100644 --- a/hotspot/src/share/vm/compiler/abstractCompiler.hpp +++ b/hotspot/src/share/vm/compiler/abstractCompiler.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -45,18 +45,26 @@ class AbstractCompiler : public CHeapObj { // Missing feature tests virtual bool supports_native() { return true; } virtual bool supports_osr () { return true; } -#if defined(TIERED) || ( !defined(COMPILER1) && !defined(COMPILER2)) +#if defined(TIERED) || ( !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK)) virtual bool is_c1 () { return false; } virtual bool is_c2 () { return false; } + virtual bool is_shark() { return false; } #else #ifdef COMPILER1 bool is_c1 () { return true; } bool is_c2 () { return false; } + bool is_shark() { return false; } #endif // COMPILER1 #ifdef COMPILER2 bool is_c1 () { return false; } bool is_c2 () { return true; } + bool is_shark() { return false; } #endif // COMPILER2 +#ifdef SHARK + bool is_c1 () { return false; } + bool is_c2 () { return false; } + bool is_shark() { return true; } +#endif // SHARK #endif // TIERED // Customization diff --git a/hotspot/src/share/vm/compiler/compileBroker.cpp b/hotspot/src/share/vm/compiler/compileBroker.cpp index 9ae477e3e15..7288cac07ba 100644 --- a/hotspot/src/share/vm/compiler/compileBroker.cpp +++ b/hotspot/src/share/vm/compiler/compileBroker.cpp @@ -568,6 +568,14 @@ void CompileBroker::compilation_init() { #endif #endif // COMPILER2 +#ifdef SHARK +#if defined(COMPILER1) || defined(COMPILER2) +#error "Can't use COMPILER1 or COMPILER2 with shark" +#endif + _compilers[0] = new SharkCompiler(); + _compilers[1] = _compilers[0]; +#endif + // Initialize the CompileTask free list _task_free_list = NULL; diff --git a/hotspot/src/share/vm/compiler/disassembler.cpp b/hotspot/src/share/vm/compiler/disassembler.cpp index 2d73e83f628..8176a816463 100644 --- a/hotspot/src/share/vm/compiler/disassembler.cpp +++ b/hotspot/src/share/vm/compiler/disassembler.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 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 @@ -371,7 +371,7 @@ static int printf_to_env(void* env_pv, const char* format, ...) { address decode_env::decode_instructions(address start, address end) { _start = start; _end = end; - assert((((intptr_t)start | (intptr_t)end) % Disassembler::pd_instruction_alignment() == 0), "misaligned insn addr"); + assert(((((intptr_t)start | (intptr_t)end) % Disassembler::pd_instruction_alignment()) == 0), "misaligned insn addr"); const int show_bytes = false; // for disassembler debugging @@ -423,8 +423,14 @@ void Disassembler::decode(nmethod* nm, outputStream* st) { env.output()->print_cr("Decoding compiled method " INTPTR_FORMAT ":", nm); env.output()->print_cr("Code:"); +#ifdef SHARK + SharkEntry* entry = (SharkEntry *) nm->instructions_begin(); + unsigned char* p = entry->code_start(); + unsigned char* end = entry->code_limit(); +#else unsigned char* p = nm->instructions_begin(); unsigned char* end = nm->instructions_end(); +#endif // SHARK // If there has been profiling, print the buckets. if (FlatProfiler::bucket_start_for(p) != NULL) { diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp index 0aa08ec3018..1fac91a5466 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp @@ -664,19 +664,14 @@ CMSCollector::CMSCollector(ConcurrentMarkSweepGeneration* cmsGen, return; } - // XXX use a global constant instead of 64! - typedef struct OopTaskQueuePadded { - OopTaskQueue work_queue; - char pad[64 - sizeof(OopTaskQueue)]; // prevent false sharing - } OopTaskQueuePadded; - + typedef Padded PaddedOopTaskQueue; for (i = 0; i < num_queues; i++) { - OopTaskQueuePadded *q_padded = new OopTaskQueuePadded(); - if (q_padded == NULL) { + PaddedOopTaskQueue *q = new PaddedOopTaskQueue(); + if (q == NULL) { warning("work_queue allocation failure."); return; } - _task_queues->register_queue(i, &q_padded->work_queue); + _task_queues->register_queue(i, q); } for (i = 0; i < num_queues; i++) { _task_queues->queue(i)->initialize(); diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/vmCMSOperations.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/vmCMSOperations.cpp index bcded9b04a8..bf5188ba74c 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/vmCMSOperations.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/vmCMSOperations.cpp @@ -234,6 +234,11 @@ void VM_GenCollectFullConcurrent::doit_epilogue() { GenCollectedHeap* gch = GenCollectedHeap::heap(); if (_gc_cause != GCCause::_gc_locker && gch->total_full_collections_completed() <= _full_gc_count_before) { + // maybe we should change the condition to test _gc_cause == + // GCCause::_java_lang_system_gc, instead of + // _gc_cause != GCCause::_gc_locker + assert(_gc_cause == GCCause::_java_lang_system_gc, + "the only way to get here if this was a System.gc()-induced GC"); assert(ExplicitGCInvokesConcurrent, "Error"); // Now, wait for witnessing concurrent gc cycle to complete, // but do so in native mode, because we want to lock the diff --git a/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp b/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp index 2b46502b67d..1cbb86c0371 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp @@ -158,13 +158,18 @@ CollectionSetChooser::CollectionSetChooser() : // The line below is the worst bit of C++ hackery I've ever written // (Detlefs, 11/23). You should think of it as equivalent to // "_regions(100, true)": initialize the growable array and inform it - // that it should allocate its elem array(s) on the C heap. The first - // argument, however, is actually a comma expression (new-expr, 100). - // The purpose of the new_expr is to inform the growable array that it - // is *already* allocated on the C heap: it uses the placement syntax to - // keep it from actually doing any allocation. - _markedRegions((ResourceObj::operator new (sizeof(GrowableArray), - (void*)&_markedRegions, + // that it should allocate its elem array(s) on the C heap. + // + // The first argument, however, is actually a comma expression + // (set_allocation_type(this, C_HEAP), 100). The purpose of the + // set_allocation_type() call is to replace the default allocation + // type for embedded objects STACK_OR_EMBEDDED with C_HEAP. It will + // allow to pass the assert in GenericGrowableArray() which checks + // that a growable array object must be on C heap if elements are. + // + // Note: containing object is allocated on C heap since it is CHeapObj. + // + _markedRegions((ResourceObj::set_allocation_type((address)&_markedRegions, ResourceObj::C_HEAP), 100), true), diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.cpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.cpp index 7652a5f05e4..78d3d5cb2cd 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -271,21 +271,16 @@ jbyte* ConcurrentG1Refine::add_card_count(jbyte* card_ptr, int* count, bool* def if (cas_res == prev_epoch_entry) { // We successfully updated the card num value in the epoch entry count_ptr->_count = 0; // initialize counter for new card num + jbyte* old_card_ptr = card_num_2_ptr(old_card_num); // Even though the region containg the card at old_card_num was not // in the young list when old_card_num was recorded in the epoch // cache it could have been added to the free list and subsequently - // added to the young list in the intervening time. If the evicted - // card is in a young region just return the card_ptr and the evicted - // card will not be cleaned. See CR 6817995. - - jbyte* old_card_ptr = card_num_2_ptr(old_card_num); - if (is_young_card(old_card_ptr)) { - *count = 0; - // We can defer the processing of card_ptr - *defer = true; - return card_ptr; - } + // added to the young list in the intervening time. See CR 6817995. + // We do not deal with this case here - it will be handled in + // HeapRegion::oops_on_card_seq_iterate_careful after it has been + // determined that the region containing the card has been allocated + // to, and it's safe to check the young type of the region. // We do not want to defer processing of card_ptr in this case // (we need to refine old_card_ptr and card_ptr) @@ -301,22 +296,22 @@ jbyte* ConcurrentG1Refine::cache_insert(jbyte* card_ptr, bool* defer) { jbyte* cached_ptr = add_card_count(card_ptr, &count, defer); assert(cached_ptr != NULL, "bad cached card ptr"); - if (is_young_card(cached_ptr)) { - // The region containing cached_ptr has been freed during a clean up - // pause, reallocated, and tagged as young. - assert(cached_ptr != card_ptr, "shouldn't be"); + // We've just inserted a card pointer into the card count cache + // and got back the card that we just inserted or (evicted) the + // previous contents of that count slot. - // We've just inserted a new old-gen card pointer into the card count - // cache and evicted the previous contents of that count slot. - // The evicted card pointer has been determined to be in a young region - // and so cannot be the newly inserted card pointer (that will be - // in an old region). - // The count for newly inserted card will be set to zero during the - // insertion, so we don't want to defer the cleaning of the newly - // inserted card pointer. - assert(*defer == false, "deferring non-hot card"); - return NULL; - } + // The card we got back could be in a young region. When the + // returned card (if evicted) was originally inserted, we had + // determined that its containing region was not young. However + // it is possible for the region to be freed during a cleanup + // pause, then reallocated and tagged as young which will result + // in the returned card residing in a young region. + // + // We do not deal with this case here - the change from non-young + // to young could be observed at any time - it will be handled in + // HeapRegion::oops_on_card_seq_iterate_careful after it has been + // determined that the region containing the card has been allocated + // to. // The card pointer we obtained from card count cache is not hot // so do not store it in the cache; return it for immediate @@ -325,7 +320,7 @@ jbyte* ConcurrentG1Refine::cache_insert(jbyte* card_ptr, bool* defer) { return cached_ptr; } - // Otherwise, the pointer we got from the _card_counts is hot. + // Otherwise, the pointer we got from the _card_counts cache is hot. jbyte* res = NULL; MutexLockerEx x(HotCardCache_lock, Mutex::_no_safepoint_check_flag); if (_n_hot == _hot_cache_size) { @@ -338,17 +333,8 @@ jbyte* ConcurrentG1Refine::cache_insert(jbyte* card_ptr, bool* defer) { if (_hot_cache_idx == _hot_cache_size) _hot_cache_idx = 0; _n_hot++; - if (res != NULL) { - // Even though the region containg res was not in the young list - // when it was recorded in the hot cache it could have been added - // to the free list and subsequently added to the young list in - // the intervening time. If res is in a young region, return NULL - // so that res is not cleaned. See CR 6817995. - - if (is_young_card(res)) { - res = NULL; - } - } + // The card obtained from the hot card cache could be in a young + // region. See above on how this can happen. return res; } diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp index 8ecced2375b..88d9e01d0ab 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp @@ -266,6 +266,12 @@ void ConcurrentMarkThread::run() { _cm->clearNextBitmap(); _sts.leave(); } + + // Update the number of full collections that have been + // completed. This will also notify the FullGCCount_lock in case a + // Java thread is waiting for a full GC to happen (e.g., it + // called System.gc() with +ExplicitGCInvokesConcurrent). + g1->increment_full_collections_completed(true /* outer */); } assert(_should_terminate, "just checking"); diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp index b242e78ee7e..658ac777f49 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp @@ -638,6 +638,11 @@ G1CollectedHeap::attempt_allocation_slow(size_t word_size, // Now retry the allocation. if (_cur_alloc_region != NULL) { + if (allocated_young_region != NULL) { + // We need to ensure that the store to top does not + // float above the setting of the young type. + OrderAccess::storestore(); + } res = _cur_alloc_region->allocate(word_size); } } @@ -809,7 +814,8 @@ public: } }; -void G1CollectedHeap::do_collection(bool full, bool clear_all_soft_refs, +void G1CollectedHeap::do_collection(bool explicit_gc, + bool clear_all_soft_refs, size_t word_size) { if (GC_locker::check_active_before_gc()) { return; // GC is disabled (e.g. JNI GetXXXCritical operation) @@ -821,10 +827,6 @@ void G1CollectedHeap::do_collection(bool full, bool clear_all_soft_refs, Universe::print_heap_before_gc(); } - if (full && DisableExplicitGC) { - return; - } - assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint"); assert(Thread::current() == VMThread::vm_thread(), "should be in vm thread"); @@ -837,9 +839,11 @@ void G1CollectedHeap::do_collection(bool full, bool clear_all_soft_refs, IsGCActiveMark x; // Timing + bool system_gc = (gc_cause() == GCCause::_java_lang_system_gc); + assert(!system_gc || explicit_gc, "invariant"); gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps); TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); - TraceTime t(full ? "Full GC (System.gc())" : "Full GC", + TraceTime t(system_gc ? "Full GC (System.gc())" : "Full GC", PrintGC, true, gclog_or_tty); TraceMemoryManagerStats tms(true /* fullGC */); @@ -944,7 +948,7 @@ void G1CollectedHeap::do_collection(bool full, bool clear_all_soft_refs, heap_region_iterate(&rs_clear); // Resize the heap if necessary. - resize_if_necessary_after_full_collection(full ? 0 : word_size); + resize_if_necessary_after_full_collection(explicit_gc ? 0 : word_size); if (_cg1r->use_cache()) { _cg1r->clear_and_record_card_counts(); @@ -1009,13 +1013,18 @@ void G1CollectedHeap::do_collection(bool full, bool clear_all_soft_refs, "young list should be empty at this point"); } + // Update the number of full collections that have been completed. + increment_full_collections_completed(false /* outer */); + if (PrintHeapAtGC) { Universe::print_heap_after_gc(); } } void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) { - do_collection(true, clear_all_soft_refs, 0); + do_collection(true, /* explicit_gc */ + clear_all_soft_refs, + 0 /* word_size */); } // This code is mostly copied from TenuredGeneration. @@ -1331,6 +1340,7 @@ G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) : _young_list(new YoungList(this)), _gc_time_stamp(0), _surviving_young_words(NULL), + _full_collections_completed(0), _in_cset_fast_test(NULL), _in_cset_fast_test_base(NULL), _dirty_cards_region_list(NULL) { @@ -1689,6 +1699,51 @@ size_t G1CollectedHeap::unsafe_max_alloc() { return car->free(); } +bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) { + return + ((cause == GCCause::_gc_locker && GCLockerInvokesConcurrent) || + (cause == GCCause::_java_lang_system_gc && ExplicitGCInvokesConcurrent)); +} + +void G1CollectedHeap::increment_full_collections_completed(bool outer) { + MonitorLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag); + + // We have already incremented _total_full_collections at the start + // of the GC, so total_full_collections() represents how many full + // collections have been started. + unsigned int full_collections_started = total_full_collections(); + + // Given that this method is called at the end of a Full GC or of a + // concurrent cycle, and those can be nested (i.e., a Full GC can + // interrupt a concurrent cycle), the number of full collections + // completed should be either one (in the case where there was no + // nesting) or two (when a Full GC interrupted a concurrent cycle) + // behind the number of full collections started. + + // This is the case for the inner caller, i.e. a Full GC. + assert(outer || + (full_collections_started == _full_collections_completed + 1) || + (full_collections_started == _full_collections_completed + 2), + err_msg("for inner caller: full_collections_started = %u " + "is inconsistent with _full_collections_completed = %u", + full_collections_started, _full_collections_completed)); + + // This is the case for the outer caller, i.e. the concurrent cycle. + assert(!outer || + (full_collections_started == _full_collections_completed + 1), + err_msg("for outer caller: full_collections_started = %u " + "is inconsistent with _full_collections_completed = %u", + full_collections_started, _full_collections_completed)); + + _full_collections_completed += 1; + + // This notify_all() will ensure that a thread that called + // System.gc() with (with ExplicitGCInvokesConcurrent set or not) + // and it's waiting for a full GC to finish will be woken up. It is + // waiting in VM_G1IncCollectionPause::doit_epilogue(). + FullGCCount_lock->notify_all(); +} + void G1CollectedHeap::collect_as_vm_thread(GCCause::Cause cause) { assert(Thread::current()->is_VM_thread(), "Precondition#1"); assert(Heap_lock->is_locked(), "Precondition#2"); @@ -1709,25 +1764,41 @@ void G1CollectedHeap::collect(GCCause::Cause cause) { // The caller doesn't have the Heap_lock assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock"); - int gc_count_before; + unsigned int gc_count_before; + unsigned int full_gc_count_before; { MutexLocker ml(Heap_lock); // Read the GC count while holding the Heap_lock gc_count_before = SharedHeap::heap()->total_collections(); + full_gc_count_before = SharedHeap::heap()->total_full_collections(); // Don't want to do a GC until cleanup is completed. wait_for_cleanup_complete(); - } // We give up heap lock; VMThread::execute gets it back below - switch (cause) { - case GCCause::_scavenge_alot: { - // Do an incremental pause, which might sometimes be abandoned. - VM_G1IncCollectionPause op(gc_count_before, cause); + + // We give up heap lock; VMThread::execute gets it back below + } + + if (should_do_concurrent_full_gc(cause)) { + // Schedule an initial-mark evacuation pause that will start a + // concurrent cycle. + VM_G1IncCollectionPause op(gc_count_before, + true, /* should_initiate_conc_mark */ + g1_policy()->max_pause_time_ms(), + cause); + VMThread::execute(&op); + } else { + if (cause == GCCause::_gc_locker + DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) { + + // Schedule a standard evacuation pause. + VM_G1IncCollectionPause op(gc_count_before, + false, /* should_initiate_conc_mark */ + g1_policy()->max_pause_time_ms(), + cause); VMThread::execute(&op); - break; - } - default: { - // In all other cases, we currently do a full gc. - VM_G1CollectFull op(gc_count_before, cause); + } else { + // Schedule a Full GC. + VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause); VMThread::execute(&op); } } @@ -1989,6 +2060,11 @@ void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) { void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r, HeapRegionClosure *cl) { + if (r == NULL) { + // The CSet is empty so there's nothing to do. + return; + } + assert(r->in_collection_set(), "Start region must be a member of the collection set."); HeapRegion* cur = r; @@ -2481,11 +2557,13 @@ void G1CollectedHeap::gc_epilogue(bool full /* Ignored */) { } void G1CollectedHeap::do_collection_pause() { + assert(Heap_lock->owned_by_self(), "we assume we'reholding the Heap_lock"); + // Read the GC count while holding the Heap_lock // we need to do this _before_ wait_for_cleanup_complete(), to // ensure that we do not give up the heap lock and potentially // pick up the wrong count - int gc_count_before = SharedHeap::heap()->total_collections(); + unsigned int gc_count_before = SharedHeap::heap()->total_collections(); // Don't want to do a GC pause while cleanup is being completed! wait_for_cleanup_complete(); @@ -2493,7 +2571,10 @@ void G1CollectedHeap::do_collection_pause() { g1_policy()->record_stop_world_start(); { MutexUnlocker mu(Heap_lock); // give up heap lock, execute gets it back - VM_G1IncCollectionPause op(gc_count_before); + VM_G1IncCollectionPause op(gc_count_before, + false, /* should_initiate_conc_mark */ + g1_policy()->max_pause_time_ms(), + GCCause::_g1_inc_collection_pause); VMThread::execute(&op); } } @@ -2612,7 +2693,7 @@ struct PrepareForRSScanningClosure : public HeapRegionClosure { }; void -G1CollectedHeap::do_collection_pause_at_safepoint() { +G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) { if (GC_locker::check_active_before_gc()) { return; // GC is disabled (e.g. JNI GetXXXCritical operation) } @@ -2637,8 +2718,12 @@ G1CollectedHeap::do_collection_pause_at_safepoint() { else strcat(verbose_str, "(partial)"); } - if (g1_policy()->during_initial_mark_pause()) + if (g1_policy()->during_initial_mark_pause()) { strcat(verbose_str, " (initial-mark)"); + // We are about to start a marking cycle, so we increment the + // full collection counter. + increment_total_full_collections(); + } // if PrintGCDetails is on, we'll print long statistics information // in the collector policy code, so let's not print this as the output @@ -2661,7 +2746,6 @@ G1CollectedHeap::do_collection_pause_at_safepoint() { "young list should be well formed"); } - bool abandoned = false; { // Call to jvmpi::post_class_unload_events must occur outside of active GC IsGCActiveMark x; @@ -2743,7 +2827,7 @@ G1CollectedHeap::do_collection_pause_at_safepoint() { // Now choose the CS. We may abandon a pause if we find no // region that will fit in the MMU pause. - bool abandoned = g1_policy()->choose_collection_set(); + bool abandoned = g1_policy()->choose_collection_set(target_pause_time_ms); // Nothing to do if we were unable to choose a collection set. if (!abandoned) { diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp index 38b44e72c75..74606c18bdf 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp @@ -277,6 +277,18 @@ private: void update_surviving_young_words(size_t* surv_young_words); void cleanup_surviving_young_words(); + // It decides whether an explicit GC should start a concurrent cycle + // instead of doing a STW GC. Currently, a concurrent cycle is + // explicitly started if: + // (a) cause == _gc_locker and +GCLockerInvokesConcurrent, or + // (b) cause == _java_lang_system_gc and +ExplicitGCInvokesConcurrent. + bool should_do_concurrent_full_gc(GCCause::Cause cause); + + // Keeps track of how many "full collections" (i.e., Full GCs or + // concurrent cycles) we have completed. The number of them we have + // started is maintained in _total_full_collections in CollectedHeap. + volatile unsigned int _full_collections_completed; + protected: // Returns "true" iff none of the gc alloc regions have any allocations @@ -356,13 +368,14 @@ protected: // GC pause. void retire_alloc_region(HeapRegion* alloc_region, bool par); - // Helper function for two callbacks below. - // "full", if true, indicates that the GC is for a System.gc() request, - // and should collect the entire heap. If "clear_all_soft_refs" is true, - // all soft references are cleared during the GC. If "full" is false, - // "word_size" describes the allocation that the GC should - // attempt (at least) to satisfy. - void do_collection(bool full, bool clear_all_soft_refs, + // - if explicit_gc is true, the GC is for a System.gc() or a heap + // inspection request and should collect the entire heap + // - if clear_all_soft_refs is true, all soft references are cleared + // during the GC + // - if explicit_gc is false, word_size describes the allocation that + // the GC should attempt (at least) to satisfy + void do_collection(bool explicit_gc, + bool clear_all_soft_refs, size_t word_size); // Callback from VM_G1CollectFull operation. @@ -431,6 +444,26 @@ public: _in_cset_fast_test_length * sizeof(bool)); } + // This is called at the end of either a concurrent cycle or a Full + // GC to update the number of full collections completed. Those two + // can happen in a nested fashion, i.e., we start a concurrent + // cycle, a Full GC happens half-way through it which ends first, + // and then the cycle notices that a Full GC happened and ends + // too. The outer parameter is a boolean to help us do a bit tighter + // consistency checking in the method. If outer is false, the caller + // is the inner caller in the nesting (i.e., the Full GC). If outer + // is true, the caller is the outer caller in this nesting (i.e., + // the concurrent cycle). Further nesting is not currently + // supported. The end of the this call also notifies the + // FullGCCount_lock in case a Java thread is waiting for a full GC + // to happen (e.g., it called System.gc() with + // +ExplicitGCInvokesConcurrent). + void increment_full_collections_completed(bool outer); + + unsigned int full_collections_completed() { + return _full_collections_completed; + } + protected: // Shrink the garbage-first heap by at most the given size (in bytes!). @@ -444,7 +477,7 @@ protected: // The guts of the incremental collection pause, executed by the vm // thread. - virtual void do_collection_pause_at_safepoint(); + virtual void do_collection_pause_at_safepoint(double target_pause_time_ms); // Actually do the work of evacuating the collection set. virtual void evacuate_collection_set(); diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp index 1eeba34217c..0cb73eb0c6b 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp @@ -154,7 +154,6 @@ G1CollectorPolicy::G1CollectorPolicy() : _known_garbage_bytes(0), _young_gc_eff_seq(new TruncatedSeq(TruncatedSeqLength)), - _target_pause_time_ms(-1.0), _recent_prev_end_times_for_all_gcs_sec(new TruncatedSeq(NumPrevPausesForHeuristics)), @@ -1635,8 +1634,6 @@ void G1CollectorPolicy::record_collection_pause_end(bool abandoned) { double update_rs_time_goal_ms = _mmu_tracker->max_gc_time() * MILLIUNITS * G1RSetUpdatingPauseTimePercent / 100.0; adjust_concurrent_refinement(update_rs_time, update_rs_processed_buffers, update_rs_time_goal_ms); // - - _target_pause_time_ms = -1.0; } // @@ -2366,7 +2363,6 @@ G1CollectorPolicy_BestRegionsFirst::should_do_collection_pause(size_t if (reached_target_length) { assert( young_list_length > 0 && _g1->young_list()->length() > 0, "invariant" ); - _target_pause_time_ms = max_pause_time_ms; return true; } } else { @@ -2398,6 +2394,17 @@ bool G1CollectorPolicy_BestRegionsFirst::assertMarkedBytesDataOK() { } #endif +bool +G1CollectorPolicy::force_initial_mark_if_outside_cycle() { + bool during_cycle = _g1->concurrent_mark()->cmThread()->during_cycle(); + if (!during_cycle) { + set_initiate_conc_mark_if_possible(); + return true; + } else { + return false; + } +} + void G1CollectorPolicy::decide_on_conc_mark_initiation() { // We are about to decide on whether this pause will be an @@ -2864,7 +2871,8 @@ void G1CollectorPolicy::print_collection_set(HeapRegion* list_head, outputStream #endif // !PRODUCT bool -G1CollectorPolicy_BestRegionsFirst::choose_collection_set() { +G1CollectorPolicy_BestRegionsFirst::choose_collection_set( + double target_pause_time_ms) { // Set this here - in case we're not doing young collections. double non_young_start_time_sec = os::elapsedTime(); @@ -2877,26 +2885,19 @@ G1CollectorPolicy_BestRegionsFirst::choose_collection_set() { start_recording_regions(); - guarantee(_target_pause_time_ms > -1.0 - NOT_PRODUCT(|| Universe::heap()->gc_cause() == GCCause::_scavenge_alot), - "_target_pause_time_ms should have been set!"); -#ifndef PRODUCT - if (_target_pause_time_ms <= -1.0) { - assert(ScavengeALot && Universe::heap()->gc_cause() == GCCause::_scavenge_alot, "Error"); - _target_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0; - } -#endif - assert(_collection_set == NULL, "Precondition"); + guarantee(target_pause_time_ms > 0.0, + err_msg("target_pause_time_ms = %1.6lf should be positive", + target_pause_time_ms)); + guarantee(_collection_set == NULL, "Precondition"); double base_time_ms = predict_base_elapsed_time_ms(_pending_cards); double predicted_pause_time_ms = base_time_ms; - double target_time_ms = _target_pause_time_ms; - double time_remaining_ms = target_time_ms - base_time_ms; + double time_remaining_ms = target_pause_time_ms - base_time_ms; // the 10% and 50% values are arbitrary... - if (time_remaining_ms < 0.10*target_time_ms) { - time_remaining_ms = 0.50 * target_time_ms; + if (time_remaining_ms < 0.10 * target_pause_time_ms) { + time_remaining_ms = 0.50 * target_pause_time_ms; _within_target = false; } else { _within_target = true; @@ -3059,7 +3060,18 @@ choose_collection_set_end: _recorded_non_young_cset_choice_time_ms = (non_young_end_time_sec - non_young_start_time_sec) * 1000.0; - return abandon_collection; + // Here we are supposed to return whether the pause should be + // abandoned or not (i.e., whether the collection set is empty or + // not). However, this introduces a subtle issue when a pause is + // initiated explicitly with System.gc() and + // +ExplicitGCInvokesConcurrent (see Comment #2 in CR 6944166), it's + // supposed to start a marking cycle, and it's abandoned. So, by + // returning false here we are telling the caller never to consider + // a pause to be abandoned. We'll actually remove all the code + // associated with abandoned pauses as part of CR 6963209, but we are + // just disabling them this way for the moment to avoid increasing + // further the amount of changes for CR 6944166. + return false; } void G1CollectorPolicy_BestRegionsFirst::record_full_collection_end() { diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp index b6f885d4534..61dbee6c09e 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp @@ -199,8 +199,6 @@ protected: size_t _young_cset_length; bool _last_young_gc_full; - double _target_pause_time_ms; - unsigned _full_young_pause_num; unsigned _partial_young_pause_num; @@ -526,6 +524,10 @@ public: return _mmu_tracker; } + double max_pause_time_ms() { + return _mmu_tracker->max_gc_time() * 1000.0; + } + double predict_init_time_ms() { return get_new_prediction(_concurrent_mark_init_times_ms); } @@ -1008,7 +1010,7 @@ public: // Choose a new collection set. Marks the chosen regions as being // "in_collection_set", and links them together. The head and number of // the collection set are available via access methods. - virtual bool choose_collection_set() = 0; + virtual bool choose_collection_set(double target_pause_time_ms) = 0; // The head of the list (via "next_in_collection_set()") representing the // current collection set. @@ -1077,6 +1079,12 @@ public: void set_during_initial_mark_pause() { _during_initial_mark_pause = true; } void clear_during_initial_mark_pause(){ _during_initial_mark_pause = false; } + // This sets the initiate_conc_mark_if_possible() flag to start a + // new cycle, as long as we are not already in one. It's best if it + // is called during a safepoint when the test whether a cycle is in + // progress or not is stable. + bool force_initial_mark_if_outside_cycle(); + // This is called at the very beginning of an evacuation pause (it // has to be the first thing that the pause does). If // initiate_conc_mark_if_possible() is true, and the concurrent @@ -1259,7 +1267,7 @@ class G1CollectorPolicy_BestRegionsFirst: public G1CollectorPolicy { // If the estimated is less then desirable, resize if possible. void expand_if_possible(size_t numRegions); - virtual bool choose_collection_set(); + virtual bool choose_collection_set(double target_pause_time_ms); virtual void record_collection_pause_start(double start_time_sec, size_t start_used); virtual void record_concurrent_mark_cleanup_end(size_t freed_bytes, diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp index 5de8d9e61f6..a3a77ed186b 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -676,9 +676,27 @@ void HRInto_G1RemSet::concurrentRefineOneCard_impl(jbyte* card_ptr, int worker_i // We must complete this write before we do any of the reads below. OrderAccess::storeload(); // And process it, being careful of unallocated portions of TLAB's. + + // The region for the current card may be a young region. The + // current card may have been a card that was evicted from the + // card cache. When the card was inserted into the cache, we had + // determined that its region was non-young. While in the cache, + // the region may have been freed during a cleanup pause, reallocated + // and tagged as young. + // + // We wish to filter out cards for such a region but the current + // thread, if we're running conucrrently, may "see" the young type + // change at any time (so an earlier "is_young" check may pass or + // fail arbitrarily). We tell the iteration code to perform this + // filtering when it has been determined that there has been an actual + // allocation in this region and making it safe to check the young type. + bool filter_young = true; + HeapWord* stop_point = r->oops_on_card_seq_iterate_careful(dirtyRegion, - &filter_then_update_rs_oop_cl); + &filter_then_update_rs_oop_cl, + filter_young); + // If stop_point is non-null, then we encountered an unallocated region // (perhaps the unfilled portion of a TLAB.) For now, we'll dirty the // card and re-enqueue: if we put off the card until a GC pause, then the @@ -789,8 +807,14 @@ void HRInto_G1RemSet::concurrentRefineOneCard(jbyte* card_ptr, int worker_i) { if (r == NULL) { assert(_g1->is_in_permanent(start), "Or else where?"); } else { - guarantee(!r->is_young(), "It was evicted in the current minor cycle."); - // Process card pointer we get back from the hot card cache + // Checking whether the region we got back from the cache + // is young here is inappropriate. The region could have been + // freed, reallocated and tagged as young while in the cache. + // Hence we could see its young type change at any time. + // + // Process card pointer we get back from the hot card cache. This + // will check whether the region containing the card is young + // _after_ checking that the region has been allocated from. concurrentRefineOneCard_impl(res, worker_i); } } diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp index 74541915ef3..4e5446e1f5e 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp @@ -658,7 +658,8 @@ HeapRegion::object_iterate_mem_careful(MemRegion mr, HeapWord* HeapRegion:: oops_on_card_seq_iterate_careful(MemRegion mr, - FilterOutOfRegionClosure* cl) { + FilterOutOfRegionClosure* cl, + bool filter_young) { G1CollectedHeap* g1h = G1CollectedHeap::heap(); // If we're within a stop-world GC, then we might look at a card in a @@ -672,6 +673,16 @@ oops_on_card_seq_iterate_careful(MemRegion mr, if (mr.is_empty()) return NULL; // Otherwise, find the obj that extends onto mr.start(). + // The intersection of the incoming mr (for the card) and the + // allocated part of the region is non-empty. This implies that + // we have actually allocated into this region. The code in + // G1CollectedHeap.cpp that allocates a new region sets the + // is_young tag on the region before allocating. Thus we + // safely know if this region is young. + if (is_young() && filter_young) { + return NULL; + } + // We used to use "block_start_careful" here. But we're actually happy // to update the BOT while we do this... HeapWord* cur = block_start(mr.start()); diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp index c8768c24267..42e96bbfb50 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp +++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.hpp @@ -252,7 +252,7 @@ class HeapRegion: public G1OffsetTableContigSpace { // survivor }; - YoungType _young_type; + volatile YoungType _young_type; int _young_index_in_cset; SurvRateGroup* _surv_rate_group; int _age_index; @@ -726,9 +726,12 @@ class HeapRegion: public G1OffsetTableContigSpace { HeapWord* object_iterate_mem_careful(MemRegion mr, ObjectClosure* cl); + // In this version - if filter_young is true and the region + // is a young region then we skip the iteration. HeapWord* oops_on_card_seq_iterate_careful(MemRegion mr, - FilterOutOfRegionClosure* cl); + FilterOutOfRegionClosure* cl, + bool filter_young); // The region "mr" is entirely in "this", and starts and ends at block // boundaries. The caller declares that all the contained blocks are diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.cpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.cpp index cbd325adc16..b71cf1918c9 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.cpp @@ -42,14 +42,19 @@ HeapRegionSeq::HeapRegionSeq(const size_t max_size) : // The line below is the worst bit of C++ hackery I've ever written // (Detlefs, 11/23). You should think of it as equivalent to // "_regions(100, true)": initialize the growable array and inform it - // that it should allocate its elem array(s) on the C heap. The first - // argument, however, is actually a comma expression (new-expr, 100). - // The purpose of the new_expr is to inform the growable array that it - // is *already* allocated on the C heap: it uses the placement syntax to - // keep it from actually doing any allocation. - _regions((ResourceObj::operator new (sizeof(GrowableArray), - (void*)&_regions, - ResourceObj::C_HEAP), + // that it should allocate its elem array(s) on the C heap. + // + // The first argument, however, is actually a comma expression + // (set_allocation_type(this, C_HEAP), 100). The purpose of the + // set_allocation_type() call is to replace the default allocation + // type for embedded objects STACK_OR_EMBEDDED with C_HEAP. It will + // allow to pass the assert in GenericGrowableArray() which checks + // that a growable array object must be on C heap if elements are. + // + // Note: containing object is allocated on C heap since it is CHeapObj. + // + _regions((ResourceObj::set_allocation_type((address)&_regions, + ResourceObj::C_HEAP), (int)max_size), true), _next_rr_candidate(0), diff --git a/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp b/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp index 02370cadc18..575e6781786 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.cpp @@ -42,8 +42,65 @@ void VM_G1CollectFull::doit() { void VM_G1IncCollectionPause::doit() { JvmtiGCForAllocationMarker jgcm; G1CollectedHeap* g1h = G1CollectedHeap::heap(); + assert(!_should_initiate_conc_mark || + ((_gc_cause == GCCause::_gc_locker && GCLockerInvokesConcurrent) || + (_gc_cause == GCCause::_java_lang_system_gc && ExplicitGCInvokesConcurrent)), + "only a GC locker or a System.gc() induced GC should start a cycle"); + GCCauseSetter x(g1h, _gc_cause); - g1h->do_collection_pause_at_safepoint(); + if (_should_initiate_conc_mark) { + // It's safer to read full_collections_completed() here, given + // that noone else will be updating it concurrently. Since we'll + // only need it if we're initiating a marking cycle, no point in + // setting it earlier. + _full_collections_completed_before = g1h->full_collections_completed(); + + // At this point we are supposed to start a concurrent cycle. We + // will do so if one is not already in progress. + bool res = g1h->g1_policy()->force_initial_mark_if_outside_cycle(); + } + g1h->do_collection_pause_at_safepoint(_target_pause_time_ms); +} + +void VM_G1IncCollectionPause::doit_epilogue() { + VM_GC_Operation::doit_epilogue(); + + // If the pause was initiated by a System.gc() and + // +ExplicitGCInvokesConcurrent, we have to wait here for the cycle + // that just started (or maybe one that was already in progress) to + // finish. + if (_gc_cause == GCCause::_java_lang_system_gc && + _should_initiate_conc_mark) { + assert(ExplicitGCInvokesConcurrent, + "the only way to be here is if ExplicitGCInvokesConcurrent is set"); + + G1CollectedHeap* g1h = G1CollectedHeap::heap(); + + // In the doit() method we saved g1h->full_collections_completed() + // in the _full_collections_completed_before field. We have to + // wait until we observe that g1h->full_collections_completed() + // has increased by at least one. This can happen if a) we started + // a cycle and it completes, b) a cycle already in progress + // completes, or c) a Full GC happens. + + // If the condition has already been reached, there's no point in + // actually taking the lock and doing the wait. + if (g1h->full_collections_completed() <= + _full_collections_completed_before) { + // The following is largely copied from CMS + + Thread* thr = Thread::current(); + assert(thr->is_Java_thread(), "invariant"); + JavaThread* jt = (JavaThread*)thr; + ThreadToNativeFromVM native(jt); + + MutexLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag); + while (g1h->full_collections_completed() <= + _full_collections_completed_before) { + FullGCCount_lock->wait(Mutex::_no_safepoint_check_flag); + } + } + } } void VM_CGC_Operation::doit() { diff --git a/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.hpp b/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.hpp index 3368c300eaf..d05beac9ea1 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.hpp +++ b/hotspot/src/share/vm/gc_implementation/g1/vm_operations_g1.hpp @@ -31,13 +31,12 @@ // - VM_G1PopRegionCollectionPause class VM_G1CollectFull: public VM_GC_Operation { - private: public: - VM_G1CollectFull(int gc_count_before, - GCCause::Cause gc_cause) - : VM_GC_Operation(gc_count_before) - { - _gc_cause = gc_cause; + VM_G1CollectFull(unsigned int gc_count_before, + unsigned int full_gc_count_before, + GCCause::Cause cause) + : VM_GC_Operation(gc_count_before, full_gc_count_before) { + _gc_cause = cause; } ~VM_G1CollectFull() {} virtual VMOp_Type type() const { return VMOp_G1CollectFull; } @@ -67,12 +66,28 @@ class VM_G1CollectForAllocation: public VM_GC_Operation { }; class VM_G1IncCollectionPause: public VM_GC_Operation { - public: - VM_G1IncCollectionPause(int gc_count_before, - GCCause::Cause gc_cause = GCCause::_g1_inc_collection_pause) : - VM_GC_Operation(gc_count_before) { _gc_cause = gc_cause; } +private: + bool _should_initiate_conc_mark; + double _target_pause_time_ms; + unsigned int _full_collections_completed_before; +public: + VM_G1IncCollectionPause(unsigned int gc_count_before, + bool should_initiate_conc_mark, + double target_pause_time_ms, + GCCause::Cause cause) + : VM_GC_Operation(gc_count_before), + _full_collections_completed_before(0), + _should_initiate_conc_mark(should_initiate_conc_mark), + _target_pause_time_ms(target_pause_time_ms) { + guarantee(target_pause_time_ms > 0.0, + err_msg("target_pause_time_ms = %1.6lf should be positive", + target_pause_time_ms)); + + _gc_cause = cause; + } virtual VMOp_Type type() const { return VMOp_G1IncCollectionPause; } virtual void doit(); + virtual void doit_epilogue(); virtual const char* name() const { return "garbage-first incremental collection pause"; } diff --git a/hotspot/src/share/vm/gc_implementation/includeDB_gc_g1 b/hotspot/src/share/vm/gc_implementation/includeDB_gc_g1 index dd271e1d1d8..13e3464ed8f 100644 --- a/hotspot/src/share/vm/gc_implementation/includeDB_gc_g1 +++ b/hotspot/src/share/vm/gc_implementation/includeDB_gc_g1 @@ -367,4 +367,6 @@ vm_operations_g1.hpp vmGCOperations.hpp vm_operations_g1.cpp vm_operations_g1.hpp vm_operations_g1.cpp g1CollectedHeap.inline.hpp +vm_operations_g1.cpp g1CollectorPolicy.hpp +vm_operations_g1.cpp interfaceSupport.hpp vm_operations_g1.cpp isGCActiveMark.hpp diff --git a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp index 250d244d25a..dc655aed136 100644 --- a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp +++ b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp @@ -539,10 +539,9 @@ ParNewGeneration(ReservedSpace rs, size_t initial_byte_size, int level) guarantee(_task_queues != NULL, "task_queues allocation failure."); for (uint i1 = 0; i1 < ParallelGCThreads; i1++) { - ObjToScanQueuePadded *q_padded = new ObjToScanQueuePadded(); - guarantee(q_padded != NULL, "work_queue Allocation failure."); - - _task_queues->register_queue(i1, &q_padded->work_queue); + ObjToScanQueue *q = new ObjToScanQueue(); + guarantee(q != NULL, "work_queue Allocation failure."); + _task_queues->register_queue(i1, q); } for (uint i2 = 0; i2 < ParallelGCThreads; i2++) diff --git a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.hpp b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.hpp index afbab7b99c5..8196e621372 100644 --- a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.hpp +++ b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -33,8 +33,8 @@ class ParEvacuateFollowersClosure; // but they must be here to allow ParScanClosure::do_oop_work to be defined // in genOopClosures.inline.hpp. -typedef OopTaskQueue ObjToScanQueue; -typedef OopTaskQueueSet ObjToScanQueueSet; +typedef Padded ObjToScanQueue; +typedef GenericTaskQueueSet ObjToScanQueueSet; // Enable this to get push/pop/steal stats. const int PAR_STATS_ENABLED = 0; @@ -304,12 +304,6 @@ class ParNewGeneration: public DefNewGeneration { friend class ParEvacuateFollowersClosure; private: - // XXX use a global constant instead of 64! - struct ObjToScanQueuePadded { - ObjToScanQueue work_queue; - char pad[64 - sizeof(ObjToScanQueue)]; // prevent false sharing - }; - // The per-worker-thread work queues ObjToScanQueueSet* _task_queues; diff --git a/hotspot/src/share/vm/gc_implementation/parNew/parOopClosures.hpp b/hotspot/src/share/vm/gc_implementation/parNew/parOopClosures.hpp index f261f31b752..c6a2543d0f5 100644 --- a/hotspot/src/share/vm/gc_implementation/parNew/parOopClosures.hpp +++ b/hotspot/src/share/vm/gc_implementation/parNew/parOopClosures.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -26,7 +26,8 @@ class ParScanThreadState; class ParNewGeneration; -typedef OopTaskQueueSet ObjToScanQueueSet; +typedef Padded ObjToScanQueue; +typedef GenericTaskQueueSet ObjToScanQueueSet; class ParallelTaskTerminator; class ParScanClosure: public OopsInGenClosure { diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.cpp index 8453ce9185e..2da32555dee 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.cpp @@ -90,10 +90,7 @@ void PSPromotionManager::pre_scavenge() { } void PSPromotionManager::post_scavenge() { -#if PS_PM_STATS - print_stats(); -#endif // PS_PM_STATS - + TASKQUEUE_STATS_ONLY(if (PrintGCDetails && ParallelGCVerbose) print_stats()); for (uint i = 0; i < ParallelGCThreads + 1; i++) { PSPromotionManager* manager = manager_array(i); if (UseDepthFirstScavengeOrder) { @@ -105,37 +102,58 @@ void PSPromotionManager::post_scavenge() { } } -#if PS_PM_STATS +#if TASKQUEUE_STATS +void +PSPromotionManager::print_taskqueue_stats(uint i) const { + const TaskQueueStats& stats = depth_first() ? + _claimed_stack_depth.stats : _claimed_stack_breadth.stats; + tty->print("%3u ", i); + stats.print(); + tty->cr(); +} void -PSPromotionManager::print_stats(uint i) { - tty->print_cr("---- GC Worker %2d Stats", i); - tty->print_cr(" total pushes %8d", _total_pushes); - tty->print_cr(" masked pushes %8d", _masked_pushes); - tty->print_cr(" overflow pushes %8d", _overflow_pushes); - tty->print_cr(" max overflow length %8d", _max_overflow_length); - tty->print_cr(""); - tty->print_cr(" arrays chunked %8d", _arrays_chunked); - tty->print_cr(" array chunks processed %8d", _array_chunks_processed); - tty->print_cr(""); - tty->print_cr(" total steals %8d", _total_steals); - tty->print_cr(" masked steals %8d", _masked_steals); - tty->print_cr(""); +PSPromotionManager::print_local_stats(uint i) const { + #define FMT " " SIZE_FORMAT_W(10) + tty->print_cr("%3u" FMT FMT FMT FMT, i, _masked_pushes, _masked_steals, + _arrays_chunked, _array_chunks_processed); + #undef FMT } +static const char* const pm_stats_hdr[] = { + " --------masked------- arrays array", + "thr push steal chunked chunks", + "--- ---------- ---------- ---------- ----------" +}; + void PSPromotionManager::print_stats() { - tty->print_cr("== GC Tasks Stats (%s), GC %3d", - (UseDepthFirstScavengeOrder) ? "Depth-First" : "Breadth-First", + const bool df = UseDepthFirstScavengeOrder; + tty->print_cr("== GC Task Stats (%s-First), GC %3d", df ? "Depth" : "Breadth", Universe::heap()->total_collections()); - for (uint i = 0; i < ParallelGCThreads+1; ++i) { - PSPromotionManager* manager = manager_array(i); - manager->print_stats(i); + tty->print("thr "); TaskQueueStats::print_header(1); tty->cr(); + tty->print("--- "); TaskQueueStats::print_header(2); tty->cr(); + for (uint i = 0; i < ParallelGCThreads + 1; ++i) { + manager_array(i)->print_taskqueue_stats(i); + } + + const uint hlines = sizeof(pm_stats_hdr) / sizeof(pm_stats_hdr[0]); + for (uint i = 0; i < hlines; ++i) tty->print_cr(pm_stats_hdr[i]); + for (uint i = 0; i < ParallelGCThreads + 1; ++i) { + manager_array(i)->print_local_stats(i); } } -#endif // PS_PM_STATS +void +PSPromotionManager::reset_stats() { + TaskQueueStats& stats = depth_first() ? + claimed_stack_depth()->stats : claimed_stack_breadth()->stats; + stats.reset(); + _masked_pushes = _masked_steals = 0; + _arrays_chunked = _array_chunks_processed = 0; +} +#endif // TASKQUEUE_STATS PSPromotionManager::PSPromotionManager() { ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); @@ -189,16 +207,7 @@ void PSPromotionManager::reset() { _prefetch_queue.clear(); -#if PS_PM_STATS - _total_pushes = 0; - _masked_pushes = 0; - _overflow_pushes = 0; - _max_overflow_length = 0; - _arrays_chunked = 0; - _array_chunks_processed = 0; - _total_steals = 0; - _masked_steals = 0; -#endif // PS_PM_STATS + TASKQUEUE_STATS_ONLY(reset_stats()); } @@ -423,14 +432,9 @@ oop PSPromotionManager::copy_to_survivor_space(oop o, bool depth_first) { new_obj->is_objArray() && PSChunkLargeArrays) { // we'll chunk it -#if PS_PM_STATS - ++_arrays_chunked; -#endif // PS_PM_STATS oop* const masked_o = mask_chunked_array_oop(o); push_depth(masked_o); -#if PS_PM_STATS - ++_masked_pushes; -#endif // PS_PM_STATS + TASKQUEUE_STATS_ONLY(++_arrays_chunked; ++_masked_pushes); } else { // we'll just push its contents new_obj->push_contents(this); @@ -494,9 +498,7 @@ void PSPromotionManager::process_array_chunk(oop old) { assert(old->is_objArray(), "invariant"); assert(old->is_forwarded(), "invariant"); -#if PS_PM_STATS - ++_array_chunks_processed; -#endif // PS_PM_STATS + TASKQUEUE_STATS_ONLY(++_array_chunks_processed); oop const obj = old->forwardee(); @@ -508,9 +510,7 @@ void PSPromotionManager::process_array_chunk(oop old) { assert(start > 0, "invariant"); arrayOop(old)->set_length(start); push_depth(mask_chunked_array_oop(old)); -#if PS_PM_STATS - ++_masked_pushes; -#endif // PS_PM_STATS + TASKQUEUE_STATS_ONLY(++_masked_pushes); } else { // this is the final chunk for this array start = 0; diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.hpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.hpp index 07694fc94ce..ec89b9557bb 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.hpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.hpp @@ -42,8 +42,6 @@ class MutableSpace; class PSOldGen; class ParCompactionManager; -#define PS_PM_STATS 0 - class PSPromotionManager : public CHeapObj { friend class PSScavenge; friend class PSRefProcTaskExecutor; @@ -54,22 +52,18 @@ class PSPromotionManager : public CHeapObj { static PSOldGen* _old_gen; static MutableSpace* _young_space; -#if PS_PM_STATS - uint _total_pushes; - uint _masked_pushes; +#if TASKQUEUE_STATS + size_t _masked_pushes; + size_t _masked_steals; + size_t _arrays_chunked; + size_t _array_chunks_processed; - uint _overflow_pushes; - uint _max_overflow_length; - - uint _arrays_chunked; - uint _array_chunks_processed; - - uint _total_steals; - uint _masked_steals; - - void print_stats(uint i); + void print_taskqueue_stats(uint i) const; + void print_local_stats(uint i) const; static void print_stats(); -#endif // PS_PM_STATS + + void reset_stats(); +#endif // TASKQUEUE_STATS PSYoungPromotionLAB _young_lab; PSOldPromotionLAB _old_lab; @@ -143,42 +137,12 @@ class PSPromotionManager : public CHeapObj { template void push_depth(T* p) { assert(depth_first(), "pre-condition"); - -#if PS_PM_STATS - ++_total_pushes; - int stack_length = claimed_stack_depth()->overflow_stack()->length(); -#endif // PS_PM_STATS - claimed_stack_depth()->push(p); - -#if PS_PM_STATS - if (claimed_stack_depth()->overflow_stack()->length() != stack_length) { - ++_overflow_pushes; - if ((uint)stack_length + 1 > _max_overflow_length) { - _max_overflow_length = (uint)stack_length + 1; - } - } -#endif // PS_PM_STATS } void push_breadth(oop o) { assert(!depth_first(), "pre-condition"); - -#if PS_PM_STATS - ++_total_pushes; - int stack_length = claimed_stack_breadth()->overflow_stack()->length(); -#endif // PS_PM_STATS - claimed_stack_breadth()->push(o); - -#if PS_PM_STATS - if (claimed_stack_breadth()->overflow_stack()->length() != stack_length) { - ++_overflow_pushes; - if ((uint)stack_length + 1 > _max_overflow_length) { - _max_overflow_length = (uint)stack_length + 1; - } - } -#endif // PS_PM_STATS } protected: @@ -256,12 +220,5 @@ class PSPromotionManager : public CHeapObj { template inline void claim_or_forward_depth(T* p); template inline void claim_or_forward_breadth(T* p); -#if PS_PM_STATS - void increment_steals(oop* p = NULL) { - _total_steals += 1; - if (p != NULL && is_oop_masked(p)) { - _masked_steals += 1; - } - } -#endif // PS_PM_STATS + TASKQUEUE_STATS_ONLY(inline void record_steal(StarTask& p);) }; diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.inline.hpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.inline.hpp index 213f6261401..ea81c817b30 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.inline.hpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.inline.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -124,3 +124,11 @@ inline void PSPromotionManager::process_popped_location_depth(StarTask p) { } } } + +#if TASKQUEUE_STATS +void PSPromotionManager::record_steal(StarTask& p) { + if (is_oop_masked(p)) { + ++_masked_steals; + } +} +#endif // TASKQUEUE_STATS diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psTasks.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psTasks.cpp index bbff68c6b2c..6f72724bfda 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psTasks.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psTasks.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -148,9 +148,7 @@ void StealTask::do_it(GCTaskManager* manager, uint which) { while(true) { StarTask p; if (PSPromotionManager::steal_depth(which, &random_seed, p)) { -#if PS_PM_STATS - pm->increment_steals(p); -#endif // PS_PM_STATS + TASKQUEUE_STATS_ONLY(pm->record_steal(p)); pm->process_popped_location_depth(p); pm->drain_stacks_depth(true); } else { @@ -163,9 +161,6 @@ void StealTask::do_it(GCTaskManager* manager, uint which) { while(true) { oop obj; if (PSPromotionManager::steal_breadth(which, &random_seed, obj)) { -#if PS_PM_STATS - pm->increment_steals(); -#endif // PS_PM_STATS obj->copy_contents(pm); pm->drain_stacks_breadth(true); } else { diff --git a/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.hpp b/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.hpp index d70d78ab92f..b3a202902a5 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.hpp +++ b/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.hpp @@ -86,9 +86,7 @@ class VM_GC_Operation: public VM_Operation { _gc_locked = false; - if (full) { - _full_gc_count_before = full_gc_count_before; - } + _full_gc_count_before = full_gc_count_before; // In ParallelScavengeHeap::mem_allocate() collections can be // executed within a loop and _all_soft_refs_clear can be set // true after they have been cleared by a collection and another diff --git a/hotspot/src/share/vm/gc_interface/gcCause.cpp b/hotspot/src/share/vm/gc_interface/gcCause.cpp index 19822c92777..e96f55a86ee 100644 --- a/hotspot/src/share/vm/gc_interface/gcCause.cpp +++ b/hotspot/src/share/vm/gc_interface/gcCause.cpp @@ -78,6 +78,9 @@ const char* GCCause::to_string(GCCause::Cause cause) { case _old_generation_too_full_to_scavenge: return "Old Generation Too Full To Scavenge"; + case _g1_inc_collection_pause: + return "G1 Evacuation Pause"; + case _last_ditch_collection: return "Last ditch collection"; diff --git a/hotspot/src/share/vm/includeDB_compiler1 b/hotspot/src/share/vm/includeDB_compiler1 index 302bcc59600..bdfea08070c 100644 --- a/hotspot/src/share/vm/includeDB_compiler1 +++ b/hotspot/src/share/vm/includeDB_compiler1 @@ -252,6 +252,7 @@ c1_LIRGenerator.cpp ciCPCache.hpp c1_LIRGenerator.cpp ciInstance.hpp c1_LIRGenerator.cpp heapRegion.hpp c1_LIRGenerator.cpp sharedRuntime.hpp +c1_LIRGenerator.cpp stubRoutines.hpp c1_LIRGenerator.hpp c1_Instruction.hpp c1_LIRGenerator.hpp c1_LIR.hpp @@ -270,6 +271,8 @@ c1_LIRGenerator_.cpp ciObjArrayKlass.hpp c1_LIRGenerator_.cpp ciTypeArrayKlass.hpp c1_LIRGenerator_.cpp sharedRuntime.hpp c1_LIRGenerator_.cpp vmreg_.inline.hpp +c1_LIRGenerator_.cpp stubRoutines.hpp + c1_LinearScan.cpp bitMap.inline.hpp c1_LinearScan.cpp c1_CFGPrinter.hpp @@ -413,6 +416,7 @@ codeBlob.cpp c1_Runtime1.hpp compileBroker.cpp c1_Compiler.hpp frame_.cpp c1_Runtime1.hpp +frame_.cpp vframeArray.hpp globals.cpp c1_globals.hpp diff --git a/hotspot/src/share/vm/includeDB_compiler2 b/hotspot/src/share/vm/includeDB_compiler2 index a7695d75c56..33bb7152cda 100644 --- a/hotspot/src/share/vm/includeDB_compiler2 +++ b/hotspot/src/share/vm/includeDB_compiler2 @@ -911,6 +911,7 @@ postaloc.cpp machnode.hpp reg_split.cpp addnode.hpp reg_split.cpp allocation.inline.hpp reg_split.cpp callnode.hpp +reg_split.cpp c2compiler.hpp reg_split.cpp cfgnode.hpp reg_split.cpp chaitin.hpp reg_split.cpp loopnode.hpp diff --git a/hotspot/src/share/vm/includeDB_core b/hotspot/src/share/vm/includeDB_core index 3e9089f24a8..fe4252dfcfd 100644 --- a/hotspot/src/share/vm/includeDB_core +++ b/hotspot/src/share/vm/includeDB_core @@ -284,6 +284,7 @@ atomic.hpp allocation.hpp atomic_.inline.hpp atomic.hpp atomic_.inline.hpp os.hpp atomic_.inline.hpp vm_version_.hpp +atomic_.inline.hpp orderAccess_.inline.hpp // attachListener is jck optional, put cpp deps in includeDB_features @@ -1734,6 +1735,7 @@ genCollectedHeap.cpp sharedHeap.hpp genCollectedHeap.cpp space.hpp genCollectedHeap.cpp symbolTable.hpp genCollectedHeap.cpp systemDictionary.hpp +genCollectedHeap.cpp vmError.hpp genCollectedHeap.cpp vmGCOperations.hpp genCollectedHeap.cpp vmSymbols.hpp genCollectedHeap.cpp vmThread.hpp @@ -3230,6 +3232,7 @@ os.cpp defaultStream.hpp os.cpp events.hpp os.cpp frame.inline.hpp os.cpp hpi.hpp +os.cpp icBuffer.hpp os.cpp interfaceSupport.hpp os.cpp interpreter.hpp os.cpp java.hpp @@ -3241,6 +3244,7 @@ os.cpp mutexLocker.hpp os.cpp oop.inline.hpp os.cpp os.hpp os.cpp os_.inline.hpp +os.cpp privilegedStack.hpp os.cpp stubRoutines.hpp os.cpp systemDictionary.hpp os.cpp threadService.hpp diff --git a/hotspot/src/share/vm/includeDB_shark b/hotspot/src/share/vm/includeDB_shark new file mode 100644 index 00000000000..17e451daecd --- /dev/null +++ b/hotspot/src/share/vm/includeDB_shark @@ -0,0 +1,371 @@ +// +// Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. +// Copyright 2008, 2009, 2010 Red Hat, Inc. +// 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. +// +// + +// NOTE: DO NOT CHANGE THIS COPYRIGHT TO NEW STYLE - IT WILL BREAK makeDeps! + +ciMethod.cpp ciTypeFlow.hpp +ciMethod.cpp methodOop.hpp + +ciTypeFlow.cpp allocation.inline.hpp +ciTypeFlow.cpp bytecode.hpp +ciTypeFlow.cpp bytecodes.hpp +ciTypeFlow.cpp ciConstant.hpp +ciTypeFlow.cpp ciField.hpp +ciTypeFlow.cpp ciMethod.hpp +ciTypeFlow.cpp ciMethodData.hpp +ciTypeFlow.cpp ciObjArrayKlass.hpp +ciTypeFlow.cpp ciStreams.hpp +ciTypeFlow.cpp ciTypeArrayKlass.hpp +ciTypeFlow.cpp ciTypeFlow.hpp +ciTypeFlow.cpp compileLog.hpp +ciTypeFlow.cpp deoptimization.hpp +ciTypeFlow.cpp growableArray.hpp +ciTypeFlow.cpp shark_globals.hpp + +ciTypeFlow.hpp ciEnv.hpp +ciTypeFlow.hpp ciKlass.hpp +ciTypeFlow.hpp ciMethodBlocks.hpp + +cppInterpreter_.cpp shark_globals.hpp + +compileBroker.cpp sharkCompiler.hpp + +disassembler.cpp sharkEntry.hpp + +globals.hpp shark_globals_.hpp + +globals.cpp shark_globals.hpp + +llvmValue.hpp llvmHeaders.hpp +llvmValue.hpp sharkContext.hpp +llvmValue.hpp sharkType.hpp + +nmethod.cpp sharkCompiler.hpp + +sharedRuntime_.cpp compileBroker.hpp +sharedRuntime_.cpp sharkCompiler.hpp + +shark_globals.cpp shark_globals.hpp + +shark_globals.hpp shark_globals_.hpp +shark_globals.hpp globals.hpp + +sharkBlock.cpp debug.hpp +sharkBlock.cpp bytecodes.hpp +sharkBlock.cpp llvmHeaders.hpp +sharkBlock.cpp llvmValue.hpp +sharkBlock.cpp shark_globals.hpp +sharkBlock.cpp sharkBlock.hpp +sharkBlock.cpp sharkBuilder.hpp +sharkBlock.cpp sharkConstant.hpp +sharkBlock.cpp sharkState.hpp +sharkBlock.cpp sharkValue.hpp + +sharkBlock.hpp allocation.hpp +sharkBlock.hpp ciMethod.hpp +sharkBlock.hpp ciStreams.hpp +sharkBlock.hpp debug.hpp +sharkBlock.hpp llvmHeaders.hpp +sharkBlock.hpp sharkBuilder.hpp +sharkBlock.hpp sharkConstant.hpp +sharkBlock.hpp sharkInvariants.hpp +sharkBlock.hpp sharkState.hpp +sharkBlock.hpp sharkValue.hpp + +sharkBuilder.cpp ciMethod.hpp +sharkBuilder.cpp debug.hpp +sharkBuilder.cpp llvmHeaders.hpp +sharkBuilder.cpp llvmValue.hpp +sharkBuilder.cpp methodOop.hpp +sharkBuilder.cpp os.hpp +sharkBuilder.cpp resourceArea.hpp +sharkBuilder.cpp llvmHeaders.hpp +sharkBuilder.cpp sharkBuilder.hpp +sharkBuilder.cpp sharkContext.hpp +sharkBuilder.cpp sharkRuntime.hpp +sharkBuilder.cpp synchronizer.hpp +sharkBuilder.cpp thread.hpp + +sharkBuilder.hpp barrierSet.hpp +sharkBuilder.hpp cardTableModRefBS.hpp +sharkBuilder.hpp ciType.hpp +sharkBuilder.hpp debug.hpp +sharkBuilder.hpp llvmHeaders.hpp +sharkBuilder.hpp llvmValue.hpp +sharkBuilder.hpp sizes.hpp +sharkBuilder.hpp sharkCodeBuffer.hpp +sharkBuilder.hpp sharkType.hpp +sharkBuilder.hpp sharkValue.hpp +sharkBuilder.hpp sharkEntry.hpp + +sharkCacheDecache.cpp ciMethod.hpp +sharkCacheDecache.cpp debugInfoRec.hpp +sharkCacheDecache.cpp llvmValue.hpp +sharkCacheDecache.cpp sharkBuilder.hpp +sharkCacheDecache.cpp sharkCacheDecache.hpp +sharkCacheDecache.cpp sharkFunction.hpp +sharkCacheDecache.cpp sharkState.hpp + +sharkCacheDecache.hpp ciMethod.hpp +sharkCacheDecache.hpp debugInfoRec.hpp +sharkCacheDecache.hpp sharkBuilder.hpp +sharkCacheDecache.hpp sharkFunction.hpp +sharkCacheDecache.hpp sharkStateScanner.hpp + +sharkCodeBuffer.hpp allocation.hpp +sharkCodeBuffer.hpp codeBuffer.hpp +sharkCodeBuffer.hpp llvmHeaders.hpp + +sharkCompiler.cpp abstractCompiler.hpp +sharkCompiler.cpp ciEnv.hpp +sharkCompiler.cpp ciMethod.hpp +sharkCompiler.cpp debug.hpp +sharkCompiler.cpp debugInfoRec.hpp +sharkCompiler.cpp dependencies.hpp +sharkCompiler.cpp exceptionHandlerTable.hpp +sharkCompiler.cpp llvmHeaders.hpp +sharkCompiler.cpp oopMap.hpp +sharkCompiler.cpp oopRecorder.hpp +sharkCompiler.cpp shark_globals.hpp +sharkCompiler.cpp sharkBuilder.hpp +sharkCompiler.cpp sharkCodeBuffer.hpp +sharkCompiler.cpp sharkCompiler.hpp +sharkCompiler.cpp sharkContext.hpp +sharkCompiler.cpp sharkEntry.hpp +sharkCompiler.cpp sharkFunction.hpp +sharkCompiler.cpp sharkMemoryManager.hpp +sharkCompiler.cpp sharkNativeWrapper.hpp + +sharkCompiler.hpp abstractCompiler.hpp +sharkCompiler.hpp ciEnv.hpp +sharkCompiler.hpp ciMethod.hpp +sharkCompiler.hpp compileBroker.hpp +sharkCompiler.hpp llvmHeaders.hpp +sharkCompiler.hpp sharkMemoryManager.hpp + +sharkContext.cpp arrayOop.hpp +sharkContext.cpp globalDefinitions.hpp +sharkContext.cpp llvmHeaders.hpp +sharkContext.cpp oop.hpp +sharkContext.cpp sharkContext.hpp + +sharkContext.hpp llvmHeaders.hpp +sharkContext.hpp sharkCompiler.hpp + +sharkConstant.cpp ciInstance.hpp +sharkConstant.cpp ciStreams.hpp +sharkConstant.cpp sharkBuilder.hpp +sharkConstant.cpp sharkConstant.hpp +sharkConstant.cpp sharkValue.hpp + +sharkConstant.hpp allocation.hpp +sharkConstant.hpp ciStreams.hpp +sharkConstant.hpp sharkBuilder.hpp +sharkConstant.hpp sharkValue.hpp + +sharkEntry.hpp llvmHeaders.hpp + +sharkFunction.cpp allocation.hpp +sharkFunction.cpp ciTypeFlow.hpp +sharkFunction.cpp debug.hpp +sharkFunction.cpp llvmHeaders.hpp +sharkFunction.cpp llvmValue.hpp +sharkFunction.cpp shark_globals.hpp +sharkFunction.cpp sharkBuilder.hpp +sharkFunction.cpp sharkEntry.hpp +sharkFunction.cpp sharkFunction.hpp +sharkFunction.cpp sharkState.hpp +sharkFunction.cpp sharkTopLevelBlock.hpp + +sharkFunction.hpp allocation.hpp +sharkFunction.hpp ciEnv.hpp +sharkFunction.hpp ciStreams.hpp +sharkFunction.hpp ciTypeFlow.hpp +sharkFunction.hpp llvmHeaders.hpp +sharkFunction.hpp llvmValue.hpp +sharkFunction.hpp sharkBuilder.hpp +sharkFunction.hpp sharkContext.hpp +sharkFunction.hpp sharkInvariants.hpp +sharkFunction.hpp sharkStack.hpp + +sharkInliner.cpp allocation.hpp +sharkInliner.cpp bytecodes.hpp +sharkInliner.cpp ciField.hpp +sharkInliner.cpp ciMethod.hpp +sharkInliner.cpp ciStreams.hpp +sharkInliner.cpp shark_globals.hpp +sharkInliner.cpp sharkBlock.hpp +sharkInliner.cpp sharkConstant.hpp +sharkInliner.cpp sharkInliner.hpp +sharkInliner.cpp sharkIntrinsics.hpp +sharkInliner.cpp sharkState.hpp +sharkInliner.cpp sharkValue.hpp + +sharkInliner.hpp allocation.hpp +sharkInliner.hpp ciMethod.hpp +sharkInliner.hpp llvmHeaders.hpp +sharkInliner.hpp sharkState.hpp + +sharkIntrinsics.cpp ciMethod.hpp +sharkIntrinsics.cpp llvmHeaders.hpp +sharkIntrinsics.cpp shark_globals.hpp +sharkIntrinsics.cpp sharkIntrinsics.hpp +sharkIntrinsics.cpp sharkState.hpp +sharkIntrinsics.cpp sharkValue.hpp + +sharkIntrinsics.hpp allocation.hpp +sharkIntrinsics.hpp ciMethod.hpp +sharkIntrinsics.hpp llvmHeaders.hpp +sharkIntrinsics.hpp sharkState.hpp + +sharkInvariants.cpp sharkInvariants.hpp + +sharkInvariants.hpp allocation.hpp +sharkInvariants.hpp ciEnv.hpp +sharkInvariants.hpp ciMethod.hpp +sharkInvariants.hpp ciInstanceKlass.hpp +sharkInvariants.hpp ciTypeFlow.hpp +sharkInvariants.hpp debugInfoRec.hpp +sharkInvariants.hpp dependencies.hpp +sharkInvariants.hpp llvmHeaders.hpp +sharkInvariants.hpp sharkBuilder.hpp + +sharkMemoryManager.hpp llvmHeaders.hpp +sharkMemoryManager.hpp sharkEntry.hpp + +sharkMemoryManager.cpp llvmHeaders.hpp +sharkMemoryManager.cpp sharkEntry.hpp +sharkMemoryManager.cpp sharkMemoryManager.hpp + +sharkNativeWrapper.cpp llvmHeaders.hpp +sharkNativeWrapper.cpp sharkNativeWrapper.hpp +sharkNativeWrapper.cpp sharkType.hpp + +sharkNativeWrapper.hpp handles.hpp +sharkNativeWrapper.hpp llvmHeaders.hpp +sharkNativeWrapper.hpp sharkBuilder.hpp +sharkNativeWrapper.hpp sharkContext.hpp +sharkNativeWrapper.hpp sharkInvariants.hpp +sharkNativeWrapper.hpp sharkStack.hpp + +sharkRuntime.cpp biasedLocking.hpp +sharkRuntime.cpp deoptimization.hpp +sharkRuntime.cpp llvmHeaders.hpp +sharkRuntime.cpp klassOop.hpp +sharkRuntime.cpp sharkRuntime.hpp +sharkRuntime.cpp stack_.inline.hpp +sharkRuntime.cpp thread.hpp + +sharkRuntime.hpp allocation.hpp +sharkRuntime.hpp llvmHeaders.hpp +sharkRuntime.hpp llvmValue.hpp +sharkRuntime.hpp klassOop.hpp +sharkRuntime.hpp thread.hpp + +sharkStack.cpp llvmHeaders.hpp +sharkStack.cpp sharkFunction.hpp +sharkStack.cpp sharkNativeWrapper.hpp +sharkStack.cpp sharkStack.hpp +sharkStack.cpp sharkType.hpp + +sharkStack.hpp llvmHeaders.hpp +sharkStack.hpp sharkInvariants.hpp +sharkStack.hpp sharkType.hpp + +sharkState.cpp allocation.hpp +sharkState.cpp ciType.hpp +sharkState.cpp ciTypeFlow.hpp +sharkState.cpp sharkBuilder.hpp +sharkState.cpp sharkCacheDecache.hpp +sharkState.cpp sharkState.hpp +sharkState.cpp sharkTopLevelBlock.hpp +sharkState.cpp sharkType.hpp +sharkState.cpp sharkValue.hpp + +sharkState.hpp allocation.hpp +sharkState.hpp ciMethod.hpp +sharkState.hpp llvmHeaders.hpp +sharkState.hpp sharkBuilder.hpp +sharkState.hpp sharkInvariants.hpp +sharkState.hpp sharkValue.hpp + +sharkStateScanner.cpp sharkState.hpp +sharkStateScanner.cpp sharkStateScanner.hpp + +sharkStateScanner.hpp allocation.hpp +sharkStateScanner.hpp llvmHeaders.hpp +sharkStateScanner.hpp sharkFunction.hpp +sharkStateScanner.hpp sharkInvariants.hpp + +sharkTopLevelBlock.cpp allocation.hpp +sharkTopLevelBlock.cpp bytecodes.hpp +sharkTopLevelBlock.cpp ciField.hpp +sharkTopLevelBlock.cpp ciInstance.hpp +sharkTopLevelBlock.cpp ciObjArrayKlass.hpp +sharkTopLevelBlock.cpp ciStreams.hpp +sharkTopLevelBlock.cpp ciType.hpp +sharkTopLevelBlock.cpp ciTypeFlow.hpp +sharkTopLevelBlock.cpp debug.hpp +sharkTopLevelBlock.cpp deoptimization.hpp +sharkTopLevelBlock.cpp llvmHeaders.hpp +sharkTopLevelBlock.cpp llvmValue.hpp +sharkTopLevelBlock.cpp shark_globals.hpp +sharkTopLevelBlock.cpp sharkCacheDecache.hpp +sharkTopLevelBlock.cpp sharkTopLevelBlock.hpp +sharkTopLevelBlock.cpp sharkBuilder.hpp +sharkTopLevelBlock.cpp sharkConstant.hpp +sharkTopLevelBlock.cpp sharkInliner.hpp +sharkTopLevelBlock.cpp sharkState.hpp +sharkTopLevelBlock.cpp sharkValue.hpp + +sharkTopLevelBlock.hpp allocation.hpp +sharkTopLevelBlock.hpp bytecodes.hpp +sharkTopLevelBlock.hpp ciStreams.hpp +sharkTopLevelBlock.hpp ciType.hpp +sharkTopLevelBlock.hpp ciTypeFlow.hpp +sharkTopLevelBlock.hpp llvmHeaders.hpp +sharkTopLevelBlock.hpp sharkBlock.hpp +sharkTopLevelBlock.hpp sharkBuilder.hpp +sharkTopLevelBlock.hpp sharkFunction.hpp +sharkTopLevelBlock.hpp sharkState.hpp +sharkTopLevelBlock.hpp sharkValue.hpp + +sharkType.hpp allocation.hpp +sharkType.hpp ciType.hpp +sharkType.hpp globalDefinitions.hpp +sharkType.hpp llvmHeaders.hpp +sharkType.hpp sharkContext.hpp + +sharkValue.cpp ciType.hpp +sharkValue.cpp llvmHeaders.hpp +sharkValue.cpp llvmValue.hpp +sharkValue.cpp sharkBuilder.hpp +sharkValue.cpp sharkValue.hpp + +sharkValue.hpp allocation.hpp +sharkValue.hpp ciType.hpp +sharkValue.hpp llvmHeaders.hpp +sharkValue.hpp llvmValue.hpp +sharkValue.hpp sharkType.hpp diff --git a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp index a9d0d0484f7..29b4ede2bd9 100644 --- a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp +++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp @@ -339,7 +339,8 @@ #define CHECK_NULL(obj_) \ if ((obj_) == NULL) { \ VM_JAVA_ERROR(vmSymbols::java_lang_NullPointerException(), ""); \ - } + } \ + VERIFY_OOP(obj_) #define VMdoubleConstZero() 0.0 #define VMdoubleConstOne() 1.0 @@ -509,7 +510,7 @@ BytecodeInterpreter::run(interpreterState istate) { /* 0xB0 */ &&opc_areturn, &&opc_return, &&opc_getstatic, &&opc_putstatic, /* 0xB4 */ &&opc_getfield, &&opc_putfield, &&opc_invokevirtual,&&opc_invokespecial, -/* 0xB8 */ &&opc_invokestatic,&&opc_invokeinterface,NULL, &&opc_new, +/* 0xB8 */ &&opc_invokestatic,&&opc_invokeinterface,&&opc_default, &&opc_new, /* 0xBC */ &&opc_newarray, &&opc_anewarray, &&opc_arraylength, &&opc_athrow, /* 0xC0 */ &&opc_checkcast, &&opc_instanceof, &&opc_monitorenter, &&opc_monitorexit, @@ -539,6 +540,7 @@ BytecodeInterpreter::run(interpreterState istate) { // this will trigger a VERIFY_OOP on entry if (istate->msg() != initialize && ! METHOD->is_static()) { oop rcvr = LOCALS_OBJECT(0); + VERIFY_OOP(rcvr); } #endif // #define HACK @@ -547,7 +549,7 @@ BytecodeInterpreter::run(interpreterState istate) { #endif // HACK /* QQQ this should be a stack method so we don't know actual direction */ - assert(istate->msg() == initialize || + guarantee(istate->msg() == initialize || topOfStack >= istate->stack_limit() && topOfStack < istate->stack_base(), "Stack top out of range"); @@ -613,6 +615,7 @@ BytecodeInterpreter::run(interpreterState istate) { rcvr = METHOD->constants()->pool_holder()->klass_part()->java_mirror(); } else { rcvr = LOCALS_OBJECT(0); + VERIFY_OOP(rcvr); } // The initial monitor is ours for the taking BasicObjectLock* mon = &istate->monitor_base()[-1]; @@ -735,6 +738,7 @@ BytecodeInterpreter::run(interpreterState istate) { case popping_frame: { // returned from a java call to pop the frame, restart the call // clear the message so we don't confuse ourselves later + ShouldNotReachHere(); // we don't return this. assert(THREAD->pop_frame_in_process(), "wrong frame pop state"); istate->set_msg(no_request); THREAD->clr_pop_frame_in_process(); @@ -801,6 +805,7 @@ BytecodeInterpreter::run(interpreterState istate) { // continue locking now that we have a monitor to use // we expect to find newly allocated monitor at the "top" of the monitor stack. oop lockee = STACK_OBJECT(-1); + VERIFY_OOP(lockee); // derefing's lockee ought to provoke implicit null check // find a free monitor BasicObjectLock* entry = (BasicObjectLock*) istate->stack_base(); @@ -911,6 +916,7 @@ run: /* load from local variable */ CASE(_aload): + VERIFY_OOP(LOCALS_OBJECT(pc[1])); SET_STACK_OBJECT(LOCALS_OBJECT(pc[1]), 0); UPDATE_PC_AND_TOS_AND_CONTINUE(2, 1); @@ -930,6 +936,7 @@ run: #undef OPC_LOAD_n #define OPC_LOAD_n(num) \ CASE(_aload_##num): \ + VERIFY_OOP(LOCALS_OBJECT(num)); \ SET_STACK_OBJECT(LOCALS_OBJECT(num), 0); \ UPDATE_PC_AND_TOS_AND_CONTINUE(1, 1); \ \ @@ -975,6 +982,7 @@ run: opcode = pc[1]; switch(opcode) { case Bytecodes::_aload: + VERIFY_OOP(LOCALS_OBJECT(reg)); SET_STACK_OBJECT(LOCALS_OBJECT(reg), 0); UPDATE_PC_AND_TOS_AND_CONTINUE(4, 1); @@ -1099,7 +1107,7 @@ run: CASE(_i##opcname): \ if (test && (STACK_INT(-1) == 0)) { \ VM_JAVA_ERROR(vmSymbols::java_lang_ArithmeticException(), \ - "/ by int zero"); \ + "/ by zero"); \ } \ SET_STACK_INT(VMint##opname(STACK_INT(-2), \ STACK_INT(-1)), \ @@ -1277,7 +1285,12 @@ run: jfloat f; jdouble r; f = STACK_FLOAT(-1); +#ifdef IA64 + // IA64 gcc bug + r = ( f == 0.0f ) ? (jdouble) f : (jdouble) f + ia64_double_zero; +#else r = (jdouble) f; +#endif MORE_STACK(-1); // POP SET_STACK_DOUBLE(r, 1); UPDATE_PC_AND_TOS_AND_CONTINUE(1, 2); @@ -1471,6 +1484,7 @@ run: CASE(_return_register_finalizer): { oop rcvr = LOCALS_OBJECT(0); + VERIFY_OOP(rcvr); if (rcvr->klass()->klass_part()->has_finalizer()) { CALL_VM(InterpreterRuntime::register_finalizer(THREAD, rcvr), handle_exception); } @@ -1561,6 +1575,7 @@ run: */ CASE(_aastore): { oop rhsObject = STACK_OBJECT(-1); + VERIFY_OOP(rhsObject); ARRAY_INTRO( -3); // arrObj, index are set if (rhsObject != NULL) { @@ -1703,6 +1718,7 @@ run: obj = (oop)NULL; } else { obj = (oop) STACK_OBJECT(-1); + VERIFY_OOP(obj); } CALL_VM(InterpreterRuntime::post_field_access(THREAD, obj, @@ -1728,6 +1744,7 @@ run: int field_offset = cache->f2(); if (cache->is_volatile()) { if (tos_type == atos) { + VERIFY_OOP(obj->obj_field_acquire(field_offset)); SET_STACK_OBJECT(obj->obj_field_acquire(field_offset), -1); } else if (tos_type == itos) { SET_STACK_INT(obj->int_field_acquire(field_offset), -1); @@ -1748,6 +1765,7 @@ run: } } else { if (tos_type == atos) { + VERIFY_OOP(obj->obj_field(field_offset)); SET_STACK_OBJECT(obj->obj_field(field_offset), -1); } else if (tos_type == itos) { SET_STACK_INT(obj->int_field(field_offset), -1); @@ -1799,6 +1817,7 @@ run: } else { obj = (oop) STACK_OBJECT(-2); } + VERIFY_OOP(obj); } CALL_VM(InterpreterRuntime::post_field_modification(THREAD, @@ -1837,6 +1856,7 @@ run: if (tos_type == itos) { obj->release_int_field_put(field_offset, STACK_INT(-1)); } else if (tos_type == atos) { + VERIFY_OOP(STACK_OBJECT(-1)); obj->release_obj_field_put(field_offset, STACK_OBJECT(-1)); OrderAccess::release_store(&BYTE_MAP_BASE[(uintptr_t)obj >> CardTableModRefBS::card_shift], 0); } else if (tos_type == btos) { @@ -1857,6 +1877,7 @@ run: if (tos_type == itos) { obj->int_field_put(field_offset, STACK_INT(-1)); } else if (tos_type == atos) { + VERIFY_OOP(STACK_OBJECT(-1)); obj->obj_field_put(field_offset, STACK_OBJECT(-1)); OrderAccess::release_store(&BYTE_MAP_BASE[(uintptr_t)obj >> CardTableModRefBS::card_shift], 0); } else if (tos_type == btos) { @@ -1961,6 +1982,7 @@ run: } CASE(_checkcast): if (STACK_OBJECT(-1) != NULL) { + VERIFY_OOP(STACK_OBJECT(-1)); u2 index = Bytes::get_Java_u2(pc+1); if (ProfileInterpreter) { // needs Profile_checkcast QQQ @@ -1999,6 +2021,7 @@ run: if (STACK_OBJECT(-1) == NULL) { SET_STACK_INT(0, -1); } else { + VERIFY_OOP(STACK_OBJECT(-1)); u2 index = Bytes::get_Java_u2(pc+1); // Constant pool may have actual klass or unresolved klass. If it is // unresolved we must resolve it @@ -2044,10 +2067,12 @@ run: break; case JVM_CONSTANT_String: + VERIFY_OOP(constants->resolved_string_at(index)); SET_STACK_OBJECT(constants->resolved_string_at(index), 0); break; case JVM_CONSTANT_Class: + VERIFY_OOP(constants->resolved_klass_at(index)->klass_part()->java_mirror()); SET_STACK_OBJECT(constants->resolved_klass_at(index)->klass_part()->java_mirror(), 0); break; @@ -2059,17 +2084,6 @@ run: THREAD->set_vm_result(NULL); break; -#if 0 - CASE(_fast_igetfield): - CASE(_fastagetfield): - CASE(_fast_aload_0): - CASE(_fast_iaccess_0): - CASE(__fast_aaccess_0): - CASE(_fast_linearswitch): - CASE(_fast_binaryswitch): - fatal("unsupported fast bytecode"); -#endif - default: ShouldNotReachHere(); } UPDATE_PC_AND_TOS_AND_CONTINUE(incr, 1); @@ -2122,6 +2136,7 @@ run: // get receiver int parms = cache->parameter_size(); // Same comments as invokevirtual apply here + VERIFY_OOP(STACK_OBJECT(-parms)); instanceKlass* rcvrKlass = (instanceKlass*) STACK_OBJECT(-parms)->klass()->klass_part(); callee = (methodOop) rcvrKlass->start_of_vtable()[ cache->f2()]; @@ -2205,6 +2220,7 @@ run: // this fails with an assert // instanceKlass* rcvrKlass = instanceKlass::cast(STACK_OBJECT(-parms)->klass()); // but this works + VERIFY_OOP(STACK_OBJECT(-parms)); instanceKlass* rcvrKlass = (instanceKlass*) STACK_OBJECT(-parms)->klass()->klass_part(); /* Executing this code in java.lang.String: @@ -2651,14 +2667,14 @@ handle_return: LOCALS_SLOT(METHOD->size_of_parameters() - 1)); THREAD->set_popframe_condition_bit(JavaThread::popframe_force_deopt_reexecution_bit); } - UPDATE_PC_AND_RETURN(1); - } else { - // Normal return - // Advance the pc and return to frame manager - istate->set_msg(return_from_method); - istate->set_return_kind((Bytecodes::Code)opcode); - UPDATE_PC_AND_RETURN(1); + THREAD->clr_pop_frame_in_process(); } + + // Normal return + // Advance the pc and return to frame manager + istate->set_msg(return_from_method); + istate->set_return_kind((Bytecodes::Code)opcode); + UPDATE_PC_AND_RETURN(1); } /* handle_return: */ // This is really a fatal error return diff --git a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.hpp b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.hpp index 44c8e8bb75d..086b26b7f8e 100644 --- a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.hpp +++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.hpp @@ -440,7 +440,7 @@ static jint VMintXor(jint op1, jint op2); * iushr, ishl, and ishr bytecodes, respectively. */ -static jint VMintUshr(jint op, jint num); +static juint VMintUshr(jint op, jint num); static jint VMintShl (jint op, jint num); static jint VMintShr (jint op, jint num); diff --git a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.inline.hpp b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.inline.hpp index 887e5459a9c..041d6a1453f 100644 --- a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.inline.hpp +++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.inline.hpp @@ -27,14 +27,11 @@ #ifdef CC_INTERP #ifdef ASSERT -extern "C" { typedef void (*verify_oop_fn_t)(oop, const char *);}; -#define VERIFY_OOP(o) \ - /*{ verify_oop_fn_t verify_oop_entry = \ - *StubRoutines::verify_oop_subroutine_entry_address(); \ - if (verify_oop_entry) { \ - (*verify_oop_entry)((o), "Not an oop!"); \ - } \ - }*/ +#define VERIFY_OOP(o_) \ + if (VerifyOops) { \ + assert((oop(o_))->is_oop_or_null(), "Not an oop!"); \ + StubRoutines::_verify_oop_count++; \ + } #else #define VERIFY_OOP(o) #endif diff --git a/hotspot/src/share/vm/interpreter/bytecodeTracer.cpp b/hotspot/src/share/vm/interpreter/bytecodeTracer.cpp index 6fa807a4d86..1a5cadb4cc4 100644 --- a/hotspot/src/share/vm/interpreter/bytecodeTracer.cpp +++ b/hotspot/src/share/vm/interpreter/bytecodeTracer.cpp @@ -328,24 +328,35 @@ void BytecodePrinter::print_field_or_method(int orig_i, int i, outputStream* st) constantPoolOop constants = method()->constants(); constantTag tag = constants->tag_at(i); - int nt_index = -1; + bool has_klass = true; switch (tag.value()) { case JVM_CONSTANT_InterfaceMethodref: case JVM_CONSTANT_Methodref: case JVM_CONSTANT_Fieldref: + break; case JVM_CONSTANT_NameAndType: + case JVM_CONSTANT_InvokeDynamic: + has_klass = false; break; default: st->print_cr(" bad tag=%d at %d", tag.value(), i); return; } - symbolOop klass = constants->klass_name_at(constants->uncached_klass_ref_index_at(i)); symbolOop name = constants->uncached_name_ref_at(i); symbolOop signature = constants->uncached_signature_ref_at(i); const char* sep = (tag.is_field() ? "/" : ""); - st->print_cr(" %d <%s.%s%s%s> ", i, klass->as_C_string(), name->as_C_string(), sep, signature->as_C_string()); + if (has_klass) { + symbolOop klass = constants->klass_name_at(constants->uncached_klass_ref_index_at(i)); + st->print_cr(" %d <%s.%s%s%s> ", i, klass->as_C_string(), name->as_C_string(), sep, signature->as_C_string()); + } else { + if (tag.is_invoke_dynamic()) { + int bsm = constants->invoke_dynamic_bootstrap_method_ref_index_at(i); + st->print(" bsm=%d", bsm); + } + st->print_cr(" %d <%s%s%s>", i, name->as_C_string(), sep, signature->as_C_string()); + } } diff --git a/hotspot/src/share/vm/interpreter/interpreter.cpp b/hotspot/src/share/vm/interpreter/interpreter.cpp index edef0fafc94..1b1a16333e8 100644 --- a/hotspot/src/share/vm/interpreter/interpreter.cpp +++ b/hotspot/src/share/vm/interpreter/interpreter.cpp @@ -41,20 +41,20 @@ void InterpreterCodelet::verify() { } -void InterpreterCodelet::print() { +void InterpreterCodelet::print_on(outputStream* st) const { if (PrintInterpreter) { - tty->cr(); - tty->print_cr("----------------------------------------------------------------------"); + st->cr(); + st->print_cr("----------------------------------------------------------------------"); } - if (description() != NULL) tty->print("%s ", description()); - if (bytecode() >= 0 ) tty->print("%d %s ", bytecode(), Bytecodes::name(bytecode())); - tty->print_cr("[" INTPTR_FORMAT ", " INTPTR_FORMAT "] %d bytes", + if (description() != NULL) st->print("%s ", description()); + if (bytecode() >= 0 ) st->print("%d %s ", bytecode(), Bytecodes::name(bytecode())); + st->print_cr("[" INTPTR_FORMAT ", " INTPTR_FORMAT "] %d bytes", code_begin(), code_end(), code_size()); if (PrintInterpreter) { - tty->cr(); - Disassembler::decode(code_begin(), code_end(), tty); + st->cr(); + Disassembler::decode(code_begin(), code_end(), st); } } diff --git a/hotspot/src/share/vm/interpreter/interpreter.hpp b/hotspot/src/share/vm/interpreter/interpreter.hpp index fdb9f993bbb..e8da2ce3123 100644 --- a/hotspot/src/share/vm/interpreter/interpreter.hpp +++ b/hotspot/src/share/vm/interpreter/interpreter.hpp @@ -52,7 +52,8 @@ class InterpreterCodelet: public Stub { // Debugging void verify(); - void print(); + void print_on(outputStream* st) const; + void print() const { print_on(tty); } // Interpreter-specific initialization void initialize(const char* description, Bytecodes::Code bytecode); diff --git a/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp b/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp index 2880a9ec2f9..c156bbb3792 100644 --- a/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp +++ b/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp @@ -702,10 +702,6 @@ IRT_ENTRY(void, InterpreterRuntime::resolve_invokedynamic(JavaThread* thread)) { methodHandle caller_method(thread, method(thread)); - // first find the bootstrap method - KlassHandle caller_klass(thread, caller_method->method_holder()); - Handle bootm = SystemDictionary::find_bootstrap_method(caller_klass, CHECK); - constantPoolHandle pool(thread, caller_method->constants()); pool->set_invokedynamic(); // mark header to flag active call sites @@ -726,7 +722,7 @@ IRT_ENTRY(void, InterpreterRuntime::resolve_invokedynamic(JavaThread* thread)) { CallInfo info; LinkResolver::resolve_invoke(info, Handle(), pool, site_index, bytecode, CHECK); - // The main entry corresponds to a JVM_CONSTANT_NameAndType, and serves + // The main entry corresponds to a JVM_CONSTANT_InvokeDynamic, and serves // as a common reference point for all invokedynamic call sites with // that exact call descriptor. We will link it in the CP cache exactly // as if it were an invokevirtual of MethodHandle.invoke. @@ -734,23 +730,30 @@ IRT_ENTRY(void, InterpreterRuntime::resolve_invokedynamic(JavaThread* thread)) { bytecode, info.resolved_method(), info.vtable_index()); - assert(pool->cache()->entry_at(main_index)->is_vfinal(), "f2 must be a methodOop"); } // The method (f2 entry) of the main entry is the MH.invoke for the // invokedynamic target call signature. - intptr_t f2_value = pool->cache()->entry_at(main_index)->f2(); - methodHandle signature_invoker(THREAD, (methodOop) f2_value); + oop f1_value = pool->cache()->entry_at(main_index)->f1(); + methodHandle signature_invoker(THREAD, (methodOop) f1_value); assert(signature_invoker.not_null() && signature_invoker->is_method() && signature_invoker->is_method_handle_invoke(), "correct result from LinkResolver::resolve_invokedynamic"); + Handle bootm = SystemDictionary::find_bootstrap_method(caller_method, caller_bci, + main_index, CHECK); + if (bootm.is_null()) { + THROW_MSG(vmSymbols::java_lang_IllegalStateException(), + "no bootstrap method found for invokedynamic"); + } + + // Short circuit if CallSite has been bound already: + if (!pool->cache()->secondary_entry_at(site_index)->is_f1_null()) + return; + symbolHandle call_site_name(THREAD, pool->name_ref_at(site_index)); Handle info; // NYI: Other metadata from a new kind of CP entry. (Annotations?) - // this is the index which gets stored on the CallSite object (as "callerPosition"): - int call_site_position = constantPoolCacheOopDesc::decode_secondary_index(site_index); - Handle call_site = SystemDictionary::make_dynamic_call_site(bootm, // Callee information: diff --git a/hotspot/src/share/vm/interpreter/linkResolver.cpp b/hotspot/src/share/vm/interpreter/linkResolver.cpp index 1c444a954ca..4a3669403f1 100644 --- a/hotspot/src/share/vm/interpreter/linkResolver.cpp +++ b/hotspot/src/share/vm/interpreter/linkResolver.cpp @@ -67,6 +67,15 @@ void CallInfo::set_virtual(KlassHandle resolved_klass, KlassHandle selected_klas set_common(resolved_klass, selected_klass, resolved_method, selected_method, vtable_index, CHECK); } +void CallInfo::set_dynamic(methodHandle resolved_method, TRAPS) { + assert(resolved_method->is_method_handle_invoke(), ""); + KlassHandle resolved_klass = SystemDictionaryHandles::MethodHandle_klass(); + assert(resolved_klass == resolved_method->method_holder(), ""); + int vtable_index = methodOopDesc::nonvirtual_vtable_index; + assert(resolved_method->vtable_index() == vtable_index, ""); + set_common(resolved_klass, KlassHandle(), resolved_method, resolved_method, vtable_index, CHECK); +} + void CallInfo::set_common(KlassHandle resolved_klass, KlassHandle selected_klass, methodHandle resolved_method, methodHandle selected_method, int vtable_index, TRAPS) { assert(resolved_method->signature() == selected_method->signature(), "signatures must correspond"); _resolved_klass = resolved_klass; @@ -176,9 +185,20 @@ void LinkResolver::lookup_implicit_method(methodHandle& result, KlassHandle klass, symbolHandle name, symbolHandle signature, KlassHandle current_klass, TRAPS) { - if (EnableMethodHandles && MethodHandles::enabled() && + if (EnableMethodHandles && klass() == SystemDictionary::MethodHandle_klass() && methodOopDesc::is_method_handle_invoke_name(name())) { + if (!MethodHandles::enabled()) { + // Make sure the Java part of the runtime has been booted up. + klassOop natives = SystemDictionary::MethodHandleNatives_klass(); + if (natives == NULL || instanceKlass::cast(natives)->is_not_initialized()) { + SystemDictionary::resolve_or_fail(vmSymbolHandles::sun_dyn_MethodHandleNatives(), + Handle(), + Handle(), + true, + CHECK); + } + } methodOop result_oop = SystemDictionary::find_method_handle_invoke(name, signature, current_klass, @@ -1065,7 +1085,7 @@ void LinkResolver::resolve_invokedynamic(CallInfo& result, constantPoolHandle po if (resolved_method.is_null()) { THROW(vmSymbols::java_lang_InternalError()); } - result.set_virtual(resolved_klass, KlassHandle(), resolved_method, resolved_method, resolved_method->vtable_index(), CHECK); + result.set_dynamic(resolved_method, CHECK); } //------------------------------------------------------------------------------------------------------------------------ diff --git a/hotspot/src/share/vm/interpreter/linkResolver.hpp b/hotspot/src/share/vm/interpreter/linkResolver.hpp index c39ea8f41db..f98db15a441 100644 --- a/hotspot/src/share/vm/interpreter/linkResolver.hpp +++ b/hotspot/src/share/vm/interpreter/linkResolver.hpp @@ -73,6 +73,7 @@ class CallInfo: public LinkInfo { void set_static( KlassHandle resolved_klass, methodHandle resolved_method , TRAPS); void set_interface(KlassHandle resolved_klass, KlassHandle selected_klass, methodHandle resolved_method, methodHandle selected_method , TRAPS); void set_virtual( KlassHandle resolved_klass, KlassHandle selected_klass, methodHandle resolved_method, methodHandle selected_method, int vtable_index, TRAPS); + void set_dynamic( methodHandle resolved_method, TRAPS); void set_common( KlassHandle resolved_klass, KlassHandle selected_klass, methodHandle resolved_method, methodHandle selected_method, int vtable_index, TRAPS); friend class LinkResolver; diff --git a/hotspot/src/share/vm/interpreter/oopMapCache.cpp b/hotspot/src/share/vm/interpreter/oopMapCache.cpp index 1ee2675d67e..4ad801c9243 100644 --- a/hotspot/src/share/vm/interpreter/oopMapCache.cpp +++ b/hotspot/src/share/vm/interpreter/oopMapCache.cpp @@ -281,9 +281,7 @@ class MaskFillerForNative: public NativeSignatureIterator { public: void pass_int() { /* ignore */ } void pass_long() { /* ignore */ } -#if defined(_LP64) || defined(ZERO) void pass_float() { /* ignore */ } -#endif void pass_double() { /* ignore */ } void pass_object() { set_one(offset()); } diff --git a/hotspot/src/share/vm/interpreter/rewriter.cpp b/hotspot/src/share/vm/interpreter/rewriter.cpp index 00afdf63a14..558e3138be5 100644 --- a/hotspot/src/share/vm/interpreter/rewriter.cpp +++ b/hotspot/src/share/vm/interpreter/rewriter.cpp @@ -32,14 +32,17 @@ void Rewriter::compute_index_maps() { const int length = _pool->length(); init_cp_map(length); + jint tag_mask = 0; for (int i = 0; i < length; i++) { int tag = _pool->tag_at(i).value(); + tag_mask |= (1 << tag); switch (tag) { case JVM_CONSTANT_InterfaceMethodref: case JVM_CONSTANT_Fieldref : // fall through case JVM_CONSTANT_Methodref : // fall through case JVM_CONSTANT_MethodHandle : // fall through case JVM_CONSTANT_MethodType : // fall through + case JVM_CONSTANT_InvokeDynamic : // fall through add_cp_cache_entry(i); break; } @@ -47,6 +50,8 @@ void Rewriter::compute_index_maps() { guarantee((int)_cp_cache_map.length()-1 <= (int)((u2)-1), "all cp cache indexes fit in a u2"); + + _have_invoke_dynamic = ((tag_mask & (1 << JVM_CONSTANT_InvokeDynamic)) != 0); } @@ -59,6 +64,28 @@ void Rewriter::make_constant_pool_cache(TRAPS) { constantPoolCacheOop cache = oopFactory::new_constantPoolCache(length, methodOopDesc::IsUnsafeConc, CHECK); cache->initialize(_cp_cache_map); + + // Don't bother to the next pass if there is no JVM_CONSTANT_InvokeDynamic. + if (_have_invoke_dynamic) { + for (int i = 0; i < length; i++) { + int pool_index = cp_cache_entry_pool_index(i); + if (pool_index >= 0 && + _pool->tag_at(pool_index).is_invoke_dynamic()) { + int bsm_index = _pool->invoke_dynamic_bootstrap_method_ref_index_at(pool_index); + if (bsm_index != 0) { + assert(_pool->tag_at(bsm_index).is_method_handle(), "must be a MH constant"); + // There is a CP cache entry holding the BSM for these calls. + int bsm_cache_index = cp_entry_to_cp_cache(bsm_index); + cache->entry_at(i)->initialize_bootstrap_method_index_in_cache(bsm_cache_index); + } else { + // There is no CP cache entry holding the BSM for these calls. + // We will need to look for a class-global BSM, later. + guarantee(AllowTransitionalJSR292, ""); + } + } + } + } + _pool->set_cache(cache); cache->set_constant_pool(_pool()); } diff --git a/hotspot/src/share/vm/interpreter/rewriter.hpp b/hotspot/src/share/vm/interpreter/rewriter.hpp index 91ad08a2b95..1f772a640a2 100644 --- a/hotspot/src/share/vm/interpreter/rewriter.hpp +++ b/hotspot/src/share/vm/interpreter/rewriter.hpp @@ -32,6 +32,7 @@ class Rewriter: public StackObj { objArrayHandle _methods; intArray _cp_map; intStack _cp_cache_map; + bool _have_invoke_dynamic; void init_cp_map(int length) { _cp_map.initialize(length, -1); @@ -56,6 +57,22 @@ class Rewriter: public StackObj { return cache_index; } + // Access the contents of _cp_cache_map to determine CP cache layout. + int cp_cache_entry_pool_index(int cache_index) { + int cp_index = _cp_cache_map[cache_index]; + if ((cp_index & _secondary_entry_tag) != 0) + return -1; + else + return cp_index; + } + int cp_cache_secondary_entry_main_index(int cache_index) { + int cp_index = _cp_cache_map[cache_index]; + if ((cp_index & _secondary_entry_tag) == 0) + return -1; + else + return (cp_index - _secondary_entry_tag); + } + // All the work goes in here: Rewriter(instanceKlassHandle klass, constantPoolHandle cpool, objArrayHandle methods, TRAPS); diff --git a/hotspot/src/share/vm/memory/allocation.cpp b/hotspot/src/share/vm/memory/allocation.cpp index e2979646c9c..6331bcefc78 100644 --- a/hotspot/src/share/vm/memory/allocation.cpp +++ b/hotspot/src/share/vm/memory/allocation.cpp @@ -43,24 +43,73 @@ void* ResourceObj::operator new(size_t size, allocation_type type) { switch (type) { case C_HEAP: res = (address)AllocateHeap(size, "C_Heap: ResourceOBJ"); + DEBUG_ONLY(set_allocation_type(res, C_HEAP);) break; case RESOURCE_AREA: + // new(size) sets allocation type RESOURCE_AREA. res = (address)operator new(size); break; default: ShouldNotReachHere(); } - // Set allocation type in the resource object for assertion checks. - DEBUG_ONLY(((ResourceObj *)res)->_allocation = type;) return res; } void ResourceObj::operator delete(void* p) { assert(((ResourceObj *)p)->allocated_on_C_heap(), "delete only allowed for C_HEAP objects"); + DEBUG_ONLY(((ResourceObj *)p)->_allocation = badHeapOopVal;) FreeHeap(p); } +#ifdef ASSERT +void ResourceObj::set_allocation_type(address res, allocation_type type) { + // Set allocation type in the resource object + uintptr_t allocation = (uintptr_t)res; + assert((allocation & allocation_mask) == 0, "address should be aligned to 4 bytes at least"); + assert(type <= allocation_mask, "incorrect allocation type"); + ((ResourceObj *)res)->_allocation = ~(allocation + type); +} + +ResourceObj::allocation_type ResourceObj::get_allocation_type() const { + assert(~(_allocation | allocation_mask) == (uintptr_t)this, "lost resource object"); + return (allocation_type)((~_allocation) & allocation_mask); +} + +ResourceObj::ResourceObj() { // default constructor + if (~(_allocation | allocation_mask) != (uintptr_t)this) { + set_allocation_type((address)this, STACK_OR_EMBEDDED); + } else if (allocated_on_stack()) { + // For some reason we got a value which looks like an allocation on stack. + // Pass if it is really allocated on stack. + assert(Thread::current()->on_local_stack((address)this),"should be on stack"); + } else { + assert(allocated_on_res_area() || allocated_on_C_heap() || allocated_on_arena(), + "allocation_type should be set by operator new()"); + } +} + +ResourceObj::ResourceObj(const ResourceObj& r) { // default copy constructor + // Used in ClassFileParser::parse_constant_pool_entries() for ClassFileStream. + set_allocation_type((address)this, STACK_OR_EMBEDDED); +} + +ResourceObj& ResourceObj::operator=(const ResourceObj& r) { // default copy assignment + // Used in InlineTree::ok_to_inline() for WarmCallInfo. + assert(allocated_on_stack(), "copy only into local"); + // Keep current _allocation value; + return *this; +} + +ResourceObj::~ResourceObj() { + // allocated_on_C_heap() also checks that encoded (in _allocation) address == this. + if (!allocated_on_C_heap()) { // ResourceObj::delete() zaps _allocation for C_heap. + _allocation = badHeapOopVal; // zap type + } +} +#endif // ASSERT + + void trace_heap_malloc(size_t size, const char* name, void* p) { // A lock is not needed here - tty uses a lock internally tty->print_cr("Heap malloc " INTPTR_FORMAT " %7d %s", p, size, name == NULL ? "" : name); @@ -166,32 +215,40 @@ class ChunkPool { _medium_pool = new ChunkPool(Chunk::medium_size + Chunk::aligned_overhead_size()); _small_pool = new ChunkPool(Chunk::init_size + Chunk::aligned_overhead_size()); } + + static void clean() { + enum { BlocksToKeep = 5 }; + _small_pool->free_all_but(BlocksToKeep); + _medium_pool->free_all_but(BlocksToKeep); + _large_pool->free_all_but(BlocksToKeep); + } }; ChunkPool* ChunkPool::_large_pool = NULL; ChunkPool* ChunkPool::_medium_pool = NULL; ChunkPool* ChunkPool::_small_pool = NULL; - void chunkpool_init() { ChunkPool::initialize(); } +void +Chunk::clean_chunk_pool() { + ChunkPool::clean(); +} + //-------------------------------------------------------------------------------------- // ChunkPoolCleaner implementation +// class ChunkPoolCleaner : public PeriodicTask { - enum { CleaningInterval = 5000, // cleaning interval in ms - BlocksToKeep = 5 // # of extra blocks to keep - }; + enum { CleaningInterval = 5000 }; // cleaning interval in ms public: ChunkPoolCleaner() : PeriodicTask(CleaningInterval) {} void task() { - ChunkPool::small_pool()->free_all_but(BlocksToKeep); - ChunkPool::medium_pool()->free_all_but(BlocksToKeep); - ChunkPool::large_pool()->free_all_but(BlocksToKeep); + ChunkPool::clean(); } }; diff --git a/hotspot/src/share/vm/memory/allocation.hpp b/hotspot/src/share/vm/memory/allocation.hpp index 0200670c757..a9f363b499b 100644 --- a/hotspot/src/share/vm/memory/allocation.hpp +++ b/hotspot/src/share/vm/memory/allocation.hpp @@ -174,8 +174,9 @@ class Chunk: public CHeapObj { // Start the chunk_pool cleaner task static void start_chunk_pool_cleaner_task(); -}; + static void clean_chunk_pool(); +}; //------------------------------Arena------------------------------------------ // Fast allocation of memory @@ -316,32 +317,36 @@ extern void resource_free_bytes( char *old, size_t size ); // use delete to deallocate. class ResourceObj ALLOCATION_SUPER_CLASS_SPEC { public: - enum allocation_type { UNKNOWN = 0, C_HEAP, RESOURCE_AREA, ARENA }; + enum allocation_type { STACK_OR_EMBEDDED = 0, RESOURCE_AREA, C_HEAP, ARENA, allocation_mask = 0x3 }; + static void set_allocation_type(address res, allocation_type type) NOT_DEBUG_RETURN; #ifdef ASSERT private: - allocation_type _allocation; + // When this object is allocated on stack the new() operator is not + // called but garbage on stack may look like a valid allocation_type. + // Store negated 'this' pointer when new() is called to distinguish cases. + uintptr_t _allocation; public: - bool allocated_on_C_heap() { return _allocation == C_HEAP; } + allocation_type get_allocation_type() const; + bool allocated_on_stack() const { return get_allocation_type() == STACK_OR_EMBEDDED; } + bool allocated_on_res_area() const { return get_allocation_type() == RESOURCE_AREA; } + bool allocated_on_C_heap() const { return get_allocation_type() == C_HEAP; } + bool allocated_on_arena() const { return get_allocation_type() == ARENA; } + ResourceObj(); // default construtor + ResourceObj(const ResourceObj& r); // default copy construtor + ResourceObj& operator=(const ResourceObj& r); // default copy assignment + ~ResourceObj(); #endif // ASSERT public: void* operator new(size_t size, allocation_type type); void* operator new(size_t size, Arena *arena) { address res = (address)arena->Amalloc(size); - // Set allocation type in the resource object - DEBUG_ONLY(((ResourceObj *)res)->_allocation = ARENA;) + DEBUG_ONLY(set_allocation_type(res, ARENA);) return res; } void* operator new(size_t size) { address res = (address)resource_allocate_bytes(size); - // Set allocation type in the resource object - DEBUG_ONLY(((ResourceObj *)res)->_allocation = RESOURCE_AREA;) - return res; - } - void* operator new(size_t size, void* where, allocation_type type) { - void* res = where; - // Set allocation type in the resource object - DEBUG_ONLY(((ResourceObj *)res)->_allocation = type;) + DEBUG_ONLY(set_allocation_type(res, RESOURCE_AREA);) return res; } void operator delete(void* p); diff --git a/hotspot/src/share/vm/memory/cardTableModRefBS.hpp b/hotspot/src/share/vm/memory/cardTableModRefBS.hpp index a972e159ff4..6bacb22f320 100644 --- a/hotspot/src/share/vm/memory/cardTableModRefBS.hpp +++ b/hotspot/src/share/vm/memory/cardTableModRefBS.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -44,6 +44,7 @@ class CardTableModRefBS: public ModRefBarrierSet { friend class VMStructs; friend class CardTableRS; friend class CheckForUnmarkedOops; // Needs access to raw card bytes. + friend class SharkBuilder; #ifndef PRODUCT // For debugging. friend class GuaranteeNotModClosure; diff --git a/hotspot/src/share/vm/memory/genCollectedHeap.cpp b/hotspot/src/share/vm/memory/genCollectedHeap.cpp index 79005deba1d..0f7d2dc738d 100644 --- a/hotspot/src/share/vm/memory/genCollectedHeap.cpp +++ b/hotspot/src/share/vm/memory/genCollectedHeap.cpp @@ -941,7 +941,9 @@ bool GenCollectedHeap::is_in(const void* p) const { VerifyBeforeExit || PrintAssembly || tty->count() != 0 || // already printing - VerifyAfterGC, "too expensive"); + VerifyAfterGC || + VMError::fatal_error_in_progress(), "too expensive"); + #endif // This might be sped up with a cache of the last generation that // answered yes. diff --git a/hotspot/src/share/vm/memory/generation.hpp b/hotspot/src/share/vm/memory/generation.hpp index 021dd45e0ec..af0bdf2b3f5 100644 --- a/hotspot/src/share/vm/memory/generation.hpp +++ b/hotspot/src/share/vm/memory/generation.hpp @@ -131,7 +131,9 @@ class Generation: public CHeapObj { enum SomePublicConstants { // Generations are GenGrain-aligned and have size that are multiples of // GenGrain. - LogOfGenGrain = 16, + // Note: on ARM we add 1 bit for card_table_base to be properly aligned + // (we expect its low byte to be zero - see implementation of post_barrier) + LogOfGenGrain = 16 ARM_ONLY(+1), GenGrain = 1 << LogOfGenGrain }; diff --git a/hotspot/src/share/vm/oops/arrayKlass.cpp b/hotspot/src/share/vm/oops/arrayKlass.cpp index d5a5abdda46..8ed78221916 100644 --- a/hotspot/src/share/vm/oops/arrayKlass.cpp +++ b/hotspot/src/share/vm/oops/arrayKlass.cpp @@ -179,8 +179,6 @@ jint arrayKlass::jvmti_class_status() const { return JVMTI_CLASS_STATUS_ARRAY; } -#ifndef PRODUCT - // Printing void arrayKlass::oop_print_on(oop obj, outputStream* st) { @@ -189,8 +187,6 @@ void arrayKlass::oop_print_on(oop obj, outputStream* st) { st->print_cr(" - length: %d", arrayOop(obj)->length()); } -#endif - // Verification void arrayKlass::oop_verify_on(oop obj, outputStream* st) { diff --git a/hotspot/src/share/vm/oops/arrayKlass.hpp b/hotspot/src/share/vm/oops/arrayKlass.hpp index a78e2f79aa0..199131ee465 100644 --- a/hotspot/src/share/vm/oops/arrayKlass.hpp +++ b/hotspot/src/share/vm/oops/arrayKlass.hpp @@ -115,20 +115,15 @@ class arrayKlass: public Klass { // Return a handle. static void complete_create_array_klass(arrayKlassHandle k, KlassHandle super_klass, TRAPS); - public: - // jvm support - jint compute_modifier_flags(TRAPS) const; + // jvm support + jint compute_modifier_flags(TRAPS) const; - public: - // JVMTI support - jint jvmti_class_status() const; + // JVMTI support + jint jvmti_class_status() const; -#ifndef PRODUCT - public: // Printing void oop_print_on(oop obj, outputStream* st); -#endif - public: + // Verification void oop_verify_on(oop obj, outputStream* st); }; diff --git a/hotspot/src/share/vm/oops/arrayKlassKlass.cpp b/hotspot/src/share/vm/oops/arrayKlassKlass.cpp index e2bb1432c58..2128f61f93e 100644 --- a/hotspot/src/share/vm/oops/arrayKlassKlass.cpp +++ b/hotspot/src/share/vm/oops/arrayKlassKlass.cpp @@ -151,15 +151,12 @@ arrayKlassKlass::oop_update_pointers(ParCompactionManager* cm, oop obj, } #endif // SERIALGC -#ifndef PRODUCT - // Printing void arrayKlassKlass::oop_print_on(oop obj, outputStream* st) { assert(obj->is_klass(), "must be klass"); klassKlass::oop_print_on(obj, st); } -#endif //PRODUCT void arrayKlassKlass::oop_print_value_on(oop obj, outputStream* st) { assert(obj->is_klass(), "must be klass"); diff --git a/hotspot/src/share/vm/oops/arrayKlassKlass.hpp b/hotspot/src/share/vm/oops/arrayKlassKlass.hpp index 6377fd689c3..4fe4fb51aad 100644 --- a/hotspot/src/share/vm/oops/arrayKlassKlass.hpp +++ b/hotspot/src/share/vm/oops/arrayKlassKlass.hpp @@ -55,12 +55,9 @@ class arrayKlassKlass : public klassKlass { int oop_oop_iterate(oop obj, OopClosure* blk); int oop_oop_iterate_m(oop obj, OopClosure* blk, MemRegion mr); - public: // Printing void oop_print_value_on(oop obj, outputStream* st); -#ifndef PRODUCT void oop_print_on(oop obj, outputStream* st); -#endif //PRODUCT // Verification const char* internal_name() const; diff --git a/hotspot/src/share/vm/oops/compiledICHolderKlass.cpp b/hotspot/src/share/vm/oops/compiledICHolderKlass.cpp index fcda8a56adb..800b7eba9b1 100644 --- a/hotspot/src/share/vm/oops/compiledICHolderKlass.cpp +++ b/hotspot/src/share/vm/oops/compiledICHolderKlass.cpp @@ -154,8 +154,6 @@ int compiledICHolderKlass::oop_update_pointers(ParCompactionManager* cm, } #endif // SERIALGC -#ifndef PRODUCT - // Printing void compiledICHolderKlass::oop_print_on(oop obj, outputStream* st) { @@ -166,8 +164,6 @@ void compiledICHolderKlass::oop_print_on(oop obj, outputStream* st) { st->print(" - klass: "); c->holder_klass()->print_value_on(st); st->cr(); } -#endif //PRODUCT - void compiledICHolderKlass::oop_print_value_on(oop obj, outputStream* st) { assert(obj->is_compiledICHolder(), "must be compiledICHolder"); Klass::oop_print_value_on(obj, st); diff --git a/hotspot/src/share/vm/oops/compiledICHolderKlass.hpp b/hotspot/src/share/vm/oops/compiledICHolderKlass.hpp index 2baefb79444..33fd89b0d62 100644 --- a/hotspot/src/share/vm/oops/compiledICHolderKlass.hpp +++ b/hotspot/src/share/vm/oops/compiledICHolderKlass.hpp @@ -68,12 +68,9 @@ class compiledICHolderKlass : public Klass { int oop_oop_iterate(oop obj, OopClosure* blk); int oop_oop_iterate_m(oop obj, OopClosure* blk, MemRegion mr); - public: // Printing void oop_print_value_on(oop obj, outputStream* st); -#ifndef PRODUCT void oop_print_on (oop obj, outputStream* st); -#endif //PRODUCT // Verification const char* internal_name() const; diff --git a/hotspot/src/share/vm/oops/constMethodKlass.cpp b/hotspot/src/share/vm/oops/constMethodKlass.cpp index 593e4c9838a..b5f15e5f6b7 100644 --- a/hotspot/src/share/vm/oops/constMethodKlass.cpp +++ b/hotspot/src/share/vm/oops/constMethodKlass.cpp @@ -197,8 +197,6 @@ int constMethodKlass::oop_update_pointers(ParCompactionManager* cm, oop obj, } #endif // SERIALGC -#ifndef PRODUCT - // Printing void constMethodKlass::oop_print_on(oop obj, outputStream* st) { @@ -216,8 +214,6 @@ void constMethodKlass::oop_print_on(oop obj, outputStream* st) { } } -#endif //PRODUCT - // Short version of printing constMethodOop - just print the name of the // method it belongs to. void constMethodKlass::oop_print_value_on(oop obj, outputStream* st) { diff --git a/hotspot/src/share/vm/oops/constMethodKlass.hpp b/hotspot/src/share/vm/oops/constMethodKlass.hpp index bc478142177..4e99518c675 100644 --- a/hotspot/src/share/vm/oops/constMethodKlass.hpp +++ b/hotspot/src/share/vm/oops/constMethodKlass.hpp @@ -77,12 +77,9 @@ public: int oop_oop_iterate(oop obj, OopClosure* blk); int oop_oop_iterate_m(oop obj, OopClosure* blk, MemRegion mr); - public: // Printing void oop_print_value_on(oop obj, outputStream* st); -#ifndef PRODUCT void oop_print_on (oop obj, outputStream* st); -#endif //PRODUCT // Verify operations const char* internal_name() const; diff --git a/hotspot/src/share/vm/oops/constantPoolKlass.cpp b/hotspot/src/share/vm/oops/constantPoolKlass.cpp index ab00023b60f..7ca3c79b1da 100644 --- a/hotspot/src/share/vm/oops/constantPoolKlass.cpp +++ b/hotspot/src/share/vm/oops/constantPoolKlass.cpp @@ -299,8 +299,6 @@ void constantPoolKlass::oop_push_contents(PSPromotionManager* pm, oop obj) { } #endif // SERIALGC -#ifndef PRODUCT - // Printing void constantPoolKlass::oop_print_on(oop obj, outputStream* st) { @@ -379,6 +377,10 @@ void constantPoolKlass::oop_print_on(oop obj, outputStream* st) { case JVM_CONSTANT_MethodType : st->print("signature_index=%d", cp->method_type_index_at(index)); break; + case JVM_CONSTANT_InvokeDynamic : + st->print("bootstrap_method_index=%d", cp->invoke_dynamic_bootstrap_method_ref_index_at(index)); + st->print(" name_and_type_index=%d", cp->invoke_dynamic_name_and_type_ref_index_at(index)); + break; default: ShouldNotReachHere(); break; @@ -388,8 +390,6 @@ void constantPoolKlass::oop_print_on(oop obj, outputStream* st) { st->cr(); } -#endif - void constantPoolKlass::oop_print_value_on(oop obj, outputStream* st) { assert(obj->is_constantPool(), "must be constantPool"); constantPoolOop cp = constantPoolOop(obj); diff --git a/hotspot/src/share/vm/oops/constantPoolKlass.hpp b/hotspot/src/share/vm/oops/constantPoolKlass.hpp index 65f9a931f1f..95adcbe307b 100644 --- a/hotspot/src/share/vm/oops/constantPoolKlass.hpp +++ b/hotspot/src/share/vm/oops/constantPoolKlass.hpp @@ -61,18 +61,13 @@ class constantPoolKlass : public Klass { int oop_oop_iterate_m(oop obj, OopClosure* blk, MemRegion mr); // Allocation profiling support - // no idea why this is pure virtual and not in Klass ??? juint alloc_size() const { return _alloc_size; } void set_alloc_size(juint n) { _alloc_size = n; } - public: // Printing void oop_print_value_on(oop obj, outputStream* st); -#ifndef PRODUCT void oop_print_on(oop obj, outputStream* st); -#endif - public: // Verification const char* internal_name() const; void oop_verify_on(oop obj, outputStream* st); diff --git a/hotspot/src/share/vm/oops/constantPoolOop.cpp b/hotspot/src/share/vm/oops/constantPoolOop.cpp index 4915a4543dd..62e2f64dc79 100644 --- a/hotspot/src/share/vm/oops/constantPoolOop.cpp +++ b/hotspot/src/share/vm/oops/constantPoolOop.cpp @@ -264,10 +264,15 @@ symbolOop constantPoolOopDesc::impl_signature_ref_at(int which, bool uncached) { int constantPoolOopDesc::impl_name_and_type_ref_index_at(int which, bool uncached) { int i = which; if (!uncached && cache() != NULL) { - if (constantPoolCacheOopDesc::is_secondary_index(which)) + if (constantPoolCacheOopDesc::is_secondary_index(which)) { // Invokedynamic indexes are always processed in native order // so there is no question of reading a native u2 in Java order here. - return cache()->main_entry_at(which)->constant_pool_index(); + int pool_index = cache()->main_entry_at(which)->constant_pool_index(); + if (tag_at(pool_index).is_invoke_dynamic()) + pool_index = invoke_dynamic_name_and_type_ref_index_at(pool_index); + assert(tag_at(pool_index).is_name_and_type(), ""); + return pool_index; + } // change byte-ordering and go via cache i = remap_instruction_operand_from_cache(which); } else { @@ -830,6 +835,19 @@ bool constantPoolOopDesc::compare_entry_to(int index1, constantPoolHandle cp2, } } break; + case JVM_CONSTANT_InvokeDynamic: + { + int k1 = invoke_dynamic_bootstrap_method_ref_index_at(index1); + int k2 = cp2->invoke_dynamic_bootstrap_method_ref_index_at(index2); + if (k1 == k2) { + int i1 = invoke_dynamic_name_and_type_ref_index_at(index1); + int i2 = cp2->invoke_dynamic_name_and_type_ref_index_at(index2); + if (i1 == i2) { + return true; + } + } + } break; + case JVM_CONSTANT_UnresolvedString: { symbolOop s1 = unresolved_string_at(index1); @@ -1016,6 +1034,13 @@ void constantPoolOopDesc::copy_entry_to(int from_i, constantPoolHandle to_cp, to_cp->method_handle_index_at_put(to_i, k1, k2); } break; + case JVM_CONSTANT_InvokeDynamic: + { + int k1 = invoke_dynamic_bootstrap_method_ref_index_at(from_i); + int k2 = invoke_dynamic_name_and_type_ref_index_at(from_i); + to_cp->invoke_dynamic_at_put(to_i, k1, k2); + } break; + // Invalid is used as the tag for the second constant pool entry // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should // not be seen by itself. @@ -1231,6 +1256,7 @@ jint constantPoolOopDesc::cpool_entry_size(jint idx) { case JVM_CONSTANT_Methodref: case JVM_CONSTANT_InterfaceMethodref: case JVM_CONSTANT_NameAndType: + case JVM_CONSTANT_InvokeDynamic: return 5; case JVM_CONSTANT_Long: @@ -1444,6 +1470,15 @@ int constantPoolOopDesc::copy_cpool_bytes(int cpool_size, DBG(printf("JVM_CONSTANT_MethodType: %hd", idx1)); break; } + case JVM_CONSTANT_InvokeDynamic: { + *bytes = JVM_CONSTANT_InvokeDynamic; + idx1 = invoke_dynamic_bootstrap_method_ref_index_at(idx); + idx2 = invoke_dynamic_name_and_type_ref_index_at(idx); + Bytes::put_Java_u2((address) (bytes+1), idx1); + Bytes::put_Java_u2((address) (bytes+3), idx2); + DBG(printf("JVM_CONSTANT_InvokeDynamic: %hd %hd", idx1, idx2)); + break; + } } DBG(printf("\n")); bytes += ent_size; diff --git a/hotspot/src/share/vm/oops/constantPoolOop.hpp b/hotspot/src/share/vm/oops/constantPoolOop.hpp index 3ea9087636d..8b5889b45ee 100644 --- a/hotspot/src/share/vm/oops/constantPoolOop.hpp +++ b/hotspot/src/share/vm/oops/constantPoolOop.hpp @@ -156,6 +156,11 @@ class constantPoolOopDesc : public oopDesc { *int_at_addr(which) = ref_index; } + void invoke_dynamic_at_put(int which, int bootstrap_method_index, int name_and_type_index) { + tag_at_put(which, JVM_CONSTANT_InvokeDynamic); + *int_at_addr(which) = ((jint) name_and_type_index<<16) | bootstrap_method_index; + } + // Temporary until actual use void unresolved_string_at_put(int which, symbolOop s) { *obj_at_addr(which) = NULL; @@ -396,6 +401,16 @@ class constantPoolOopDesc : public oopDesc { int sym = method_type_index_at(which); return symbol_at(sym); } + int invoke_dynamic_bootstrap_method_ref_index_at(int which) { + assert(tag_at(which).is_invoke_dynamic(), "Corrupted constant pool"); + jint ref_index = *int_at_addr(which); + return extract_low_short_from_int(ref_index); + } + int invoke_dynamic_name_and_type_ref_index_at(int which) { + assert(tag_at(which).is_invoke_dynamic(), "Corrupted constant pool"); + jint ref_index = *int_at_addr(which); + return extract_high_short_from_int(ref_index); + } // The following methods (name/signature/klass_ref_at, klass_ref_at_noresolve, // name_and_type_ref_index_at) all expect to be passed indices obtained diff --git a/hotspot/src/share/vm/oops/cpCacheKlass.cpp b/hotspot/src/share/vm/oops/cpCacheKlass.cpp index afff3352a6c..3d7916ffaa5 100644 --- a/hotspot/src/share/vm/oops/cpCacheKlass.cpp +++ b/hotspot/src/share/vm/oops/cpCacheKlass.cpp @@ -248,8 +248,6 @@ constantPoolCacheKlass::oop_update_pointers(ParCompactionManager* cm, oop obj, } #endif // SERIALGC -#ifndef PRODUCT - void constantPoolCacheKlass::oop_print_on(oop obj, outputStream* st) { assert(obj->is_constantPoolCache(), "obj must be constant pool cache"); constantPoolCacheOop cache = (constantPoolCacheOop)obj; @@ -259,8 +257,6 @@ void constantPoolCacheKlass::oop_print_on(oop obj, outputStream* st) { for (int i = 0; i < cache->length(); i++) cache->entry_at(i)->print(st, i); } -#endif - void constantPoolCacheKlass::oop_print_value_on(oop obj, outputStream* st) { assert(obj->is_constantPoolCache(), "obj must be constant pool cache"); constantPoolCacheOop cache = (constantPoolCacheOop)obj; diff --git a/hotspot/src/share/vm/oops/cpCacheKlass.hpp b/hotspot/src/share/vm/oops/cpCacheKlass.hpp index 2104dbbe0a5..f790e16374e 100644 --- a/hotspot/src/share/vm/oops/cpCacheKlass.hpp +++ b/hotspot/src/share/vm/oops/cpCacheKlass.hpp @@ -61,14 +61,10 @@ class constantPoolCacheKlass: public Klass { juint alloc_size() const { return _alloc_size; } void set_alloc_size(juint n) { _alloc_size = n; } - public: // Printing void oop_print_value_on(oop obj, outputStream* st); -#ifndef PRODUCT void oop_print_on(oop obj, outputStream* st); -#endif - public: // Verification const char* internal_name() const; void oop_verify_on(oop obj, outputStream* st); diff --git a/hotspot/src/share/vm/oops/cpCacheOop.cpp b/hotspot/src/share/vm/oops/cpCacheOop.cpp index f9533c5bd79..eb27f1658ab 100644 --- a/hotspot/src/share/vm/oops/cpCacheOop.cpp +++ b/hotspot/src/share/vm/oops/cpCacheOop.cpp @@ -134,7 +134,7 @@ int ConstantPoolCacheEntry::field_index() const { void ConstantPoolCacheEntry::set_method(Bytecodes::Code invoke_code, methodHandle method, int vtable_index) { - + assert(!is_secondary_entry(), ""); assert(method->interpreter_entry() != NULL, "should have been set at this point"); assert(!method->is_obsolete(), "attempt to write obsolete method to cpCache"); bool change_to_virtual = (invoke_code == Bytecodes::_invokeinterface); @@ -142,7 +142,6 @@ void ConstantPoolCacheEntry::set_method(Bytecodes::Code invoke_code, int byte_no = -1; bool needs_vfinal_flag = false; switch (invoke_code) { - case Bytecodes::_invokedynamic: case Bytecodes::_invokevirtual: case Bytecodes::_invokeinterface: { if (method->can_be_statically_bound()) { @@ -155,6 +154,23 @@ void ConstantPoolCacheEntry::set_method(Bytecodes::Code invoke_code, byte_no = 2; break; } + + case Bytecodes::_invokedynamic: // similar to _invokevirtual + if (TraceInvokeDynamic) { + tty->print_cr("InvokeDynamic set_method%s method="PTR_FORMAT" index=%d", + (is_secondary_entry() ? " secondary" : ""), + (intptr_t)method(), vtable_index); + method->print(); + this->print(tty, 0); + } + assert(method->can_be_statically_bound(), "must be a MH invoker method"); + assert(AllowTransitionalJSR292 || _f2 >= constantPoolOopDesc::CPCACHE_INDEX_TAG, "BSM index initialized"); + set_f1(method()); + needs_vfinal_flag = false; // _f2 is not an oop + assert(!is_vfinal(), "f2 not an oop"); + byte_no = 1; // coordinate this with bytecode_number & is_resolved + break; + case Bytecodes::_invokespecial: // Preserve the value of the vfinal flag on invokevirtual bytecode // which may be shared with this constant pool cache entry. @@ -209,6 +225,7 @@ void ConstantPoolCacheEntry::set_method(Bytecodes::Code invoke_code, void ConstantPoolCacheEntry::set_interface_call(methodHandle method, int index) { + assert(!is_secondary_entry(), ""); klassOop interf = method->method_holder(); assert(instanceKlass::cast(interf)->is_interface(), "must be an interface"); set_f1(interf); @@ -218,8 +235,23 @@ void ConstantPoolCacheEntry::set_interface_call(methodHandle method, int index) } +void ConstantPoolCacheEntry::initialize_bootstrap_method_index_in_cache(int bsm_cache_index) { + assert(!is_secondary_entry(), "only for JVM_CONSTANT_InvokeDynamic main entry"); + assert(_f2 == 0, "initialize once"); + assert(bsm_cache_index == (int)(u2)bsm_cache_index, "oob"); + set_f2(bsm_cache_index + constantPoolOopDesc::CPCACHE_INDEX_TAG); +} + +int ConstantPoolCacheEntry::bootstrap_method_index_in_cache() { + assert(!is_secondary_entry(), "only for JVM_CONSTANT_InvokeDynamic main entry"); + intptr_t bsm_cache_index = (intptr_t) _f2 - constantPoolOopDesc::CPCACHE_INDEX_TAG; + assert(bsm_cache_index == (intptr_t)(u2)bsm_cache_index, "oob"); + return (int) bsm_cache_index; +} + void ConstantPoolCacheEntry::set_dynamic_call(Handle call_site, methodHandle signature_invoker) { + assert(is_secondary_entry(), ""); int param_size = signature_invoker->size_of_parameters(); assert(param_size >= 1, "method argument size must include MH.this"); param_size -= 1; // do not count MH.this; it is not stacked for invokedynamic @@ -227,7 +259,6 @@ void ConstantPoolCacheEntry::set_dynamic_call(Handle call_site, // racing threads might be trying to install their own favorites set_f1(call_site()); } - //set_f2(0); bool is_final = true; assert(signature_invoker->is_final_method(), "is_final"); set_flags(as_flags(as_TosState(signature_invoker->result_type()), is_final, false, false, false, true) | param_size); @@ -417,14 +448,14 @@ void ConstantPoolCacheEntry::print(outputStream* st, int index) const { // print separator if (index == 0) tty->print_cr(" -------------"); // print entry - tty->print_cr("%3d (%08x) ", index, this); + tty->print("%3d ("PTR_FORMAT") ", index, (intptr_t)this); if (is_secondary_entry()) tty->print_cr("[%5d|secondary]", main_entry_index()); else tty->print_cr("[%02x|%02x|%5d]", bytecode_2(), bytecode_1(), constant_pool_index()); - tty->print_cr(" [ %08x]", (address)(oop)_f1); - tty->print_cr(" [ %08x]", _f2); - tty->print_cr(" [ %08x]", _flags); + tty->print_cr(" [ "PTR_FORMAT"]", (intptr_t)(oop)_f1); + tty->print_cr(" [ "PTR_FORMAT"]", (intptr_t)_f2); + tty->print_cr(" [ "PTR_FORMAT"]", (intptr_t)_flags); tty->print_cr(" -------------"); } diff --git a/hotspot/src/share/vm/oops/cpCacheOop.hpp b/hotspot/src/share/vm/oops/cpCacheOop.hpp index 0759815697c..68460717fe0 100644 --- a/hotspot/src/share/vm/oops/cpCacheOop.hpp +++ b/hotspot/src/share/vm/oops/cpCacheOop.hpp @@ -185,6 +185,10 @@ class ConstantPoolCacheEntry VALUE_OBJ_CLASS_SPEC { methodHandle signature_invoker // determines signature information ); + // For JVM_CONSTANT_InvokeDynamic cache entries: + void initialize_bootstrap_method_index_in_cache(int bsm_cache_index); + int bootstrap_method_index_in_cache(); + void set_parameter_size(int value) { assert(parameter_size() == 0 || parameter_size() == value, "size must not change"); @@ -207,6 +211,7 @@ class ConstantPoolCacheEntry VALUE_OBJ_CLASS_SPEC { case Bytecodes::_getfield : // fall through case Bytecodes::_invokespecial : // fall through case Bytecodes::_invokestatic : // fall through + case Bytecodes::_invokedynamic : // fall through case Bytecodes::_invokeinterface : return 1; case Bytecodes::_putstatic : // fall through case Bytecodes::_putfield : // fall through @@ -234,6 +239,7 @@ class ConstantPoolCacheEntry VALUE_OBJ_CLASS_SPEC { Bytecodes::Code bytecode_1() const { return Bytecodes::cast((_indices >> 16) & 0xFF); } Bytecodes::Code bytecode_2() const { return Bytecodes::cast((_indices >> 24) & 0xFF); } volatile oop f1() const { return _f1; } + bool is_f1_null() const { return (oop)_f1 == NULL; } // classifies a CPC entry as unbound intx f2() const { return _f2; } int field_index() const; int parameter_size() const { return _flags & 0xFF; } diff --git a/hotspot/src/share/vm/oops/generateOopMap.cpp b/hotspot/src/share/vm/oops/generateOopMap.cpp index 952e2661ef9..25067a84d32 100644 --- a/hotspot/src/share/vm/oops/generateOopMap.cpp +++ b/hotspot/src/share/vm/oops/generateOopMap.cpp @@ -2111,7 +2111,13 @@ void GenerateOopMap::verify_error(const char *format, ...) { // We do not distinguish between different types of errors for verification // errors. Let the verifier give a better message. const char *msg = "Illegal class file encountered. Try running with -Xverify:all"; - error_work(msg, NULL); + _got_error = true; + // Append method name + char msg_buffer2[512]; + jio_snprintf(msg_buffer2, sizeof(msg_buffer2), "%s in method %s", msg, + method()->name()->as_C_string()); + _exception = Exceptions::new_exception(Thread::current(), + vmSymbols::java_lang_LinkageError(), msg_buffer2); } // diff --git a/hotspot/src/share/vm/oops/klass.cpp b/hotspot/src/share/vm/oops/klass.cpp index 867d715b4a6..2b6dc261ef9 100644 --- a/hotspot/src/share/vm/oops/klass.cpp +++ b/hotspot/src/share/vm/oops/klass.cpp @@ -520,8 +520,6 @@ jint Klass::jvmti_class_status() const { return 0; } -#ifndef PRODUCT - // Printing void Klass::oop_print_on(oop obj, outputStream* st) { @@ -541,8 +539,6 @@ void Klass::oop_print_on(oop obj, outputStream* st) { st->cr(); } -#endif //PRODUCT - void Klass::oop_print_value_on(oop obj, outputStream* st) { // print title ResourceMark rm; // Cannot print in debug mode without this diff --git a/hotspot/src/share/vm/oops/klass.hpp b/hotspot/src/share/vm/oops/klass.hpp index 8895a64e3b5..ca4571b9b39 100644 --- a/hotspot/src/share/vm/oops/klass.hpp +++ b/hotspot/src/share/vm/oops/klass.hpp @@ -772,16 +772,12 @@ class Klass : public Klass_vtbl { // jvm support virtual jint compute_modifier_flags(TRAPS) const; - public: // JVMTI support virtual jint jvmti_class_status() const; - public: // Printing virtual void oop_print_value_on(oop obj, outputStream* st); -#ifndef PRODUCT virtual void oop_print_on (oop obj, outputStream* st); -#endif //PRODUCT // Verification virtual const char* internal_name() const = 0; diff --git a/hotspot/src/share/vm/oops/klassKlass.cpp b/hotspot/src/share/vm/oops/klassKlass.cpp index d4647e1081f..74a352fda35 100644 --- a/hotspot/src/share/vm/oops/klassKlass.cpp +++ b/hotspot/src/share/vm/oops/klassKlass.cpp @@ -194,16 +194,12 @@ int klassKlass::oop_update_pointers(ParCompactionManager* cm, oop obj, #endif // SERIALGC -#ifndef PRODUCT - // Printing void klassKlass::oop_print_on(oop obj, outputStream* st) { Klass::oop_print_on(obj, st); } -#endif //PRODUCT - void klassKlass::oop_print_value_on(oop obj, outputStream* st) { Klass::oop_print_value_on(obj, st); } diff --git a/hotspot/src/share/vm/oops/klassKlass.hpp b/hotspot/src/share/vm/oops/klassKlass.hpp index 14b56ff9e7e..168e8daad8d 100644 --- a/hotspot/src/share/vm/oops/klassKlass.hpp +++ b/hotspot/src/share/vm/oops/klassKlass.hpp @@ -67,12 +67,9 @@ class klassKlass: public Klass { juint alloc_size() const { return _alloc_size; } void set_alloc_size(juint n) { _alloc_size = n; } - public: // Printing void oop_print_value_on(oop obj, outputStream* st); -#ifndef PRODUCT void oop_print_on (oop obj, outputStream* st); -#endif //PRODUCT // Verification const char* internal_name() const; diff --git a/hotspot/src/share/vm/oops/methodOop.cpp b/hotspot/src/share/vm/oops/methodOop.cpp index 75a9d23dc72..32032c0022c 100644 --- a/hotspot/src/share/vm/oops/methodOop.cpp +++ b/hotspot/src/share/vm/oops/methodOop.cpp @@ -751,10 +751,14 @@ void methodOopDesc::set_code(methodHandle mh, nmethod *code) { } OrderAccess::storestore(); +#ifdef SHARK + mh->_from_interpreted_entry = code->instructions_begin(); +#else mh->_from_compiled_entry = code->verified_entry_point(); OrderAccess::storestore(); // Instantly compiled code can execute. mh->_from_interpreted_entry = mh->get_i2c_entry(); +#endif // SHARK } @@ -851,9 +855,15 @@ jint* methodOopDesc::method_type_offsets_chain() { // MethodHandleCompiler. // Must be consistent with MethodHandleCompiler::get_method_oop(). bool methodOopDesc::is_method_handle_adapter() const { - return (is_method_handle_invoke_name(name()) && - is_synthetic() && - MethodHandleCompiler::klass_is_method_handle_adapter_holder(method_holder())); + if (is_synthetic() && + !is_native() && // has code from MethodHandleCompiler + is_method_handle_invoke_name(name()) && + MethodHandleCompiler::klass_is_method_handle_adapter_holder(method_holder())) { + assert(!is_method_handle_invoke(), "disjoint"); + return true; + } else { + return false; + } } methodHandle methodOopDesc::make_invoke_method(KlassHandle holder, diff --git a/hotspot/src/share/vm/oops/oop.cpp b/hotspot/src/share/vm/oops/oop.cpp index 1db8b7f0bd2..ff7c78a5073 100644 --- a/hotspot/src/share/vm/oops/oop.cpp +++ b/hotspot/src/share/vm/oops/oop.cpp @@ -29,15 +29,6 @@ bool always_do_update_barrier = false; BarrierSet* oopDesc::_bs = NULL; -#ifdef PRODUCT -void oopDesc::print_on(outputStream* st) const {} -void oopDesc::print_address_on(outputStream* st) const {} -char* oopDesc::print_string() { return NULL; } -void oopDesc::print() {} -void oopDesc::print_address() {} - -#else //PRODUCT - void oopDesc::print_on(outputStream* st) const { if (this == NULL) { st->print_cr("NULL"); @@ -62,10 +53,6 @@ char* oopDesc::print_string() { return st.as_string(); } -#endif // PRODUCT - -// The print_value functions are present in all builds, to support the disassembler. - void oopDesc::print_value() { print_value_on(tty); } @@ -83,9 +70,7 @@ void oopDesc::print_value_on(outputStream* st) const { st->print("NULL"); } else if (java_lang_String::is_instance(obj)) { java_lang_String::print(obj, st); -#ifndef PRODUCT if (PrintOopAddress) print_address_on(st); -#endif //PRODUCT #ifdef ASSERT } else if (!Universe::heap()->is_in(obj) || !Universe::heap()->is_in(klass())) { st->print("### BAD OOP %p ###", (address)obj); diff --git a/hotspot/src/share/vm/opto/block.cpp b/hotspot/src/share/vm/opto/block.cpp index d7cf639c9c4..1d7a84048d5 100644 --- a/hotspot/src/share/vm/opto/block.cpp +++ b/hotspot/src/share/vm/opto/block.cpp @@ -353,7 +353,8 @@ void Block::dump( const Block_Array *bbs ) const { PhaseCFG::PhaseCFG( Arena *a, RootNode *r, Matcher &m ) : Phase(CFG), _bbs(a), - _root(r) + _root(r), + _node_latency(NULL) #ifndef PRODUCT , _trace_opto_pipelining(TraceOptoPipelining || C->method_has_option("TraceOptoPipelining")) #endif diff --git a/hotspot/src/share/vm/opto/block.hpp b/hotspot/src/share/vm/opto/block.hpp index 9bd989539b2..cc06263f18e 100644 --- a/hotspot/src/share/vm/opto/block.hpp +++ b/hotspot/src/share/vm/opto/block.hpp @@ -374,7 +374,7 @@ class PhaseCFG : public Phase { float _outer_loop_freq; // Outmost loop frequency // Per node latency estimation, valid only during GCM - GrowableArray _node_latency; + GrowableArray *_node_latency; #ifndef PRODUCT bool _trace_opto_pipelining; // tracing flag diff --git a/hotspot/src/share/vm/opto/c2_globals.hpp b/hotspot/src/share/vm/opto/c2_globals.hpp index ac0a991d485..3fdaf842740 100644 --- a/hotspot/src/share/vm/opto/c2_globals.hpp +++ b/hotspot/src/share/vm/opto/c2_globals.hpp @@ -281,6 +281,12 @@ product(bool, InsertMemBarAfterArraycopy, true, \ "Insert memory barrier after arraycopy call") \ \ + develop(bool, SubsumeLoads, true, \ + "Attempt to compile while subsuming loads into machine instructions.") \ + \ + develop(bool, StressRecompilation, false, \ + "Recompile each compiled method without subsuming loads or escape analysis.") \ + \ /* controls for tier 1 compilations */ \ \ develop(bool, Tier1CountInvocations, true, \ diff --git a/hotspot/src/share/vm/opto/c2compiler.cpp b/hotspot/src/share/vm/opto/c2compiler.cpp index ff4fa6bade6..142273b2626 100644 --- a/hotspot/src/share/vm/opto/c2compiler.cpp +++ b/hotspot/src/share/vm/opto/c2compiler.cpp @@ -103,13 +103,14 @@ void C2Compiler::compile_method(ciEnv* env, if (!is_initialized()) { initialize(); } - bool subsume_loads = true; + bool subsume_loads = SubsumeLoads; bool do_escape_analysis = DoEscapeAnalysis && !env->jvmti_can_access_local_variables(); while (!env->failing()) { // Attempt to compile while subsuming loads into machine instructions. Compile C(env, this, target, entry_bci, subsume_loads, do_escape_analysis); + // Check result and retry if appropriate. if (C.failure_reason() != NULL) { if (C.failure_reason_is(retry_no_subsuming_loads())) { @@ -127,6 +128,16 @@ void C2Compiler::compile_method(ciEnv* env, // on the ciEnv via env->record_method_not_compilable(). env->record_failure(C.failure_reason()); } + if (StressRecompilation) { + if (subsume_loads) { + subsume_loads = false; + continue; // retry + } + if (do_escape_analysis) { + do_escape_analysis = false; + continue; // retry + } + } // No retry; just break the loop. break; diff --git a/hotspot/src/share/vm/opto/chaitin.cpp b/hotspot/src/share/vm/opto/chaitin.cpp index ed9124b24f8..4a8e0e3f526 100644 --- a/hotspot/src/share/vm/opto/chaitin.cpp +++ b/hotspot/src/share/vm/opto/chaitin.cpp @@ -569,7 +569,7 @@ void PhaseChaitin::gather_lrg_masks( bool after_aggressive ) { if (trace_spilling() && lrg._def != NULL) { // collect defs for MultiDef printing if (lrg._defs == NULL) { - lrg._defs = new (_ifg->_arena) GrowableArray(); + lrg._defs = new (_ifg->_arena) GrowableArray(_ifg->_arena, 2, 0, NULL); lrg._defs->append(lrg._def); } lrg._defs->append(n); diff --git a/hotspot/src/share/vm/opto/compile.cpp b/hotspot/src/share/vm/opto/compile.cpp index 63206652187..e5d3c4fdd67 100644 --- a/hotspot/src/share/vm/opto/compile.cpp +++ b/hotspot/src/share/vm/opto/compile.cpp @@ -904,8 +904,8 @@ void Compile::Init(int aliaslevel) { probe_alias_cache(NULL)->_index = AliasIdxTop; _intrinsics = NULL; - _macro_nodes = new GrowableArray(comp_arena(), 8, 0, NULL); - _predicate_opaqs = new GrowableArray(comp_arena(), 8, 0, NULL); + _macro_nodes = new(comp_arena()) GrowableArray(comp_arena(), 8, 0, NULL); + _predicate_opaqs = new(comp_arena()) GrowableArray(comp_arena(), 8, 0, NULL); register_library_intrinsics(); } diff --git a/hotspot/src/share/vm/opto/gcm.cpp b/hotspot/src/share/vm/opto/gcm.cpp index 5fc0b1c1b6a..f222001d315 100644 --- a/hotspot/src/share/vm/opto/gcm.cpp +++ b/hotspot/src/share/vm/opto/gcm.cpp @@ -841,7 +841,7 @@ void PhaseCFG::partial_latency_of_defs(Node *n) { #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print("# latency_to_inputs: node_latency[%d] = %d for node", - n->_idx, _node_latency.at_grow(n->_idx)); + n->_idx, _node_latency->at_grow(n->_idx)); dump(); } #endif @@ -853,7 +853,7 @@ void PhaseCFG::partial_latency_of_defs(Node *n) { return; uint nlen = n->len(); - uint use_latency = _node_latency.at_grow(n->_idx); + uint use_latency = _node_latency->at_grow(n->_idx); uint use_pre_order = _bbs[n->_idx]->_pre_order; for ( uint j=0; jlatency(j); uint current_latency = delta_latency + use_latency; - if (_node_latency.at_grow(def->_idx) < current_latency) { - _node_latency.at_put_grow(def->_idx, current_latency); + if (_node_latency->at_grow(def->_idx) < current_latency) { + _node_latency->at_put_grow(def->_idx, current_latency); } #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print_cr("# %d + edge_latency(%d) == %d -> %d, node_latency[%d] = %d", use_latency, j, delta_latency, current_latency, def->_idx, - _node_latency.at_grow(def->_idx)); + _node_latency->at_grow(def->_idx)); } #endif } @@ -926,7 +926,7 @@ int PhaseCFG::latency_from_use(Node *n, const Node *def, Node *use) { return 0; uint nlen = use->len(); - uint nl = _node_latency.at_grow(use->_idx); + uint nl = _node_latency->at_grow(use->_idx); for ( uint j=0; jin(j) == n) { @@ -962,7 +962,7 @@ void PhaseCFG::latency_from_uses(Node *n) { #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print("# latency_from_outputs: node_latency[%d] = %d for node", - n->_idx, _node_latency.at_grow(n->_idx)); + n->_idx, _node_latency->at_grow(n->_idx)); dump(); } #endif @@ -975,7 +975,7 @@ void PhaseCFG::latency_from_uses(Node *n) { if (latency < l) latency = l; } - _node_latency.at_put_grow(n->_idx, latency); + _node_latency->at_put_grow(n->_idx, latency); } //------------------------------hoist_to_cheaper_block------------------------- @@ -985,9 +985,9 @@ Block* PhaseCFG::hoist_to_cheaper_block(Block* LCA, Block* early, Node* self) { const double delta = 1+PROB_UNLIKELY_MAG(4); Block* least = LCA; double least_freq = least->_freq; - uint target = _node_latency.at_grow(self->_idx); - uint start_latency = _node_latency.at_grow(LCA->_nodes[0]->_idx); - uint end_latency = _node_latency.at_grow(LCA->_nodes[LCA->end_idx()]->_idx); + uint target = _node_latency->at_grow(self->_idx); + uint start_latency = _node_latency->at_grow(LCA->_nodes[0]->_idx); + uint end_latency = _node_latency->at_grow(LCA->_nodes[LCA->end_idx()]->_idx); bool in_latency = (target <= start_latency); const Block* root_block = _bbs[_root->_idx]; @@ -1005,7 +1005,7 @@ Block* PhaseCFG::hoist_to_cheaper_block(Block* LCA, Block* early, Node* self) { #ifndef PRODUCT if (trace_opto_pipelining()) { tty->print("# Find cheaper block for latency %d: ", - _node_latency.at_grow(self->_idx)); + _node_latency->at_grow(self->_idx)); self->dump(); tty->print_cr("# B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g", LCA->_pre_order, @@ -1032,9 +1032,9 @@ Block* PhaseCFG::hoist_to_cheaper_block(Block* LCA, Block* early, Node* self) { if (mach && LCA == root_block) break; - uint start_lat = _node_latency.at_grow(LCA->_nodes[0]->_idx); + uint start_lat = _node_latency->at_grow(LCA->_nodes[0]->_idx); uint end_idx = LCA->end_idx(); - uint end_lat = _node_latency.at_grow(LCA->_nodes[end_idx]->_idx); + uint end_lat = _node_latency->at_grow(LCA->_nodes[end_idx]->_idx); double LCA_freq = LCA->_freq; #ifndef PRODUCT if (trace_opto_pipelining()) { @@ -1073,7 +1073,7 @@ Block* PhaseCFG::hoist_to_cheaper_block(Block* LCA, Block* early, Node* self) { tty->print_cr("# Change latency for [%4d] from %d to %d", self->_idx, target, end_latency); } #endif - _node_latency.at_put_grow(self->_idx, end_latency); + _node_latency->at_put_grow(self->_idx, end_latency); partial_latency_of_defs(self); } @@ -1255,8 +1255,7 @@ void PhaseCFG::GlobalCodeMotion( Matcher &matcher, uint unique, Node_List &proj_ // Compute the latency information (via backwards walk) for all the // instructions in the graph - GrowableArray node_latency; - _node_latency = node_latency; + _node_latency = new GrowableArray(); // resource_area allocation if( C->do_scheduling() ) ComputeLatenciesBackwards(visited, stack); @@ -1341,6 +1340,8 @@ void PhaseCFG::GlobalCodeMotion( Matcher &matcher, uint unique, Node_List &proj_ } } #endif + // Dead. + _node_latency = (GrowableArray *)0xdeadbeef; } diff --git a/hotspot/src/share/vm/opto/lcm.cpp b/hotspot/src/share/vm/opto/lcm.cpp index 0afde90166d..2e43346c7e4 100644 --- a/hotspot/src/share/vm/opto/lcm.cpp +++ b/hotspot/src/share/vm/opto/lcm.cpp @@ -113,7 +113,8 @@ void Block::implicit_null_check(PhaseCFG *cfg, Node *proj, Node *val, int allowe if( !m->is_Mach() ) continue; MachNode *mach = m->as_Mach(); was_store = false; - switch( mach->ideal_Opcode() ) { + int iop = mach->ideal_Opcode(); + switch( iop ) { case Op_LoadB: case Op_LoadUS: case Op_LoadD: @@ -155,6 +156,12 @@ void Block::implicit_null_check(PhaseCFG *cfg, Node *proj, Node *val, int allowe default: // Also check for embedded loads if( !mach->needs_anti_dependence_check() ) continue; // Not an memory op; skip it + if( must_clone[iop] ) { + // Do not move nodes which produce flags because + // RA will try to clone it to place near branch and + // it will cause recompilation, see clone_node(). + continue; + } { // Check that value is used in memory address in // instructions with embedded load (CmpP val1,(val2+off)). @@ -461,7 +468,7 @@ Node *Block::select(PhaseCFG *cfg, Node_List &worklist, int *ready_cnt, VectorSe n_choice = 1; } - uint n_latency = cfg->_node_latency.at_grow(n->_idx); + uint n_latency = cfg->_node_latency->at_grow(n->_idx); uint n_score = n->req(); // Many inputs get high score to break ties // Keep best latency found @@ -738,7 +745,7 @@ bool Block::schedule_local(PhaseCFG *cfg, Matcher &matcher, int *ready_cnt, Vect Node *n = _nodes[j]; int idx = n->_idx; tty->print("# ready cnt:%3d ", ready_cnt[idx]); - tty->print("latency:%3d ", cfg->_node_latency.at_grow(idx)); + tty->print("latency:%3d ", cfg->_node_latency->at_grow(idx)); tty->print("%4d: %s\n", idx, n->Name()); } } @@ -765,7 +772,7 @@ bool Block::schedule_local(PhaseCFG *cfg, Matcher &matcher, int *ready_cnt, Vect #ifndef PRODUCT if (cfg->trace_opto_pipelining()) { tty->print("# select %d: %s", n->_idx, n->Name()); - tty->print(", latency:%d", cfg->_node_latency.at_grow(n->_idx)); + tty->print(", latency:%d", cfg->_node_latency->at_grow(n->_idx)); n->dump(); if (Verbose) { tty->print("# ready list:"); @@ -957,6 +964,8 @@ void Block::call_catch_cleanup(Block_Array &bbs) { Block *sb = _succs[i]; // Clone the entire area; ignoring the edge fixup for now. for( uint j = end; j > beg; j-- ) { + // It is safe here to clone a node with anti_dependence + // since clones dominate on each path. Node *clone = _nodes[j-1]->clone(); sb->_nodes.insert( 1, clone ); bbs.map(clone->_idx,sb); diff --git a/hotspot/src/share/vm/opto/macro.cpp b/hotspot/src/share/vm/opto/macro.cpp index 3431731674d..214c3150e40 100644 --- a/hotspot/src/share/vm/opto/macro.cpp +++ b/hotspot/src/share/vm/opto/macro.cpp @@ -720,7 +720,7 @@ bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray is_loaded()) { field_type = TypeInstPtr::BOTTOM; - } else if (field != NULL && field->is_constant()) { + } else if (field != NULL && field->is_constant() && field->is_static()) { // This can happen if the constant oop is non-perm. ciObject* con = field->constant_value().as_object(); // Do not "join" in the previous type; it doesn't add value, diff --git a/hotspot/src/share/vm/opto/output.cpp b/hotspot/src/share/vm/opto/output.cpp index e3d331f57d7..010743959c7 100644 --- a/hotspot/src/share/vm/opto/output.cpp +++ b/hotspot/src/share/vm/opto/output.cpp @@ -382,6 +382,10 @@ void Compile::Shorten_branches(Label *labels, int& code_size, int& reloc_size, i if (min_offset_from_last_call == 0) { blk_size += nop_size; } + } else if (mach->ideal_Opcode() == Op_Jump) { + const_size += b->_num_succs; // Address table size + // The size is valid even for 64 bit since it is + // multiplied by 2*jintSize on this method exit. } } min_offset_from_last_call += inst_size; diff --git a/hotspot/src/share/vm/opto/reg_split.cpp b/hotspot/src/share/vm/opto/reg_split.cpp index a0927213a18..a4fee6f7cc2 100644 --- a/hotspot/src/share/vm/opto/reg_split.cpp +++ b/hotspot/src/share/vm/opto/reg_split.cpp @@ -271,6 +271,32 @@ uint PhaseChaitin::split_USE( Node *def, Block *b, Node *use, uint useidx, uint return maxlrg; } +//------------------------------clone_node---------------------------- +// Clone node with anti dependence check. +Node* clone_node(Node* def, Block *b, Compile* C) { + if (def->needs_anti_dependence_check()) { +#ifdef ASSERT + if (Verbose) { + tty->print_cr("RA attempts to clone node with anti_dependence:"); + def->dump(-1); tty->cr(); + tty->print_cr("into block:"); + b->dump(); + } +#endif + if (C->subsume_loads() == true && !C->failing()) { + // Retry with subsume_loads == false + // If this is the first failure, the sentinel string will "stick" + // to the Compile object, and the C2Compiler will see it and retry. + C->record_failure(C2Compiler::retry_no_subsuming_loads()); + } else { + // Bailout without retry + C->record_method_not_compilable("RA Split failed: attempt to clone node with anti_dependence"); + } + return 0; + } + return def->clone(); +} + //------------------------------split_Rematerialize---------------------------- // Clone a local copy of the def. Node *PhaseChaitin::split_Rematerialize( Node *def, Block *b, uint insidx, uint &maxlrg, GrowableArray splits, int slidx, uint *lrg2reach, Node **Reachblock, bool walkThru ) { @@ -298,8 +324,8 @@ Node *PhaseChaitin::split_Rematerialize( Node *def, Block *b, uint insidx, uint } } - Node *spill = def->clone(); - if (C->check_node_count(NodeLimitFudgeFactor, out_of_nodes)) { + Node *spill = clone_node(def, b, C); + if (spill == NULL || C->check_node_count(NodeLimitFudgeFactor, out_of_nodes)) { // Check when generating nodes return 0; } @@ -834,13 +860,13 @@ uint PhaseChaitin::Split( uint maxlrg ) { // The effect of this clone is to drop the node out of the block, // so that the allocator does not see it anymore, and therefore // does not attempt to assign it a register. - def = def->clone(); + def = clone_node(def, b, C); + if (def == NULL || C->check_node_count(NodeLimitFudgeFactor, out_of_nodes)) { + return 0; + } _names.extend(def->_idx,0); _cfg._bbs.map(def->_idx,b); n->set_req(inpidx, def); - if (C->check_node_count(NodeLimitFudgeFactor, out_of_nodes)) { - return 0; - } continue; } diff --git a/hotspot/src/share/vm/prims/jni.cpp b/hotspot/src/share/vm/prims/jni.cpp index c81a6f9c34d..b9961726bad 100644 --- a/hotspot/src/share/vm/prims/jni.cpp +++ b/hotspot/src/share/vm/prims/jni.cpp @@ -3414,6 +3414,8 @@ static jint attach_current_thread(JavaVM *vm, void **penv, void *_args, bool dae thread->initialize_tlab(); + thread->cache_global_variables(); + // Crucial that we do not have a safepoint check for this thread, since it has // not been added to the Thread list yet. { Threads_lock->lock_without_safepoint_check(); diff --git a/hotspot/src/share/vm/prims/jvm.h b/hotspot/src/share/vm/prims/jvm.h index 1445a32d65a..bd982910111 100644 --- a/hotspot/src/share/vm/prims/jvm.h +++ b/hotspot/src/share/vm/prims/jvm.h @@ -1046,7 +1046,8 @@ enum { JVM_CONSTANT_InterfaceMethodref, JVM_CONSTANT_NameAndType, JVM_CONSTANT_MethodHandle = 15, // JSR 292 - JVM_CONSTANT_MethodType = 16 // JSR 292 + JVM_CONSTANT_MethodType = 16, // JSR 292 + JVM_CONSTANT_InvokeDynamic = 17 // JSR 292 }; /* JVM_CONSTANT_MethodHandle subtypes */ diff --git a/hotspot/src/share/vm/prims/jvmtiEnvThreadState.hpp b/hotspot/src/share/vm/prims/jvmtiEnvThreadState.hpp index 64a30b46d41..b0ebb066741 100644 --- a/hotspot/src/share/vm/prims/jvmtiEnvThreadState.hpp +++ b/hotspot/src/share/vm/prims/jvmtiEnvThreadState.hpp @@ -24,6 +24,8 @@ #ifndef _JAVA_JVMTIENVTHREADSTATE_H_ #define _JAVA_JVMTIENVTHREADSTATE_H_ +class JvmtiEnv; + /////////////////////////////////////////////////////////////// // // class JvmtiFramePop diff --git a/hotspot/src/share/vm/prims/methodHandleWalk.cpp b/hotspot/src/share/vm/prims/methodHandleWalk.cpp index f41f63a16a0..6a82f4b2436 100644 --- a/hotspot/src/share/vm/prims/methodHandleWalk.cpp +++ b/hotspot/src/share/vm/prims/methodHandleWalk.cpp @@ -738,6 +738,12 @@ void MethodHandleCompiler::emit_bc(Bytecodes::Code op, int index) { // bi case Bytecodes::_ldc: + assert(Bytecodes::format_bits(op, false) == (Bytecodes::_fmt_b|Bytecodes::_fmt_has_k), "wrong bytecode format"); + assert((char) index == index, "index does not fit in 8-bit"); + _bytecode.push(op); + _bytecode.push(index); + break; + case Bytecodes::_iload: case Bytecodes::_lload: case Bytecodes::_fload: @@ -754,7 +760,8 @@ void MethodHandleCompiler::emit_bc(Bytecodes::Code op, int index) { _bytecode.push(index); break; - // bii + // bkk + case Bytecodes::_ldc_w: case Bytecodes::_ldc2_w: case Bytecodes::_checkcast: assert(Bytecodes::format_bits(op, false) == Bytecodes::_fmt_bkk, "wrong bytecode format"); diff --git a/hotspot/src/share/vm/prims/methodHandles.cpp b/hotspot/src/share/vm/prims/methodHandles.cpp index f084b5af82f..7b3acfda1e1 100644 --- a/hotspot/src/share/vm/prims/methodHandles.cpp +++ b/hotspot/src/share/vm/prims/methodHandles.cpp @@ -2475,6 +2475,10 @@ JVM_END JVM_ENTRY(void, MHI_registerBootstrap(JNIEnv *env, jobject igcls, jclass caller_jh, jobject bsm_jh)) { instanceKlassHandle ik = MethodHandles::resolve_instance_klass(caller_jh, THREAD); + if (!AllowTransitionalJSR292) { + THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), + "registerBootstrapMethod is only supported in JSR 292 EDR"); + } ik->link_class(CHECK); if (!java_dyn_MethodHandle::is_instance(JNIHandles::resolve(bsm_jh))) { THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "method handle"); diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index 5ba65fba422..48b61217130 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -2593,6 +2593,12 @@ SOLARIS_ONLY( FLAG_IS_DEFAULT(UseVMInterruptibleIO)) { FLAG_SET_DEFAULT(UseVMInterruptibleIO, true); } +#ifdef LINUX + if (JDK_Version::current().compare_major(6) <= 0 && + FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) { + FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false); + } +#endif // LINUX return JNI_OK; } @@ -2659,6 +2665,28 @@ jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_req } #endif + // If we are running in a headless jre, force java.awt.headless property + // to be true unless the property has already been set. + // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state. + if (os::is_headless_jre()) { + const char* headless = Arguments::get_property("java.awt.headless"); + if (headless == NULL) { + char envbuffer[128]; + if (!os::getenv("JAVA_AWT_HEADLESS", envbuffer, sizeof(envbuffer))) { + if (!add_property("java.awt.headless=true")) { + return JNI_ENOMEM; + } + } else { + char buffer[256]; + strcpy(buffer, "java.awt.headless="); + strcat(buffer, envbuffer); + if (!add_property(buffer)) { + return JNI_ENOMEM; + } + } + } + } + if (!check_vm_args_consistency()) { return JNI_ERR; } @@ -2979,6 +3007,14 @@ jint Arguments::parse(const JavaVMInitArgs* args) { CommandLineFlags::printFlags(); } + // Apply CPU specific policy for the BiasedLocking + if (UseBiasedLocking) { + if (!VM_Version::use_biased_locking() && + !(FLAG_IS_CMDLINE(UseBiasedLocking))) { + UseBiasedLocking = false; + } + } + return JNI_OK; } diff --git a/hotspot/src/share/vm/runtime/deoptimization.cpp b/hotspot/src/share/vm/runtime/deoptimization.cpp index a0f26be2e49..2fc5edc360d 100644 --- a/hotspot/src/share/vm/runtime/deoptimization.cpp +++ b/hotspot/src/share/vm/runtime/deoptimization.cpp @@ -254,6 +254,7 @@ Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread } +#ifndef SHARK // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info. CodeBlob* cb = stub_frame.cb(); // Verify we have the right vframeArray @@ -270,6 +271,10 @@ Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread assert(cb->is_deoptimization_stub() || cb->is_uncommon_trap_stub(), "just checking"); Events::log("fetch unroll sp " INTPTR_FORMAT, unpack_sp); #endif +#else + intptr_t* unpack_sp = stub_frame.sender(&dummy_map).unextended_sp(); +#endif // !SHARK + // This is a guarantee instead of an assert because if vframe doesn't match // we will unpack the wrong deoptimized frame and wind up in strange places // where it will be very difficult to figure out what went wrong. Better @@ -380,7 +385,9 @@ Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread frame_pcs[0] = deopt_sender.raw_pc(); +#ifndef SHARK assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc"); +#endif // SHARK UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord, caller_adjustment * BytesPerWord, @@ -1073,7 +1080,7 @@ JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int by JRT_END -#ifdef COMPILER2 +#if defined(COMPILER2) || defined(SHARK) void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index, TRAPS) { // in case of an unresolved klass entry, load the class. if (constant_pool->tag_at(index).is_unresolved_klass()) { @@ -1835,7 +1842,7 @@ void Deoptimization::print_statistics() { if (xtty != NULL) xtty->tail("statistics"); } } -#else // COMPILER2 +#else // COMPILER2 || SHARK // Stubs for C1 only system. @@ -1871,4 +1878,4 @@ const char* Deoptimization::format_trap_state(char* buf, size_t buflen, return buf; } -#endif // COMPILER2 +#endif // COMPILER2 || SHARK diff --git a/hotspot/src/share/vm/runtime/frame.cpp b/hotspot/src/share/vm/runtime/frame.cpp index 9fb56f972c4..89de3ca1a99 100644 --- a/hotspot/src/share/vm/runtime/frame.cpp +++ b/hotspot/src/share/vm/runtime/frame.cpp @@ -876,6 +876,7 @@ void frame::oops_interpreted_do(OopClosure* f, const RegisterMap* map, bool quer #endif /* CC_INTERP */ +#ifndef PPC if (m->is_native()) { #ifdef CC_INTERP f->do_oop((oop*)&istate->_oop_temp); @@ -883,6 +884,11 @@ void frame::oops_interpreted_do(OopClosure* f, const RegisterMap* map, bool quer f->do_oop((oop*)( fp() + interpreter_frame_oop_temp_offset )); #endif /* CC_INTERP */ } +#else // PPC + if (m->is_native() && m->is_static()) { + f->do_oop(interpreter_frame_mirror_addr()); + } +#endif // PPC int max_locals = m->is_native() ? m->size_of_parameters() : m->max_locals(); @@ -1094,6 +1100,10 @@ void frame::oops_do_internal(OopClosure* f, CodeBlobClosure* cf, RegisterMap* ma oops_entry_do(f, map); } else if (CodeCache::contains(pc())) { oops_code_blob_do(f, cf, map); +#ifdef SHARK + } else if (is_fake_stub_frame()) { + // nothing to do +#endif // SHARK } else { ShouldNotReachHere(); } diff --git a/hotspot/src/share/vm/runtime/frame.hpp b/hotspot/src/share/vm/runtime/frame.hpp index 68f7115ec6d..4f2df2ad964 100644 --- a/hotspot/src/share/vm/runtime/frame.hpp +++ b/hotspot/src/share/vm/runtime/frame.hpp @@ -25,6 +25,7 @@ typedef class BytecodeInterpreter* interpreterState; class CodeBlob; +class vframeArray; // A frame represents a physical stack frame (an activation). Frames @@ -296,6 +297,9 @@ class frame VALUE_OBJ_CLASS_SPEC { void interpreter_frame_set_method(methodOop method); methodOop* interpreter_frame_method_addr() const; constantPoolCacheOop* interpreter_frame_cache_addr() const; +#ifdef PPC + oop* interpreter_frame_mirror_addr() const; +#endif public: // Entry frames diff --git a/hotspot/src/share/vm/runtime/globals.cpp b/hotspot/src/share/vm/runtime/globals.cpp index d172030f2db..e0603d38d6a 100644 --- a/hotspot/src/share/vm/runtime/globals.cpp +++ b/hotspot/src/share/vm/runtime/globals.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -181,6 +181,18 @@ void Flag::print_as_flag(outputStream* st) { #define C2_NOTPRODUCT_FLAG_STRUCT(type, name, value, doc) { #type, XSTR(name), &name, "{C2 notproduct}", DEFAULT }, #endif +#define SHARK_PRODUCT_FLAG_STRUCT(type, name, value, doc) { #type, XSTR(name), &name, "{Shark product}", DEFAULT }, +#define SHARK_PD_PRODUCT_FLAG_STRUCT(type, name, doc) { #type, XSTR(name), &name, "{Shark pd product}", DEFAULT }, +#define SHARK_DIAGNOSTIC_FLAG_STRUCT(type, name, value, doc) { #type, XSTR(name), &name, "{Shark diagnostic}", DEFAULT }, +#ifdef PRODUCT + #define SHARK_DEVELOP_FLAG_STRUCT(type, name, value, doc) /* flag is constant */ + #define SHARK_PD_DEVELOP_FLAG_STRUCT(type, name, doc) /* flag is constant */ + #define SHARK_NOTPRODUCT_FLAG_STRUCT(type, name, value, doc) +#else + #define SHARK_DEVELOP_FLAG_STRUCT(type, name, value, doc) { #type, XSTR(name), &name, "{Shark}", DEFAULT }, + #define SHARK_PD_DEVELOP_FLAG_STRUCT(type, name, doc) { #type, XSTR(name), &name, "{Shark pd}", DEFAULT }, + #define SHARK_NOTPRODUCT_FLAG_STRUCT(type, name, value, doc) { #type, XSTR(name), &name, "{Shark notproduct}", DEFAULT }, +#endif static Flag flagTable[] = { RUNTIME_FLAGS(RUNTIME_DEVELOP_FLAG_STRUCT, RUNTIME_PD_DEVELOP_FLAG_STRUCT, RUNTIME_PRODUCT_FLAG_STRUCT, RUNTIME_PD_PRODUCT_FLAG_STRUCT, RUNTIME_DIAGNOSTIC_FLAG_STRUCT, RUNTIME_EXPERIMENTAL_FLAG_STRUCT, RUNTIME_NOTPRODUCT_FLAG_STRUCT, RUNTIME_MANAGEABLE_FLAG_STRUCT, RUNTIME_PRODUCT_RW_FLAG_STRUCT, RUNTIME_LP64_PRODUCT_FLAG_STRUCT) @@ -193,6 +205,9 @@ static Flag flagTable[] = { #endif #ifdef COMPILER2 C2_FLAGS(C2_DEVELOP_FLAG_STRUCT, C2_PD_DEVELOP_FLAG_STRUCT, C2_PRODUCT_FLAG_STRUCT, C2_PD_PRODUCT_FLAG_STRUCT, C2_DIAGNOSTIC_FLAG_STRUCT, C2_EXPERIMENTAL_FLAG_STRUCT, C2_NOTPRODUCT_FLAG_STRUCT) +#endif +#ifdef SHARK + SHARK_FLAGS(SHARK_DEVELOP_FLAG_STRUCT, SHARK_PD_DEVELOP_FLAG_STRUCT, SHARK_PRODUCT_FLAG_STRUCT, SHARK_PD_PRODUCT_FLAG_STRUCT, SHARK_DIAGNOSTIC_FLAG_STRUCT, SHARK_NOTPRODUCT_FLAG_STRUCT) #endif {0, NULL, NULL} }; diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp index d4f84c4450e..28b26381fba 100644 --- a/hotspot/src/share/vm/runtime/globals.hpp +++ b/hotspot/src/share/vm/runtime/globals.hpp @@ -22,7 +22,7 @@ * */ -#if !defined(COMPILER1) && !defined(COMPILER2) +#if !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK) define_pd_global(bool, BackgroundCompilation, false); define_pd_global(bool, UseTLAB, false); define_pd_global(bool, CICompileOSR, false); @@ -607,7 +607,7 @@ class CommandLineFlags { notproduct(bool, PrintMallocFree, false, \ "Trace calls to C heap malloc/free allocation") \ \ - notproduct(bool, PrintOopAddress, false, \ + product(bool, PrintOopAddress, false, \ "Always print the location of the oop") \ \ notproduct(bool, VerifyCodeCacheOften, false, \ @@ -2442,6 +2442,10 @@ class CommandLineFlags { "Call fatal if this exception is thrown. Example: " \ "java -XX:AbortVMOnException=java.lang.NullPointerException Foo") \ \ + notproduct(ccstr, AbortVMOnExceptionMessage, NULL, \ + "Call fatal if the exception pointed by AbortVMOnException " \ + "has this message.") \ + \ develop(bool, DebugVtables, false, \ "add debugging code to vtable dispatch") \ \ @@ -3517,6 +3521,9 @@ class CommandLineFlags { experimental(bool, EnableInvokeDynamic, false, \ "recognize the invokedynamic instruction") \ \ + experimental(bool, AllowTransitionalJSR292, true, \ + "recognize pre-PFD formats of invokedynamic") \ + \ develop(bool, TraceInvokeDynamic, false, \ "trace internal invoke dynamic operations") \ \ @@ -3551,7 +3558,6 @@ class CommandLineFlags { "EINTR for I/O operations results in OS_INTRPT. The default value"\ " of this flag is true for JDK 6 and earliers") - /* * Macros for factoring of globals */ diff --git a/hotspot/src/share/vm/runtime/java.cpp b/hotspot/src/share/vm/runtime/java.cpp index 76048dcdad7..b831a0fcb3d 100644 --- a/hotspot/src/share/vm/runtime/java.cpp +++ b/hotspot/src/share/vm/runtime/java.cpp @@ -378,7 +378,8 @@ void before_exit(JavaThread * thread) { } // Terminate watcher thread - must before disenrolling any periodic task - WatcherThread::stop(); + if (PeriodicTask::num_tasks() > 0) + WatcherThread::stop(); // Print statistics gathered (profiling ...) if (Arguments::has_profile()) { diff --git a/hotspot/src/share/vm/runtime/javaFrameAnchor.hpp b/hotspot/src/share/vm/runtime/javaFrameAnchor.hpp index 062bceb53fc..7f99e020c8e 100644 --- a/hotspot/src/share/vm/runtime/javaFrameAnchor.hpp +++ b/hotspot/src/share/vm/runtime/javaFrameAnchor.hpp @@ -76,7 +76,6 @@ public: JavaFrameAnchor() { clear(); } JavaFrameAnchor(JavaFrameAnchor *src) { copy(src); } - address last_Java_pc(void) { return _last_Java_pc; } void set_last_Java_pc(address pc) { _last_Java_pc = pc; } // Assembly stub generation helpers diff --git a/hotspot/src/share/vm/runtime/mutexLocker.cpp b/hotspot/src/share/vm/runtime/mutexLocker.cpp index 71cbc771856..93f1e2feea0 100644 --- a/hotspot/src/share/vm/runtime/mutexLocker.cpp +++ b/hotspot/src/share/vm/runtime/mutexLocker.cpp @@ -159,6 +159,8 @@ void mutex_init() { def(STS_init_lock , Mutex, leaf, true ); if (UseConcMarkSweepGC) { def(iCMS_lock , Monitor, special, true ); // CMS incremental mode start/stop notification + } + if (UseConcMarkSweepGC || UseG1GC) { def(FullGCCount_lock , Monitor, leaf, true ); // in support of ExplicitGCInvokesConcurrent } if (UseG1GC) { diff --git a/hotspot/src/share/vm/runtime/os.cpp b/hotspot/src/share/vm/runtime/os.cpp index 31b6078f1c3..b51a6c5f30c 100644 --- a/hotspot/src/share/vm/runtime/os.cpp +++ b/hotspot/src/share/vm/runtime/os.cpp @@ -735,6 +735,152 @@ void os::print_date_and_time(outputStream *st) { st->print_cr("elapsed time: %d seconds", (int)t); } +// moved from debug.cpp (used to be find()) but still called from there +// The print_pc parameter is only set by the debug code in one case +void os::print_location(outputStream* st, intptr_t x, bool print_pc) { + address addr = (address)x; + CodeBlob* b = CodeCache::find_blob_unsafe(addr); + if (b != NULL) { + if (b->is_buffer_blob()) { + // the interpreter is generated into a buffer blob + InterpreterCodelet* i = Interpreter::codelet_containing(addr); + if (i != NULL) { + i->print_on(st); + return; + } + if (Interpreter::contains(addr)) { + st->print_cr(INTPTR_FORMAT " is pointing into interpreter code" + " (not bytecode specific)", addr); + return; + } + // + if (AdapterHandlerLibrary::contains(b)) { + st->print_cr("Printing AdapterHandler"); + AdapterHandlerLibrary::print_handler_on(st, b); + } + // the stubroutines are generated into a buffer blob + StubCodeDesc* d = StubCodeDesc::desc_for(addr); + if (d != NULL) { + d->print_on(st); + if (print_pc) st->cr(); + return; + } + if (StubRoutines::contains(addr)) { + st->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) " + "stub routine", addr); + return; + } + // the InlineCacheBuffer is using stubs generated into a buffer blob + if (InlineCacheBuffer::contains(addr)) { + st->print_cr(INTPTR_FORMAT " is pointing into InlineCacheBuffer", addr); + return; + } + VtableStub* v = VtableStubs::stub_containing(addr); + if (v != NULL) { + v->print_on(st); + return; + } + } + if (print_pc && b->is_nmethod()) { + ResourceMark rm; + st->print("%#p: Compiled ", addr); + ((nmethod*)b)->method()->print_value_on(st); + st->print(" = (CodeBlob*)" INTPTR_FORMAT, b); + st->cr(); + return; + } + if ( b->is_nmethod()) { + if (b->is_zombie()) { + st->print_cr(INTPTR_FORMAT " is zombie nmethod", b); + } else if (b->is_not_entrant()) { + st->print_cr(INTPTR_FORMAT " is non-entrant nmethod", b); + } + } + b->print_on(st); + return; + } + + if (Universe::heap()->is_in(addr)) { + HeapWord* p = Universe::heap()->block_start(addr); + bool print = false; + // If we couldn't find it it just may mean that heap wasn't parseable + // See if we were just given an oop directly + if (p != NULL && Universe::heap()->block_is_obj(p)) { + print = true; + } else if (p == NULL && ((oopDesc*)addr)->is_oop()) { + p = (HeapWord*) addr; + print = true; + } + if (print) { + oop(p)->print_on(st); + if (p != (HeapWord*)x && oop(p)->is_constMethod() && + constMethodOop(p)->contains(addr)) { + Thread *thread = Thread::current(); + HandleMark hm(thread); + methodHandle mh (thread, constMethodOop(p)->method()); + if (!mh->is_native()) { + st->print_cr("bci_from(%p) = %d; print_codes():", + addr, mh->bci_from(address(x))); + mh->print_codes_on(st); + } + } + return; + } + } else { + if (Universe::heap()->is_in_reserved(addr)) { + st->print_cr(INTPTR_FORMAT " is an unallocated location " + "in the heap", addr); + return; + } + } + if (JNIHandles::is_global_handle((jobject) addr)) { + st->print_cr(INTPTR_FORMAT " is a global jni handle", addr); + return; + } + if (JNIHandles::is_weak_global_handle((jobject) addr)) { + st->print_cr(INTPTR_FORMAT " is a weak global jni handle", addr); + return; + } +#ifndef PRODUCT + // we don't keep the block list in product mode + if (JNIHandleBlock::any_contains((jobject) addr)) { + st->print_cr(INTPTR_FORMAT " is a local jni handle", addr); + return; + } +#endif + + for(JavaThread *thread = Threads::first(); thread; thread = thread->next()) { + // Check for privilege stack + if (thread->privileged_stack_top() != NULL && + thread->privileged_stack_top()->contains(addr)) { + st->print_cr(INTPTR_FORMAT " is pointing into the privilege stack " + "for thread: " INTPTR_FORMAT, addr, thread); + thread->print_on(st); + return; + } + // If the addr is a java thread print information about that. + if (addr == (address)thread) { + thread->print_on(st); + return; + } + // If the addr is in the stack region for this thread then report that + // and print thread info + if (thread->stack_base() >= addr && + addr > (thread->stack_base() - thread->stack_size())) { + st->print_cr(INTPTR_FORMAT " is pointing into the stack for thread: " + INTPTR_FORMAT, addr, thread); + thread->print_on(st); + return; + } + + } + // Try an OS specific find + if (os::find(addr, st)) { + return; + } + + st->print_cr(INTPTR_FORMAT " is pointing to unknown location", addr); +} // Looks like all platforms except IA64 can use the same function to check // if C stack is walkable beyond current frame. The check for fp() is not diff --git a/hotspot/src/share/vm/runtime/os.hpp b/hotspot/src/share/vm/runtime/os.hpp index 4f7539167d2..b0286535d5d 100644 --- a/hotspot/src/share/vm/runtime/os.hpp +++ b/hotspot/src/share/vm/runtime/os.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -78,8 +78,10 @@ class os: AllStatic { } public: - static void init(void); // Called before command line parsing - static jint init_2(void); // Called after command line parsing + + static void init(void); // Called before command line parsing + static jint init_2(void); // Called after command line parsing + static void init_3(void); // Called at the end of vm init // File names are case-insensitive on windows only // Override me as needed @@ -322,7 +324,8 @@ class os: AllStatic { pgc_thread, // Parallel GC thread java_thread, compiler_thread, - watcher_thread + watcher_thread, + os_thread }; static bool create_thread(Thread* thread, @@ -451,6 +454,8 @@ class os: AllStatic { static void print_signal_handlers(outputStream* st, char* buf, size_t buflen); static void print_date_and_time(outputStream* st); + static void print_location(outputStream* st, intptr_t x, bool print_pc = false); + // The following two functions are used by fatal error handler to trace // native (C) frames. They are not part of frame.hpp/frame.cpp because // frame.hpp/cpp assume thread is JavaThread, and also because different @@ -480,6 +485,9 @@ class os: AllStatic { // Fills in path to jvm.dll/libjvm.so (this info used to find hpi). static void jvm_path(char *buf, jint buflen); + // Returns true if we are running in a headless jre. + static bool is_headless_jre(); + // JNI names static void print_jni_name_prefix_on(outputStream* st, int args_size); static void print_jni_name_suffix_on(outputStream* st, int args_size); @@ -580,8 +588,8 @@ class os: AllStatic { // Platform dependent stuff #include "incls/_os_pd.hpp.incl" - // debugging support (mostly used by debug.cpp) - static bool find(address pc) PRODUCT_RETURN0; // OS specific function to make sense out of an address + // debugging support (mostly used by debug.cpp but also fatal error handler) + static bool find(address pc, outputStream* st = tty); // OS specific function to make sense out of an address static bool dont_yield(); // when true, JVM_Yield() is nop static void print_statistics(); diff --git a/hotspot/src/share/vm/runtime/sharedRuntime.cpp b/hotspot/src/share/vm/runtime/sharedRuntime.cpp index a059585ce4b..4ff5aa0fa88 100644 --- a/hotspot/src/share/vm/runtime/sharedRuntime.cpp +++ b/hotspot/src/share/vm/runtime/sharedRuntime.cpp @@ -191,6 +191,121 @@ JRT_LEAF(jdouble, SharedRuntime::drem(jdouble x, jdouble y)) return ((jdouble)fmod((double)x,(double)y)); JRT_END +#ifdef __SOFTFP__ +JRT_LEAF(jfloat, SharedRuntime::fadd(jfloat x, jfloat y)) + return x + y; +JRT_END + +JRT_LEAF(jfloat, SharedRuntime::fsub(jfloat x, jfloat y)) + return x - y; +JRT_END + +JRT_LEAF(jfloat, SharedRuntime::fmul(jfloat x, jfloat y)) + return x * y; +JRT_END + +JRT_LEAF(jfloat, SharedRuntime::fdiv(jfloat x, jfloat y)) + return x / y; +JRT_END + +JRT_LEAF(jdouble, SharedRuntime::dadd(jdouble x, jdouble y)) + return x + y; +JRT_END + +JRT_LEAF(jdouble, SharedRuntime::dsub(jdouble x, jdouble y)) + return x - y; +JRT_END + +JRT_LEAF(jdouble, SharedRuntime::dmul(jdouble x, jdouble y)) + return x * y; +JRT_END + +JRT_LEAF(jdouble, SharedRuntime::ddiv(jdouble x, jdouble y)) + return x / y; +JRT_END + +JRT_LEAF(jfloat, SharedRuntime::i2f(jint x)) + return (jfloat)x; +JRT_END + +JRT_LEAF(jdouble, SharedRuntime::i2d(jint x)) + return (jdouble)x; +JRT_END + +JRT_LEAF(jdouble, SharedRuntime::f2d(jfloat x)) + return (jdouble)x; +JRT_END + +JRT_LEAF(int, SharedRuntime::fcmpl(float x, float y)) + return x>y ? 1 : (x==y ? 0 : -1); /* xy or is_nan */ +JRT_END + +JRT_LEAF(int, SharedRuntime::dcmpl(double x, double y)) + return x>y ? 1 : (x==y ? 0 : -1); /* xy or is_nan */ +JRT_END + +// Functions to return the opposite of the aeabi functions for nan. +JRT_LEAF(int, SharedRuntime::unordered_fcmplt(float x, float y)) + return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); +JRT_END + +JRT_LEAF(int, SharedRuntime::unordered_dcmplt(double x, double y)) + return (x < y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); +JRT_END + +JRT_LEAF(int, SharedRuntime::unordered_fcmple(float x, float y)) + return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); +JRT_END + +JRT_LEAF(int, SharedRuntime::unordered_dcmple(double x, double y)) + return (x <= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); +JRT_END + +JRT_LEAF(int, SharedRuntime::unordered_fcmpge(float x, float y)) + return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); +JRT_END + +JRT_LEAF(int, SharedRuntime::unordered_dcmpge(double x, double y)) + return (x >= y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); +JRT_END + +JRT_LEAF(int, SharedRuntime::unordered_fcmpgt(float x, float y)) + return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); +JRT_END + +JRT_LEAF(int, SharedRuntime::unordered_dcmpgt(double x, double y)) + return (x > y) ? 1 : ((g_isnan(x) || g_isnan(y)) ? 1 : 0); +JRT_END + +// Intrinsics make gcc generate code for these. +float SharedRuntime::fneg(float f) { + return -f; +} + +double SharedRuntime::dneg(double f) { + return -f; +} + +#endif // __SOFTFP__ + +#if defined(__SOFTFP__) || defined(E500V2) +// Intrinsics make gcc generate code for these. +double SharedRuntime::dabs(double f) { + return (f <= (double)0.0) ? (double)0.0 - f : f; +} + +double SharedRuntime::dsqrt(double f) { + return sqrt(f); +} +#endif JRT_LEAF(jint, SharedRuntime::f2i(jfloat x)) if (g_isnan(x)) @@ -2046,6 +2161,8 @@ int AdapterHandlerTable::_equals; int AdapterHandlerTable::_hits; int AdapterHandlerTable::_compact; +#endif + class AdapterHandlerTableIterator : public StackObj { private: AdapterHandlerTable* _table; @@ -2081,7 +2198,6 @@ class AdapterHandlerTableIterator : public StackObj { } } }; -#endif // --------------------------------------------------------------------------- @@ -2619,7 +2735,6 @@ JRT_LEAF(void, SharedRuntime::OSR_migration_end( intptr_t* buf) ) FREE_C_HEAP_ARRAY(intptr_t,buf); JRT_END -#ifndef PRODUCT bool AdapterHandlerLibrary::contains(CodeBlob* b) { AdapterHandlerTableIterator iter(_adapters); while (iter.has_next()) { @@ -2629,21 +2744,24 @@ bool AdapterHandlerLibrary::contains(CodeBlob* b) { return false; } -void AdapterHandlerLibrary::print_handler(CodeBlob* b) { +void AdapterHandlerLibrary::print_handler_on(outputStream* st, CodeBlob* b) { AdapterHandlerTableIterator iter(_adapters); while (iter.has_next()) { AdapterHandlerEntry* a = iter.next(); if ( b == CodeCache::find_blob(a->get_i2c_entry()) ) { - tty->print("Adapter for signature: "); - tty->print_cr("%s i2c: " INTPTR_FORMAT " c2i: " INTPTR_FORMAT " c2iUV: " INTPTR_FORMAT, - a->fingerprint()->as_string(), - a->get_i2c_entry(), a->get_c2i_entry(), a->get_c2i_unverified_entry()); + st->print("Adapter for signature: "); + st->print_cr("%s i2c: " INTPTR_FORMAT " c2i: " INTPTR_FORMAT " c2iUV: " INTPTR_FORMAT, + a->fingerprint()->as_string(), + a->get_i2c_entry(), a->get_c2i_entry(), a->get_c2i_unverified_entry()); + return; } } assert(false, "Should have found handler"); } +#ifndef PRODUCT + void AdapterHandlerLibrary::print_statistics() { _adapters->print_statistics(); } diff --git a/hotspot/src/share/vm/runtime/sharedRuntime.hpp b/hotspot/src/share/vm/runtime/sharedRuntime.hpp index 00b486b24ca..bd5031e49a4 100644 --- a/hotspot/src/share/vm/runtime/sharedRuntime.hpp +++ b/hotspot/src/share/vm/runtime/sharedRuntime.hpp @@ -78,6 +78,18 @@ class SharedRuntime: AllStatic { static jfloat frem(jfloat x, jfloat y); static jdouble drem(jdouble x, jdouble y); +#ifdef __SOFTFP__ + static jfloat fadd(jfloat x, jfloat y); + static jfloat fsub(jfloat x, jfloat y); + static jfloat fmul(jfloat x, jfloat y); + static jfloat fdiv(jfloat x, jfloat y); + + static jdouble dadd(jdouble x, jdouble y); + static jdouble dsub(jdouble x, jdouble y); + static jdouble dmul(jdouble x, jdouble y); + static jdouble ddiv(jdouble x, jdouble y); +#endif // __SOFTFP__ + // float conversion (needs to set appropriate rounding mode) static jint f2i (jfloat x); static jlong f2l (jfloat x); @@ -87,6 +99,12 @@ class SharedRuntime: AllStatic { static jfloat l2f (jlong x); static jdouble l2d (jlong x); +#ifdef __SOFTFP__ + static jfloat i2f (jint x); + static jdouble i2d (jint x); + static jdouble f2d (jfloat x); +#endif // __SOFTFP__ + // double trigonometrics and transcendentals static jdouble dsin(jdouble x); static jdouble dcos(jdouble x); @@ -96,6 +114,32 @@ class SharedRuntime: AllStatic { static jdouble dexp(jdouble x); static jdouble dpow(jdouble x, jdouble y); +#if defined(__SOFTFP__) || defined(E500V2) + static double dabs(double f); + static double dsqrt(double f); +#endif + +#ifdef __SOFTFP__ + // C++ compiler generates soft float instructions as well as passing + // float and double in registers. + static int fcmpl(float x, float y); + static int fcmpg(float x, float y); + static int dcmpl(double x, double y); + static int dcmpg(double x, double y); + + static int unordered_fcmplt(float x, float y); + static int unordered_dcmplt(double x, double y); + static int unordered_fcmple(float x, float y); + static int unordered_dcmple(double x, double y); + static int unordered_fcmpge(float x, float y); + static int unordered_dcmpge(double x, double y); + static int unordered_fcmpgt(float x, float y); + static int unordered_dcmpgt(double x, double y); + + static float fneg(float f); + static double dneg(double f); +#endif + // exception handling across interpreter/compiler boundaries static address raw_exception_handler_for_return_address(JavaThread* thread, address return_address); static address exception_handler_for_return_address(JavaThread* thread, address return_address); @@ -585,9 +629,7 @@ class AdapterHandlerEntry : public BasicHashtableEntry { bool compare_code(unsigned char* code, int length, int total_args_passed, BasicType* sig_bt); #endif -#ifndef PRODUCT void print(); -#endif /* PRODUCT */ }; class AdapterHandlerLibrary: public AllStatic { @@ -609,9 +651,10 @@ class AdapterHandlerLibrary: public AllStatic { static nmethod* create_dtrace_nmethod (methodHandle method); #endif // HAVE_DTRACE_H -#ifndef PRODUCT - static void print_handler(CodeBlob* b); + static void print_handler(CodeBlob* b) { print_handler_on(tty, b); } + static void print_handler_on(outputStream* st, CodeBlob* b); static bool contains(CodeBlob* b); +#ifndef PRODUCT static void print_statistics(); #endif /* PRODUCT */ diff --git a/hotspot/src/share/vm/runtime/sharedRuntimeTrans.cpp b/hotspot/src/share/vm/runtime/sharedRuntimeTrans.cpp index 69fd010532b..d507290d77e 100644 --- a/hotspot/src/share/vm/runtime/sharedRuntimeTrans.cpp +++ b/hotspot/src/share/vm/runtime/sharedRuntimeTrans.cpp @@ -572,7 +572,11 @@ double __ieee754_pow(double x, double y) { if(hy<0) z = one/z; /* z = (1/|x|) */ if(hx<0) { if(((ix-0x3ff00000)|yisint)==0) { +#ifdef CAN_USE_NAN_DEFINE + z = NAN; +#else z = (z-z)/(z-z); /* (-1)**non-int is NaN */ +#endif } else if(yisint==1) z = -1.0*z; /* (x<0)**odd = -(|x|**odd) */ } @@ -583,7 +587,12 @@ double __ieee754_pow(double x, double y) { n = (hx>>31)+1; /* (x<0)**(non-int) is NaN */ - if((n|yisint)==0) return (x-x)/(x-x); + if((n|yisint)==0) +#ifdef CAN_USE_NAN_DEFINE + return NAN; +#else + return (x-x)/(x-x); +#endif s = one; /* s (sign of result -ve**odd) = -1 else = 1 */ if((n|(yisint-1))==0) s = -one;/* (-ve)**(odd int) */ diff --git a/hotspot/src/share/vm/runtime/signature.hpp b/hotspot/src/share/vm/runtime/signature.hpp index e0635a13727..00c3bceec10 100644 --- a/hotspot/src/share/vm/runtime/signature.hpp +++ b/hotspot/src/share/vm/runtime/signature.hpp @@ -275,11 +275,7 @@ class NativeSignatureIterator: public SignatureIterator { void do_bool () { pass_int(); _jni_offset++; _offset++; } void do_char () { pass_int(); _jni_offset++; _offset++; } -#if defined(_LP64) || defined(ZERO) void do_float () { pass_float(); _jni_offset++; _offset++; } -#else - void do_float () { pass_int(); _jni_offset++; _offset++; } -#endif #ifdef _LP64 void do_double() { pass_double(); _jni_offset++; _offset += 2; } #else @@ -306,9 +302,7 @@ class NativeSignatureIterator: public SignatureIterator { virtual void pass_int() = 0; virtual void pass_long() = 0; virtual void pass_object() = 0; -#if defined(_LP64) || defined(ZERO) virtual void pass_float() = 0; -#endif #ifdef _LP64 virtual void pass_double() = 0; #else diff --git a/hotspot/src/share/vm/runtime/stubCodeGenerator.cpp b/hotspot/src/share/vm/runtime/stubCodeGenerator.cpp index f9983e1c1f9..e5215dc2b43 100644 --- a/hotspot/src/share/vm/runtime/stubCodeGenerator.cpp +++ b/hotspot/src/share/vm/runtime/stubCodeGenerator.cpp @@ -53,15 +53,13 @@ const char* StubCodeDesc::name_for(address pc) { } -void StubCodeDesc::print() { - tty->print(group()); - tty->print("::"); - tty->print(name()); - tty->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT "[ (%d bytes)", begin(), end(), size_in_bytes()); +void StubCodeDesc::print_on(outputStream* st) const { + st->print(group()); + st->print("::"); + st->print(name()); + st->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT "[ (%d bytes)", begin(), end(), size_in_bytes()); } - - // Implementation of StubCodeGenerator StubCodeGenerator::StubCodeGenerator(CodeBuffer* code) { diff --git a/hotspot/src/share/vm/runtime/stubCodeGenerator.hpp b/hotspot/src/share/vm/runtime/stubCodeGenerator.hpp index 96a6761695b..f47f0dbffd4 100644 --- a/hotspot/src/share/vm/runtime/stubCodeGenerator.hpp +++ b/hotspot/src/share/vm/runtime/stubCodeGenerator.hpp @@ -79,7 +79,8 @@ class StubCodeDesc: public CHeapObj { address end() const { return _end; } int size_in_bytes() const { return _end - _begin; } bool contains(address pc) const { return _begin <= pc && pc < _end; } - void print(); + void print_on(outputStream* st) const; + void print() const { print_on(tty); } }; // The base class for all stub-generating code generators. diff --git a/hotspot/src/share/vm/runtime/thread.cpp b/hotspot/src/share/vm/runtime/thread.cpp index f729a387a34..35afb6fe6b5 100644 --- a/hotspot/src/share/vm/runtime/thread.cpp +++ b/hotspot/src/share/vm/runtime/thread.cpp @@ -807,7 +807,7 @@ bool Thread::is_in_stack(address adr) const { // should be revisited, and they should be removed if possible. bool Thread::is_lock_owned(address adr) const { - return (_stack_base >= adr && adr >= (_stack_base - _stack_size)); + return on_local_stack(adr); } bool Thread::set_as_starting_thread() { @@ -1020,7 +1020,7 @@ void NamedThread::set_name(const char* format, ...) { // timer interrupts exists on the platform. WatcherThread* WatcherThread::_watcher_thread = NULL; -bool WatcherThread::_should_terminate = false; +volatile bool WatcherThread::_should_terminate = false; WatcherThread::WatcherThread() : Thread() { assert(watcher_thread() == NULL, "we can only allocate one WatcherThread"); @@ -1052,8 +1052,26 @@ void WatcherThread::run() { // Calculate how long it'll be until the next PeriodicTask work // should be done, and sleep that amount of time. - const size_t time_to_wait = PeriodicTask::time_to_wait(); - os::sleep(this, time_to_wait, false); + size_t time_to_wait = PeriodicTask::time_to_wait(); + + // we expect this to timeout - we only ever get unparked when + // we should terminate + { + OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */); + + jlong prev_time = os::javaTimeNanos(); + for (;;) { + int res= _SleepEvent->park(time_to_wait); + if (res == OS_TIMEOUT || _should_terminate) + break; + // spurious wakeup of some kind + jlong now = os::javaTimeNanos(); + time_to_wait -= (now - prev_time) / 1000000; + if (time_to_wait <= 0) + break; + prev_time = now; + } + } if (is_error_reported()) { // A fatal error has happened, the error handler(VMError::report_and_die) @@ -1115,6 +1133,12 @@ void WatcherThread::stop() { // it is ok to take late safepoints here, if needed MutexLocker mu(Terminator_lock); _should_terminate = true; + OrderAccess::fence(); // ensure WatcherThread sees update in main loop + + Thread* watcher = watcher_thread(); + if (watcher != NULL) + watcher->_SleepEvent->unpark(); + while(watcher_thread() != NULL) { // This wait should make safepoint checks, wait without a timeout, // and wait as a suspend-equivalent condition. @@ -1364,6 +1388,8 @@ void JavaThread::run() { this->create_stack_guard_pages(); + this->cache_global_variables(); + // Thread is now sufficient initialized to be handled by the safepoint code as being // in the VM. Change thread state from _thread_new to _thread_in_vm ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm); @@ -2955,6 +2981,9 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { return status; } + // Should be done after the heap is fully created + main_thread->cache_global_variables(); + HandleMark hm; { MutexLocker mu(Threads_lock); @@ -3230,6 +3259,9 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { WatcherThread::start(); } + // Give os specific code one last chance to start + os::init_3(); + create_vm_timer.end(); return JNI_OK; } @@ -3249,12 +3281,18 @@ static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, const char *on_load_sym char buffer[JVM_MAXPATHLEN]; char ebuf[1024]; const char *name = agent->name(); + const char *msg = "Could not find agent library "; if (agent->is_absolute_path()) { library = hpi::dll_load(name, ebuf, sizeof ebuf); if (library == NULL) { + const char *sub_msg = " in absolute path, with error: "; + size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1; + char *buf = NEW_C_HEAP_ARRAY(char, len); + jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); // If we can't find the agent, exit. - vm_exit_during_initialization("Could not find agent library in absolute path", name); + vm_exit_during_initialization(buf, NULL); + FREE_C_HEAP_ARRAY(char, buf); } } else { // Try to load the agent from the standard dll directory @@ -3267,17 +3305,17 @@ static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, const char *on_load_sym char *home = Arguments::get_java_home(); const char *fmt = "%s/bin/java %s -Dkernel.background.download=false" " sun.jkernel.DownloadManager -download client_jvm"; - int length = strlen(props) + strlen(home) + strlen(fmt) + 1; - char *cmd = AllocateHeap(length); + size_t length = strlen(props) + strlen(home) + strlen(fmt) + 1; + char *cmd = NEW_C_HEAP_ARRAY(char, length); jio_snprintf(cmd, length, fmt, home, props); int status = os::fork_and_exec(cmd); FreeHeap(props); - FreeHeap(cmd); if (status == -1) { warning(cmd); vm_exit_during_initialization("fork_and_exec failed: %s", strerror(errno)); } + FREE_C_HEAP_ARRAY(char, cmd); // when this comes back the instrument.dll should be where it belongs. library = hpi::dll_load(buffer, ebuf, sizeof ebuf); } @@ -3287,8 +3325,13 @@ static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, const char *on_load_sym hpi::dll_build_name(buffer, sizeof(buffer), ns, name); library = hpi::dll_load(buffer, ebuf, sizeof ebuf); if (library == NULL) { + const char *sub_msg = " on the library path, with error: "; + size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1; + char *buf = NEW_C_HEAP_ARRAY(char, len); + jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); // If we can't find the agent, exit. - vm_exit_during_initialization("Could not find agent library on the library path or in the local directory", name); + vm_exit_during_initialization(buf, NULL); + FREE_C_HEAP_ARRAY(char, buf); } } } diff --git a/hotspot/src/share/vm/runtime/thread.hpp b/hotspot/src/share/vm/runtime/thread.hpp index 323bb604c41..61237f41323 100644 --- a/hotspot/src/share/vm/runtime/thread.hpp +++ b/hotspot/src/share/vm/runtime/thread.hpp @@ -410,9 +410,6 @@ public: // Sweeper support void nmethods_do(CodeBlobClosure* cf); - // Tells if adr belong to this thread. This is used - // for checking if a lock is owned by the running thread. - // Used by fast lock support virtual bool is_lock_owned(address adr) const; @@ -449,6 +446,11 @@ public: void set_stack_size(size_t size) { _stack_size = size; } void record_stack_base_and_size(); + bool on_local_stack(address adr) const { + /* QQQ this has knowledge of direction, ought to be a stack method */ + return (_stack_base >= adr && adr >= (_stack_base - _stack_size)); + } + int lgrp_id() const { return _lgrp_id; } void set_lgrp_id(int value) { _lgrp_id = value; } @@ -609,7 +611,7 @@ class WatcherThread: public Thread { private: static WatcherThread* _watcher_thread; - static bool _should_terminate; + volatile static bool _should_terminate; // updated without holding lock public: enum SomeConstants { delay_interval = 10 // interrupt delay in milliseconds @@ -839,6 +841,10 @@ class JavaThread: public Thread { return (struct JNINativeInterface_ *)_jni_environment.functions; } + // This function is called at thread creation to allow + // platform specific thread variables to be initialized. + void cache_global_variables(); + // Executes Shutdown.shutdown() void invoke_shutdown_hooks(); diff --git a/hotspot/src/share/vm/runtime/vm_version.cpp b/hotspot/src/share/vm/runtime/vm_version.cpp index 8639a1d442f..30dada5e07a 100644 --- a/hotspot/src/share/vm/runtime/vm_version.cpp +++ b/hotspot/src/share/vm/runtime/vm_version.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -95,7 +95,11 @@ void Abstract_VM_Version::initialize() { #define VMTYPE "Server" #else // TIERED #ifdef ZERO +#ifdef SHARK + #define VMTYPE "Shark" +#else // SHARK #define VMTYPE "Zero" +#endif // SHARK #else // ZERO #define VMTYPE COMPILER1_PRESENT("Client") \ COMPILER2_PRESENT("Server") @@ -152,6 +156,8 @@ const char* Abstract_VM_Version::vm_release() { #define CPU IA32_ONLY("x86") \ IA64_ONLY("ia64") \ AMD64_ONLY("amd64") \ + ARM_ONLY("arm") \ + PPC_ONLY("ppc") \ SPARC_ONLY("sparc") #endif // ZERO diff --git a/hotspot/src/share/vm/runtime/vm_version.hpp b/hotspot/src/share/vm/runtime/vm_version.hpp index 9cfd88be12b..d012786ba8d 100644 --- a/hotspot/src/share/vm/runtime/vm_version.hpp +++ b/hotspot/src/share/vm/runtime/vm_version.hpp @@ -70,6 +70,9 @@ class Abstract_VM_Version: AllStatic { return _logical_processors_per_package; } + // ARCH specific policy for the BiasedLocking + static bool use_biased_locking() { return true; } + // Number of page sizes efficiently supported by the hardware. Most chips now // support two sizes, thus this default implementation. Processor-specific // subclasses should define new versions to hide this one as needed. Note diff --git a/hotspot/src/share/vm/shark/llvmHeaders.hpp b/hotspot/src/share/vm/shark/llvmHeaders.hpp new file mode 100644 index 00000000000..5bd71adc8e2 --- /dev/null +++ b/hotspot/src/share/vm/shark/llvmHeaders.hpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * 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. + * + */ + +#ifdef assert + #undef assert +#endif + +#ifdef DEBUG + #define SHARK_DEBUG + #undef DEBUG +#endif + +#include +#include +#include +#include +#include +#include +#include +#if SHARK_LLVM_VERSION < 27 +#include +#endif +#include +#include +#include +#include +#include +#include +#if SHARK_LLVM_VERSION >= 27 +#include +#include +#include +#include +#endif + +#include + +#ifdef assert + #undef assert +#endif + +// from hotspot/src/share/vm/utilities/debug.hpp +#ifdef ASSERT +#ifndef USE_REPEATED_ASSERTS +#define assert(p, msg) \ +do { \ + if (!(p)) { \ + report_vm_error(__FILE__, __LINE__, "assert(" #p ") failed", msg); \ + BREAKPOINT; \ + } \ +} while (0) +#else // #ifndef USE_REPEATED_ASSERTS +#define assert(p, msg) +do { \ + for (int __i = 0; __i < AssertRepeat; __i++) { \ + if (!(p)) { \ + report_vm_error(__FILE__, __LINE__, "assert(" #p ") failed", msg); \ + BREAKPOINT; \ + } \ + } \ +} while (0) +#endif // #ifndef USE_REPEATED_ASSERTS +#else + #define assert(p, msg) +#endif + +#ifdef DEBUG + #undef DEBUG +#endif +#ifdef SHARK_DEBUG + #define DEBUG + #undef SHARK_DEBUG +#endif diff --git a/hotspot/src/share/vm/shark/llvmValue.hpp b/hotspot/src/share/vm/shark/llvmValue.hpp new file mode 100644 index 00000000000..4088858b644 --- /dev/null +++ b/hotspot/src/share/vm/shark/llvmValue.hpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * 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. + * + */ + +class LLVMValue : public AllStatic { + public: + static llvm::ConstantInt* jbyte_constant(jbyte value) + { + return llvm::ConstantInt::get(SharkType::jbyte_type(), value, true); + } + static llvm::ConstantInt* jint_constant(jint value) + { + return llvm::ConstantInt::get(SharkType::jint_type(), value, true); + } + static llvm::ConstantInt* jlong_constant(jlong value) + { + return llvm::ConstantInt::get(SharkType::jlong_type(), value, true); + } + static llvm::ConstantFP* jfloat_constant(jfloat value) + { + return llvm::ConstantFP::get(SharkContext::current(), llvm::APFloat(value)); + } + static llvm::ConstantFP* jdouble_constant(jdouble value) + { + return llvm::ConstantFP::get(SharkContext::current(), llvm::APFloat(value)); + } + static llvm::ConstantPointerNull* null() + { + return llvm::ConstantPointerNull::get(SharkType::oop_type()); + } + + public: + static llvm::ConstantInt* bit_constant(int value) + { + return llvm::ConstantInt::get(SharkType::bit_type(), value, false); + } + static llvm::ConstantInt* intptr_constant(intptr_t value) + { + return llvm::ConstantInt::get(SharkType::intptr_type(), value, false); + } +}; diff --git a/hotspot/src/share/vm/shark/sharkBlock.cpp b/hotspot/src/share/vm/shark/sharkBlock.cpp new file mode 100644 index 00000000000..4f0f437bbdc --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkBlock.cpp @@ -0,0 +1,1260 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkBlock.cpp.incl" + +using namespace llvm; + +void SharkBlock::parse_bytecode(int start, int limit) { + SharkValue *a, *b, *c, *d; + int i; + + // Ensure the current state is initialized before we emit any code, + // so that any setup code for the state is at the start of the block + current_state(); + + // Parse the bytecodes + iter()->reset_to_bci(start); + while (iter()->next_bci() < limit) { + NOT_PRODUCT(a = b = c = d = NULL); + iter()->next(); + + if (SharkTraceBytecodes) + tty->print_cr("%4d: %s", bci(), Bytecodes::name(bc())); + + if (has_trap() && trap_bci() == bci()) { + do_trap(trap_request()); + return; + } + + if (UseLoopSafepoints) { + // XXX if a lcmp is followed by an if_?? then C2 maybe-inserts + // the safepoint before the lcmp rather than before the if. + // Maybe we should do this too. See parse2.cpp for details. + switch (bc()) { + case Bytecodes::_goto: + case Bytecodes::_ifnull: + case Bytecodes::_ifnonnull: + case Bytecodes::_if_acmpeq: + case Bytecodes::_if_acmpne: + case Bytecodes::_ifeq: + case Bytecodes::_ifne: + case Bytecodes::_iflt: + case Bytecodes::_ifle: + case Bytecodes::_ifgt: + case Bytecodes::_ifge: + case Bytecodes::_if_icmpeq: + case Bytecodes::_if_icmpne: + case Bytecodes::_if_icmplt: + case Bytecodes::_if_icmple: + case Bytecodes::_if_icmpgt: + case Bytecodes::_if_icmpge: + if (iter()->get_dest() <= bci()) + maybe_add_backedge_safepoint(); + break; + + case Bytecodes::_goto_w: + if (iter()->get_far_dest() <= bci()) + maybe_add_backedge_safepoint(); + break; + + case Bytecodes::_tableswitch: + case Bytecodes::_lookupswitch: + if (switch_default_dest() <= bci()) { + maybe_add_backedge_safepoint(); + break; + } + int len = switch_table_length(); + for (int i = 0; i < len; i++) { + if (switch_dest(i) <= bci()) { + maybe_add_backedge_safepoint(); + break; + } + } + break; + } + } + + switch (bc()) { + case Bytecodes::_nop: + break; + + case Bytecodes::_aconst_null: + push(SharkValue::null()); + break; + + case Bytecodes::_iconst_m1: + push(SharkValue::jint_constant(-1)); + break; + case Bytecodes::_iconst_0: + push(SharkValue::jint_constant(0)); + break; + case Bytecodes::_iconst_1: + push(SharkValue::jint_constant(1)); + break; + case Bytecodes::_iconst_2: + push(SharkValue::jint_constant(2)); + break; + case Bytecodes::_iconst_3: + push(SharkValue::jint_constant(3)); + break; + case Bytecodes::_iconst_4: + push(SharkValue::jint_constant(4)); + break; + case Bytecodes::_iconst_5: + push(SharkValue::jint_constant(5)); + break; + + case Bytecodes::_lconst_0: + push(SharkValue::jlong_constant(0)); + break; + case Bytecodes::_lconst_1: + push(SharkValue::jlong_constant(1)); + break; + + case Bytecodes::_fconst_0: + push(SharkValue::jfloat_constant(0)); + break; + case Bytecodes::_fconst_1: + push(SharkValue::jfloat_constant(1)); + break; + case Bytecodes::_fconst_2: + push(SharkValue::jfloat_constant(2)); + break; + + case Bytecodes::_dconst_0: + push(SharkValue::jdouble_constant(0)); + break; + case Bytecodes::_dconst_1: + push(SharkValue::jdouble_constant(1)); + break; + + case Bytecodes::_bipush: + push(SharkValue::jint_constant(iter()->get_constant_u1())); + break; + case Bytecodes::_sipush: + push(SharkValue::jint_constant(iter()->get_constant_u2())); + break; + + case Bytecodes::_ldc: + case Bytecodes::_ldc_w: + case Bytecodes::_ldc2_w: + push(SharkConstant::for_ldc(iter())->value(builder())); + break; + + case Bytecodes::_iload_0: + case Bytecodes::_lload_0: + case Bytecodes::_fload_0: + case Bytecodes::_dload_0: + case Bytecodes::_aload_0: + push(local(0)); + break; + case Bytecodes::_iload_1: + case Bytecodes::_lload_1: + case Bytecodes::_fload_1: + case Bytecodes::_dload_1: + case Bytecodes::_aload_1: + push(local(1)); + break; + case Bytecodes::_iload_2: + case Bytecodes::_lload_2: + case Bytecodes::_fload_2: + case Bytecodes::_dload_2: + case Bytecodes::_aload_2: + push(local(2)); + break; + case Bytecodes::_iload_3: + case Bytecodes::_lload_3: + case Bytecodes::_fload_3: + case Bytecodes::_dload_3: + case Bytecodes::_aload_3: + push(local(3)); + break; + case Bytecodes::_iload: + case Bytecodes::_lload: + case Bytecodes::_fload: + case Bytecodes::_dload: + case Bytecodes::_aload: + push(local(iter()->get_index())); + break; + + case Bytecodes::_baload: + do_aload(T_BYTE); + break; + case Bytecodes::_caload: + do_aload(T_CHAR); + break; + case Bytecodes::_saload: + do_aload(T_SHORT); + break; + case Bytecodes::_iaload: + do_aload(T_INT); + break; + case Bytecodes::_laload: + do_aload(T_LONG); + break; + case Bytecodes::_faload: + do_aload(T_FLOAT); + break; + case Bytecodes::_daload: + do_aload(T_DOUBLE); + break; + case Bytecodes::_aaload: + do_aload(T_OBJECT); + break; + + case Bytecodes::_istore_0: + case Bytecodes::_lstore_0: + case Bytecodes::_fstore_0: + case Bytecodes::_dstore_0: + case Bytecodes::_astore_0: + set_local(0, pop()); + break; + case Bytecodes::_istore_1: + case Bytecodes::_lstore_1: + case Bytecodes::_fstore_1: + case Bytecodes::_dstore_1: + case Bytecodes::_astore_1: + set_local(1, pop()); + break; + case Bytecodes::_istore_2: + case Bytecodes::_lstore_2: + case Bytecodes::_fstore_2: + case Bytecodes::_dstore_2: + case Bytecodes::_astore_2: + set_local(2, pop()); + break; + case Bytecodes::_istore_3: + case Bytecodes::_lstore_3: + case Bytecodes::_fstore_3: + case Bytecodes::_dstore_3: + case Bytecodes::_astore_3: + set_local(3, pop()); + break; + case Bytecodes::_istore: + case Bytecodes::_lstore: + case Bytecodes::_fstore: + case Bytecodes::_dstore: + case Bytecodes::_astore: + set_local(iter()->get_index(), pop()); + break; + + case Bytecodes::_bastore: + do_astore(T_BYTE); + break; + case Bytecodes::_castore: + do_astore(T_CHAR); + break; + case Bytecodes::_sastore: + do_astore(T_SHORT); + break; + case Bytecodes::_iastore: + do_astore(T_INT); + break; + case Bytecodes::_lastore: + do_astore(T_LONG); + break; + case Bytecodes::_fastore: + do_astore(T_FLOAT); + break; + case Bytecodes::_dastore: + do_astore(T_DOUBLE); + break; + case Bytecodes::_aastore: + do_astore(T_OBJECT); + break; + + case Bytecodes::_pop: + xpop(); + break; + case Bytecodes::_pop2: + xpop(); + xpop(); + break; + case Bytecodes::_swap: + a = xpop(); + b = xpop(); + xpush(a); + xpush(b); + break; + case Bytecodes::_dup: + a = xpop(); + xpush(a); + xpush(a); + break; + case Bytecodes::_dup_x1: + a = xpop(); + b = xpop(); + xpush(a); + xpush(b); + xpush(a); + break; + case Bytecodes::_dup_x2: + a = xpop(); + b = xpop(); + c = xpop(); + xpush(a); + xpush(c); + xpush(b); + xpush(a); + break; + case Bytecodes::_dup2: + a = xpop(); + b = xpop(); + xpush(b); + xpush(a); + xpush(b); + xpush(a); + break; + case Bytecodes::_dup2_x1: + a = xpop(); + b = xpop(); + c = xpop(); + xpush(b); + xpush(a); + xpush(c); + xpush(b); + xpush(a); + break; + case Bytecodes::_dup2_x2: + a = xpop(); + b = xpop(); + c = xpop(); + d = xpop(); + xpush(b); + xpush(a); + xpush(d); + xpush(c); + xpush(b); + xpush(a); + break; + + case Bytecodes::_arraylength: + do_arraylength(); + break; + + case Bytecodes::_getfield: + do_getfield(); + break; + case Bytecodes::_getstatic: + do_getstatic(); + break; + case Bytecodes::_putfield: + do_putfield(); + break; + case Bytecodes::_putstatic: + do_putstatic(); + break; + + case Bytecodes::_iadd: + b = pop(); + a = pop(); + push(SharkValue::create_jint( + builder()->CreateAdd(a->jint_value(), b->jint_value()), false)); + break; + case Bytecodes::_isub: + b = pop(); + a = pop(); + push(SharkValue::create_jint( + builder()->CreateSub(a->jint_value(), b->jint_value()), false)); + break; + case Bytecodes::_imul: + b = pop(); + a = pop(); + push(SharkValue::create_jint( + builder()->CreateMul(a->jint_value(), b->jint_value()), false)); + break; + case Bytecodes::_idiv: + do_idiv(); + break; + case Bytecodes::_irem: + do_irem(); + break; + case Bytecodes::_ineg: + a = pop(); + push(SharkValue::create_jint( + builder()->CreateNeg(a->jint_value()), a->zero_checked())); + break; + case Bytecodes::_ishl: + b = pop(); + a = pop(); + push(SharkValue::create_jint( + builder()->CreateShl( + a->jint_value(), + builder()->CreateAnd( + b->jint_value(), LLVMValue::jint_constant(0x1f))), false)); + break; + case Bytecodes::_ishr: + b = pop(); + a = pop(); + push(SharkValue::create_jint( + builder()->CreateAShr( + a->jint_value(), + builder()->CreateAnd( + b->jint_value(), LLVMValue::jint_constant(0x1f))), false)); + break; + case Bytecodes::_iushr: + b = pop(); + a = pop(); + push(SharkValue::create_jint( + builder()->CreateLShr( + a->jint_value(), + builder()->CreateAnd( + b->jint_value(), LLVMValue::jint_constant(0x1f))), false)); + break; + case Bytecodes::_iand: + b = pop(); + a = pop(); + push(SharkValue::create_jint( + builder()->CreateAnd(a->jint_value(), b->jint_value()), false)); + break; + case Bytecodes::_ior: + b = pop(); + a = pop(); + push(SharkValue::create_jint( + builder()->CreateOr(a->jint_value(), b->jint_value()), + a->zero_checked() && b->zero_checked())); + break; + case Bytecodes::_ixor: + b = pop(); + a = pop(); + push(SharkValue::create_jint( + builder()->CreateXor(a->jint_value(), b->jint_value()), false)); + break; + + case Bytecodes::_ladd: + b = pop(); + a = pop(); + push(SharkValue::create_jlong( + builder()->CreateAdd(a->jlong_value(), b->jlong_value()), false)); + break; + case Bytecodes::_lsub: + b = pop(); + a = pop(); + push(SharkValue::create_jlong( + builder()->CreateSub(a->jlong_value(), b->jlong_value()), false)); + break; + case Bytecodes::_lmul: + b = pop(); + a = pop(); + push(SharkValue::create_jlong( + builder()->CreateMul(a->jlong_value(), b->jlong_value()), false)); + break; + case Bytecodes::_ldiv: + do_ldiv(); + break; + case Bytecodes::_lrem: + do_lrem(); + break; + case Bytecodes::_lneg: + a = pop(); + push(SharkValue::create_jlong( + builder()->CreateNeg(a->jlong_value()), a->zero_checked())); + break; + case Bytecodes::_lshl: + b = pop(); + a = pop(); + push(SharkValue::create_jlong( + builder()->CreateShl( + a->jlong_value(), + builder()->CreateIntCast( + builder()->CreateAnd( + b->jint_value(), LLVMValue::jint_constant(0x3f)), + SharkType::jlong_type(), true)), false)); + break; + case Bytecodes::_lshr: + b = pop(); + a = pop(); + push(SharkValue::create_jlong( + builder()->CreateAShr( + a->jlong_value(), + builder()->CreateIntCast( + builder()->CreateAnd( + b->jint_value(), LLVMValue::jint_constant(0x3f)), + SharkType::jlong_type(), true)), false)); + break; + case Bytecodes::_lushr: + b = pop(); + a = pop(); + push(SharkValue::create_jlong( + builder()->CreateLShr( + a->jlong_value(), + builder()->CreateIntCast( + builder()->CreateAnd( + b->jint_value(), LLVMValue::jint_constant(0x3f)), + SharkType::jlong_type(), true)), false)); + break; + case Bytecodes::_land: + b = pop(); + a = pop(); + push(SharkValue::create_jlong( + builder()->CreateAnd(a->jlong_value(), b->jlong_value()), false)); + break; + case Bytecodes::_lor: + b = pop(); + a = pop(); + push(SharkValue::create_jlong( + builder()->CreateOr(a->jlong_value(), b->jlong_value()), + a->zero_checked() && b->zero_checked())); + break; + case Bytecodes::_lxor: + b = pop(); + a = pop(); + push(SharkValue::create_jlong( + builder()->CreateXor(a->jlong_value(), b->jlong_value()), false)); + break; + + case Bytecodes::_fadd: + b = pop(); + a = pop(); + push(SharkValue::create_jfloat( + builder()->CreateFAdd(a->jfloat_value(), b->jfloat_value()))); + break; + case Bytecodes::_fsub: + b = pop(); + a = pop(); + push(SharkValue::create_jfloat( + builder()->CreateFSub(a->jfloat_value(), b->jfloat_value()))); + break; + case Bytecodes::_fmul: + b = pop(); + a = pop(); + push(SharkValue::create_jfloat( + builder()->CreateFMul(a->jfloat_value(), b->jfloat_value()))); + break; + case Bytecodes::_fdiv: + b = pop(); + a = pop(); + push(SharkValue::create_jfloat( + builder()->CreateFDiv(a->jfloat_value(), b->jfloat_value()))); + break; + case Bytecodes::_frem: + b = pop(); + a = pop(); + push(SharkValue::create_jfloat( + builder()->CreateFRem(a->jfloat_value(), b->jfloat_value()))); + break; + case Bytecodes::_fneg: + a = pop(); + push(SharkValue::create_jfloat( + builder()->CreateFNeg(a->jfloat_value()))); + break; + + case Bytecodes::_dadd: + b = pop(); + a = pop(); + push(SharkValue::create_jdouble( + builder()->CreateFAdd(a->jdouble_value(), b->jdouble_value()))); + break; + case Bytecodes::_dsub: + b = pop(); + a = pop(); + push(SharkValue::create_jdouble( + builder()->CreateFSub(a->jdouble_value(), b->jdouble_value()))); + break; + case Bytecodes::_dmul: + b = pop(); + a = pop(); + push(SharkValue::create_jdouble( + builder()->CreateFMul(a->jdouble_value(), b->jdouble_value()))); + break; + case Bytecodes::_ddiv: + b = pop(); + a = pop(); + push(SharkValue::create_jdouble( + builder()->CreateFDiv(a->jdouble_value(), b->jdouble_value()))); + break; + case Bytecodes::_drem: + b = pop(); + a = pop(); + push(SharkValue::create_jdouble( + builder()->CreateFRem(a->jdouble_value(), b->jdouble_value()))); + break; + case Bytecodes::_dneg: + a = pop(); + push(SharkValue::create_jdouble( + builder()->CreateFNeg(a->jdouble_value()))); + break; + + case Bytecodes::_iinc: + i = iter()->get_index(); + set_local( + i, + SharkValue::create_jint( + builder()->CreateAdd( + LLVMValue::jint_constant(iter()->get_iinc_con()), + local(i)->jint_value()), false)); + break; + + case Bytecodes::_lcmp: + do_lcmp(); + break; + + case Bytecodes::_fcmpl: + do_fcmp(false, false); + break; + case Bytecodes::_fcmpg: + do_fcmp(false, true); + break; + case Bytecodes::_dcmpl: + do_fcmp(true, false); + break; + case Bytecodes::_dcmpg: + do_fcmp(true, true); + break; + + case Bytecodes::_i2l: + a = pop(); + push(SharkValue::create_jlong( + builder()->CreateIntCast( + a->jint_value(), SharkType::jlong_type(), true), a->zero_checked())); + break; + case Bytecodes::_i2f: + push(SharkValue::create_jfloat( + builder()->CreateSIToFP( + pop()->jint_value(), SharkType::jfloat_type()))); + break; + case Bytecodes::_i2d: + push(SharkValue::create_jdouble( + builder()->CreateSIToFP( + pop()->jint_value(), SharkType::jdouble_type()))); + break; + + case Bytecodes::_l2i: + push(SharkValue::create_jint( + builder()->CreateIntCast( + pop()->jlong_value(), SharkType::jint_type(), true), false)); + break; + case Bytecodes::_l2f: + push(SharkValue::create_jfloat( + builder()->CreateSIToFP( + pop()->jlong_value(), SharkType::jfloat_type()))); + break; + case Bytecodes::_l2d: + push(SharkValue::create_jdouble( + builder()->CreateSIToFP( + pop()->jlong_value(), SharkType::jdouble_type()))); + break; + + case Bytecodes::_f2i: + push(SharkValue::create_jint( + builder()->CreateCall( + builder()->f2i(), pop()->jfloat_value()), false)); + break; + case Bytecodes::_f2l: + push(SharkValue::create_jlong( + builder()->CreateCall( + builder()->f2l(), pop()->jfloat_value()), false)); + break; + case Bytecodes::_f2d: + push(SharkValue::create_jdouble( + builder()->CreateFPExt( + pop()->jfloat_value(), SharkType::jdouble_type()))); + break; + + case Bytecodes::_d2i: + push(SharkValue::create_jint( + builder()->CreateCall( + builder()->d2i(), pop()->jdouble_value()), false)); + break; + case Bytecodes::_d2l: + push(SharkValue::create_jlong( + builder()->CreateCall( + builder()->d2l(), pop()->jdouble_value()), false)); + break; + case Bytecodes::_d2f: + push(SharkValue::create_jfloat( + builder()->CreateFPTrunc( + pop()->jdouble_value(), SharkType::jfloat_type()))); + break; + + case Bytecodes::_i2b: + push(SharkValue::create_jint( + builder()->CreateAShr( + builder()->CreateShl( + pop()->jint_value(), + LLVMValue::jint_constant(24)), + LLVMValue::jint_constant(24)), false)); + break; + case Bytecodes::_i2c: + push(SharkValue::create_jint( + builder()->CreateAnd( + pop()->jint_value(), + LLVMValue::jint_constant(0xffff)), false)); + break; + case Bytecodes::_i2s: + push(SharkValue::create_jint( + builder()->CreateAShr( + builder()->CreateShl( + pop()->jint_value(), + LLVMValue::jint_constant(16)), + LLVMValue::jint_constant(16)), false)); + break; + + case Bytecodes::_return: + do_return(T_VOID); + break; + case Bytecodes::_ireturn: + do_return(T_INT); + break; + case Bytecodes::_lreturn: + do_return(T_LONG); + break; + case Bytecodes::_freturn: + do_return(T_FLOAT); + break; + case Bytecodes::_dreturn: + do_return(T_DOUBLE); + break; + case Bytecodes::_areturn: + do_return(T_OBJECT); + break; + + case Bytecodes::_athrow: + do_athrow(); + break; + + case Bytecodes::_goto: + case Bytecodes::_goto_w: + do_goto(); + break; + + case Bytecodes::_jsr: + case Bytecodes::_jsr_w: + do_jsr(); + break; + + case Bytecodes::_ret: + do_ret(); + break; + + case Bytecodes::_ifnull: + do_if(ICmpInst::ICMP_EQ, SharkValue::null(), pop()); + break; + case Bytecodes::_ifnonnull: + do_if(ICmpInst::ICMP_NE, SharkValue::null(), pop()); + break; + case Bytecodes::_if_acmpeq: + b = pop(); + a = pop(); + do_if(ICmpInst::ICMP_EQ, b, a); + break; + case Bytecodes::_if_acmpne: + b = pop(); + a = pop(); + do_if(ICmpInst::ICMP_NE, b, a); + break; + case Bytecodes::_ifeq: + do_if(ICmpInst::ICMP_EQ, SharkValue::jint_constant(0), pop()); + break; + case Bytecodes::_ifne: + do_if(ICmpInst::ICMP_NE, SharkValue::jint_constant(0), pop()); + break; + case Bytecodes::_iflt: + do_if(ICmpInst::ICMP_SLT, SharkValue::jint_constant(0), pop()); + break; + case Bytecodes::_ifle: + do_if(ICmpInst::ICMP_SLE, SharkValue::jint_constant(0), pop()); + break; + case Bytecodes::_ifgt: + do_if(ICmpInst::ICMP_SGT, SharkValue::jint_constant(0), pop()); + break; + case Bytecodes::_ifge: + do_if(ICmpInst::ICMP_SGE, SharkValue::jint_constant(0), pop()); + break; + case Bytecodes::_if_icmpeq: + b = pop(); + a = pop(); + do_if(ICmpInst::ICMP_EQ, b, a); + break; + case Bytecodes::_if_icmpne: + b = pop(); + a = pop(); + do_if(ICmpInst::ICMP_NE, b, a); + break; + case Bytecodes::_if_icmplt: + b = pop(); + a = pop(); + do_if(ICmpInst::ICMP_SLT, b, a); + break; + case Bytecodes::_if_icmple: + b = pop(); + a = pop(); + do_if(ICmpInst::ICMP_SLE, b, a); + break; + case Bytecodes::_if_icmpgt: + b = pop(); + a = pop(); + do_if(ICmpInst::ICMP_SGT, b, a); + break; + case Bytecodes::_if_icmpge: + b = pop(); + a = pop(); + do_if(ICmpInst::ICMP_SGE, b, a); + break; + + case Bytecodes::_tableswitch: + case Bytecodes::_lookupswitch: + do_switch(); + break; + + case Bytecodes::_invokestatic: + case Bytecodes::_invokespecial: + case Bytecodes::_invokevirtual: + case Bytecodes::_invokeinterface: + do_call(); + break; + + case Bytecodes::_instanceof: + // This is a very common construct: + // + // if (object instanceof Klass) { + // something = (Klass) object; + // ... + // } + // + // which gets compiled to something like this: + // + // 28: aload 9 + // 30: instanceof + // 33: ifeq 52 + // 36: aload 9 + // 38: checkcast + // + // Handling both bytecodes at once allows us + // to eliminate the checkcast. + if (iter()->next_bci() < limit && + (iter()->next_bc() == Bytecodes::_ifeq || + iter()->next_bc() == Bytecodes::_ifne) && + (!UseLoopSafepoints || + iter()->next_get_dest() > iter()->next_bci())) { + if (maybe_do_instanceof_if()) { + iter()->next(); + if (SharkTraceBytecodes) + tty->print_cr("%4d: %s", bci(), Bytecodes::name(bc())); + break; + } + } + // fall through + case Bytecodes::_checkcast: + do_instance_check(); + break; + + case Bytecodes::_new: + do_new(); + break; + case Bytecodes::_newarray: + do_newarray(); + break; + case Bytecodes::_anewarray: + do_anewarray(); + break; + case Bytecodes::_multianewarray: + do_multianewarray(); + break; + + case Bytecodes::_monitorenter: + do_monitorenter(); + break; + case Bytecodes::_monitorexit: + do_monitorexit(); + break; + + default: + ShouldNotReachHere(); + } + } +} + +SharkState* SharkBlock::initial_current_state() { + return entry_state()->copy(); +} + +int SharkBlock::switch_default_dest() { + return iter()->get_dest_table(0); +} + +int SharkBlock::switch_table_length() { + switch(bc()) { + case Bytecodes::_tableswitch: + return iter()->get_int_table(2) - iter()->get_int_table(1) + 1; + + case Bytecodes::_lookupswitch: + return iter()->get_int_table(1); + + default: + ShouldNotReachHere(); + } +} + +int SharkBlock::switch_key(int i) { + switch(bc()) { + case Bytecodes::_tableswitch: + return iter()->get_int_table(1) + i; + + case Bytecodes::_lookupswitch: + return iter()->get_int_table(2 + 2 * i); + + default: + ShouldNotReachHere(); + } +} + +int SharkBlock::switch_dest(int i) { + switch(bc()) { + case Bytecodes::_tableswitch: + return iter()->get_dest_table(i + 3); + + case Bytecodes::_lookupswitch: + return iter()->get_dest_table(2 + 2 * i + 1); + + default: + ShouldNotReachHere(); + } +} + +void SharkBlock::do_div_or_rem(bool is_long, bool is_rem) { + SharkValue *sb = pop(); + SharkValue *sa = pop(); + + check_divide_by_zero(sb); + + Value *a, *b, *p, *q; + if (is_long) { + a = sa->jlong_value(); + b = sb->jlong_value(); + p = LLVMValue::jlong_constant(0x8000000000000000LL); + q = LLVMValue::jlong_constant(-1); + } + else { + a = sa->jint_value(); + b = sb->jint_value(); + p = LLVMValue::jint_constant(0x80000000); + q = LLVMValue::jint_constant(-1); + } + + BasicBlock *ip = builder()->GetBlockInsertionPoint(); + BasicBlock *special_case = builder()->CreateBlock(ip, "special_case"); + BasicBlock *general_case = builder()->CreateBlock(ip, "general_case"); + BasicBlock *done = builder()->CreateBlock(ip, "done"); + + builder()->CreateCondBr( + builder()->CreateAnd( + builder()->CreateICmpEQ(a, p), + builder()->CreateICmpEQ(b, q)), + special_case, general_case); + + builder()->SetInsertPoint(special_case); + Value *special_result; + if (is_rem) { + if (is_long) + special_result = LLVMValue::jlong_constant(0); + else + special_result = LLVMValue::jint_constant(0); + } + else { + special_result = a; + } + builder()->CreateBr(done); + + builder()->SetInsertPoint(general_case); + Value *general_result; + if (is_rem) + general_result = builder()->CreateSRem(a, b); + else + general_result = builder()->CreateSDiv(a, b); + builder()->CreateBr(done); + + builder()->SetInsertPoint(done); + PHINode *result; + if (is_long) + result = builder()->CreatePHI(SharkType::jlong_type(), "result"); + else + result = builder()->CreatePHI(SharkType::jint_type(), "result"); + result->addIncoming(special_result, special_case); + result->addIncoming(general_result, general_case); + + if (is_long) + push(SharkValue::create_jlong(result, false)); + else + push(SharkValue::create_jint(result, false)); +} + +void SharkBlock::do_field_access(bool is_get, bool is_field) { + bool will_link; + ciField *field = iter()->get_field(will_link); + assert(will_link, "typeflow responsibility"); + assert(is_field != field->is_static(), "mismatch"); + + // Pop the value off the stack where necessary + SharkValue *value = NULL; + if (!is_get) + value = pop(); + + // Find the object we're accessing, if necessary + Value *object = NULL; + if (is_field) { + SharkValue *value = pop(); + check_null(value); + object = value->generic_value(); + } + if (is_get && field->is_constant()) { + SharkConstant *constant = SharkConstant::for_field(iter()); + if (constant->is_loaded()) + value = constant->value(builder()); + } + if (!is_get || value == NULL) { + if (!is_field) + object = builder()->CreateInlineOop(field->holder()); + + BasicType basic_type = field->type()->basic_type(); + const Type *stack_type = SharkType::to_stackType(basic_type); + const Type *field_type = SharkType::to_arrayType(basic_type); + + Value *addr = builder()->CreateAddressOfStructEntry( + object, in_ByteSize(field->offset_in_bytes()), + PointerType::getUnqual(field_type), + "addr"); + + // Do the access + if (is_get) { + Value *field_value = builder()->CreateLoad(addr); + + if (field_type != stack_type) { + field_value = builder()->CreateIntCast( + field_value, stack_type, basic_type != T_CHAR); + } + + value = SharkValue::create_generic(field->type(), field_value, false); + } + else { + Value *field_value = value->generic_value(); + + if (field_type != stack_type) { + field_value = builder()->CreateIntCast( + field_value, field_type, basic_type != T_CHAR); + } + + builder()->CreateStore(field_value, addr); + + if (!field->type()->is_primitive_type()) + builder()->CreateUpdateBarrierSet(oopDesc::bs(), addr); + + if (field->is_volatile()) + builder()->CreateMemoryBarrier(SharkBuilder::BARRIER_STORELOAD); + } + } + + // Push the value onto the stack where necessary + if (is_get) + push(value); +} + +void SharkBlock::do_lcmp() { + Value *b = pop()->jlong_value(); + Value *a = pop()->jlong_value(); + + BasicBlock *ip = builder()->GetBlockInsertionPoint(); + BasicBlock *ne = builder()->CreateBlock(ip, "lcmp_ne"); + BasicBlock *lt = builder()->CreateBlock(ip, "lcmp_lt"); + BasicBlock *gt = builder()->CreateBlock(ip, "lcmp_gt"); + BasicBlock *done = builder()->CreateBlock(ip, "done"); + + BasicBlock *eq = builder()->GetInsertBlock(); + builder()->CreateCondBr(builder()->CreateICmpEQ(a, b), done, ne); + + builder()->SetInsertPoint(ne); + builder()->CreateCondBr(builder()->CreateICmpSLT(a, b), lt, gt); + + builder()->SetInsertPoint(lt); + builder()->CreateBr(done); + + builder()->SetInsertPoint(gt); + builder()->CreateBr(done); + + builder()->SetInsertPoint(done); + PHINode *result = builder()->CreatePHI(SharkType::jint_type(), "result"); + result->addIncoming(LLVMValue::jint_constant(-1), lt); + result->addIncoming(LLVMValue::jint_constant(0), eq); + result->addIncoming(LLVMValue::jint_constant(1), gt); + + push(SharkValue::create_jint(result, false)); +} + +void SharkBlock::do_fcmp(bool is_double, bool unordered_is_greater) { + Value *a, *b; + if (is_double) { + b = pop()->jdouble_value(); + a = pop()->jdouble_value(); + } + else { + b = pop()->jfloat_value(); + a = pop()->jfloat_value(); + } + + BasicBlock *ip = builder()->GetBlockInsertionPoint(); + BasicBlock *ordered = builder()->CreateBlock(ip, "ordered"); + BasicBlock *ge = builder()->CreateBlock(ip, "fcmp_ge"); + BasicBlock *lt = builder()->CreateBlock(ip, "fcmp_lt"); + BasicBlock *eq = builder()->CreateBlock(ip, "fcmp_eq"); + BasicBlock *gt = builder()->CreateBlock(ip, "fcmp_gt"); + BasicBlock *done = builder()->CreateBlock(ip, "done"); + + builder()->CreateCondBr( + builder()->CreateFCmpUNO(a, b), + unordered_is_greater ? gt : lt, ordered); + + builder()->SetInsertPoint(ordered); + builder()->CreateCondBr(builder()->CreateFCmpULT(a, b), lt, ge); + + builder()->SetInsertPoint(ge); + builder()->CreateCondBr(builder()->CreateFCmpUGT(a, b), gt, eq); + + builder()->SetInsertPoint(lt); + builder()->CreateBr(done); + + builder()->SetInsertPoint(gt); + builder()->CreateBr(done); + + builder()->SetInsertPoint(eq); + builder()->CreateBr(done); + + builder()->SetInsertPoint(done); + PHINode *result = builder()->CreatePHI(SharkType::jint_type(), "result"); + result->addIncoming(LLVMValue::jint_constant(-1), lt); + result->addIncoming(LLVMValue::jint_constant(0), eq); + result->addIncoming(LLVMValue::jint_constant(1), gt); + + push(SharkValue::create_jint(result, false)); +} + +void SharkBlock::emit_IR() { + ShouldNotCallThis(); +} + +SharkState* SharkBlock::entry_state() { + ShouldNotCallThis(); +} + +void SharkBlock::do_zero_check(SharkValue* value) { + ShouldNotCallThis(); +} + +void SharkBlock::maybe_add_backedge_safepoint() { + ShouldNotCallThis(); +} + +bool SharkBlock::has_trap() { + return false; +} + +int SharkBlock::trap_request() { + ShouldNotCallThis(); +} + +int SharkBlock::trap_bci() { + ShouldNotCallThis(); +} + +void SharkBlock::do_trap(int trap_request) { + ShouldNotCallThis(); +} + +void SharkBlock::do_arraylength() { + ShouldNotCallThis(); +} + +void SharkBlock::do_aload(BasicType basic_type) { + ShouldNotCallThis(); +} + +void SharkBlock::do_astore(BasicType basic_type) { + ShouldNotCallThis(); +} + +void SharkBlock::do_return(BasicType type) { + ShouldNotCallThis(); +} + +void SharkBlock::do_athrow() { + ShouldNotCallThis(); +} + +void SharkBlock::do_goto() { + ShouldNotCallThis(); +} + +void SharkBlock::do_jsr() { + ShouldNotCallThis(); +} + +void SharkBlock::do_ret() { + ShouldNotCallThis(); +} + +void SharkBlock::do_if(ICmpInst::Predicate p, SharkValue* b, SharkValue* a) { + ShouldNotCallThis(); +} + +void SharkBlock::do_switch() { + ShouldNotCallThis(); +} + +void SharkBlock::do_call() { + ShouldNotCallThis(); +} + +void SharkBlock::do_instance_check() { + ShouldNotCallThis(); +} + +bool SharkBlock::maybe_do_instanceof_if() { + ShouldNotCallThis(); +} + +void SharkBlock::do_new() { + ShouldNotCallThis(); +} + +void SharkBlock::do_newarray() { + ShouldNotCallThis(); +} + +void SharkBlock::do_anewarray() { + ShouldNotCallThis(); +} + +void SharkBlock::do_multianewarray() { + ShouldNotCallThis(); +} + +void SharkBlock::do_monitorenter() { + ShouldNotCallThis(); +} + +void SharkBlock::do_monitorexit() { + ShouldNotCallThis(); +} diff --git a/hotspot/src/share/vm/shark/sharkBlock.hpp b/hotspot/src/share/vm/shark/sharkBlock.hpp new file mode 100644 index 00000000000..3de506ecdd3 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkBlock.hpp @@ -0,0 +1,281 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * 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. + * + */ + +class SharkState; + +class SharkBlock : public SharkTargetInvariants { + protected: + SharkBlock(const SharkTargetInvariants* parent) + : SharkTargetInvariants(parent), + _iter(target()), + _current_state(NULL) {} + + SharkBlock(const SharkCompileInvariants* parent, ciMethod* target) + : SharkTargetInvariants(parent, target), + _iter(target), + _current_state(NULL) {} + + private: + ciBytecodeStream _iter; + SharkState* _current_state; + + public: + ciBytecodeStream* iter() { + return &_iter; + } + Bytecodes::Code bc() { + return iter()->cur_bc(); + } + int bci() { + return iter()->cur_bci(); + } + + // Entry state + protected: + virtual SharkState* entry_state(); + + // Current state + private: + SharkState* initial_current_state(); + + public: + SharkState* current_state() { + if (_current_state == NULL) + set_current_state(initial_current_state()); + return _current_state; + } + + protected: + void set_current_state(SharkState* current_state) { + _current_state = current_state; + } + + // Local variables + protected: + SharkValue* local(int index) { + SharkValue *value = current_state()->local(index); + assert(value != NULL, "shouldn't be"); + assert(value->is_one_word() || + (index + 1 < max_locals() && + current_state()->local(index + 1) == NULL), "should be"); + return value; + } + void set_local(int index, SharkValue* value) { + assert(value != NULL, "shouldn't be"); + current_state()->set_local(index, value); + if (value->is_two_word()) + current_state()->set_local(index + 1, NULL); + } + + // Expression stack (raw) + protected: + void xpush(SharkValue* value) { + current_state()->push(value); + } + SharkValue* xpop() { + return current_state()->pop(); + } + SharkValue* xstack(int slot) { + SharkValue *value = current_state()->stack(slot); + assert(value != NULL, "shouldn't be"); + assert(value->is_one_word() || + (slot > 0 && + current_state()->stack(slot - 1) == NULL), "should be"); + return value; + } + int xstack_depth() { + return current_state()->stack_depth(); + } + + // Expression stack (cooked) + protected: + void push(SharkValue* value) { + assert(value != NULL, "shouldn't be"); + xpush(value); + if (value->is_two_word()) + xpush(NULL); + } + SharkValue* pop() { + int size = current_state()->stack(0) == NULL ? 2 : 1; + if (size == 2) + xpop(); + SharkValue *value = xpop(); + assert(value && value->size() == size, "should be"); + return value; + } + SharkValue* pop_result(BasicType type) { + SharkValue *result = pop(); + +#ifdef ASSERT + switch (result->basic_type()) { + case T_BOOLEAN: + case T_BYTE: + case T_CHAR: + case T_SHORT: + assert(type == T_INT, "type mismatch"); + break; + + case T_ARRAY: + assert(type == T_OBJECT, "type mismatch"); + break; + + default: + assert(result->basic_type() == type, "type mismatch"); + } +#endif // ASSERT + + return result; + } + + // Code generation + public: + virtual void emit_IR(); + + protected: + void parse_bytecode(int start, int limit); + + // Helpers + protected: + virtual void do_zero_check(SharkValue* value); + + // Zero checking + protected: + void check_null(SharkValue* object) { + zero_check(object); + } + void check_divide_by_zero(SharkValue* value) { + zero_check(value); + } + private: + void zero_check(SharkValue* value) { + if (!value->zero_checked()) + do_zero_check(value); + } + + // Safepoints + protected: + virtual void maybe_add_backedge_safepoint(); + + // Traps + protected: + virtual bool has_trap(); + virtual int trap_request(); + virtual int trap_bci(); + virtual void do_trap(int trap_request); + + // arraylength + protected: + virtual void do_arraylength(); + + // *aload and *astore + protected: + virtual void do_aload(BasicType basic_type); + virtual void do_astore(BasicType basic_type); + + // *div and *rem + private: + void do_idiv() { + do_div_or_rem(false, false); + } + void do_irem() { + do_div_or_rem(false, true); + } + void do_ldiv() { + do_div_or_rem(true, false); + } + void do_lrem() { + do_div_or_rem(true, true); + } + void do_div_or_rem(bool is_long, bool is_rem); + + // get* and put* + private: + void do_getstatic() { + do_field_access(true, false); + } + void do_getfield() { + do_field_access(true, true); + } + void do_putstatic() { + do_field_access(false, false); + } + void do_putfield() { + do_field_access(false, true); + } + void do_field_access(bool is_get, bool is_field); + + // lcmp and [fd]cmp[lg] + private: + void do_lcmp(); + void do_fcmp(bool is_double, bool unordered_is_greater); + + // *return and athrow + protected: + virtual void do_return(BasicType type); + virtual void do_athrow(); + + // goto* + protected: + virtual void do_goto(); + + // jsr* and ret + protected: + virtual void do_jsr(); + virtual void do_ret(); + + // if* + protected: + virtual void do_if(llvm::ICmpInst::Predicate p, SharkValue* b, SharkValue* a); + + // *switch + protected: + int switch_default_dest(); + int switch_table_length(); + int switch_key(int i); + int switch_dest(int i); + + virtual void do_switch(); + + // invoke* + protected: + virtual void do_call(); + + // checkcast and instanceof + protected: + virtual void do_instance_check(); + virtual bool maybe_do_instanceof_if(); + + // new and *newarray + protected: + virtual void do_new(); + virtual void do_newarray(); + virtual void do_anewarray(); + virtual void do_multianewarray(); + + // monitorenter and monitorexit + protected: + virtual void do_monitorenter(); + virtual void do_monitorexit(); +}; diff --git a/hotspot/src/share/vm/shark/sharkBuilder.cpp b/hotspot/src/share/vm/shark/sharkBuilder.cpp new file mode 100644 index 00000000000..1fc7c7c3c57 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkBuilder.cpp @@ -0,0 +1,591 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkBuilder.cpp.incl" + +using namespace llvm; + +SharkBuilder::SharkBuilder(SharkCodeBuffer* code_buffer) + : IRBuilder<>(SharkContext::current()), + _code_buffer(code_buffer) { +} + +// Helpers for accessing structures +Value* SharkBuilder::CreateAddressOfStructEntry(Value* base, + ByteSize offset, + const Type* type, + const char* name) { + return CreateBitCast(CreateStructGEP(base, in_bytes(offset)), type, name); +} + +LoadInst* SharkBuilder::CreateValueOfStructEntry(Value* base, + ByteSize offset, + const Type* type, + const char* name) { + return CreateLoad( + CreateAddressOfStructEntry( + base, offset, PointerType::getUnqual(type)), + name); +} + +// Helpers for accessing arrays + +LoadInst* SharkBuilder::CreateArrayLength(Value* arrayoop) { + return CreateValueOfStructEntry( + arrayoop, in_ByteSize(arrayOopDesc::length_offset_in_bytes()), + SharkType::jint_type(), "length"); +} + +Value* SharkBuilder::CreateArrayAddress(Value* arrayoop, + const Type* element_type, + int element_bytes, + ByteSize base_offset, + Value* index, + const char* name) { + Value* offset = CreateIntCast(index, SharkType::intptr_type(), false); + if (element_bytes != 1) + offset = CreateShl( + offset, + LLVMValue::intptr_constant(exact_log2(element_bytes))); + offset = CreateAdd( + LLVMValue::intptr_constant(in_bytes(base_offset)), offset); + + return CreateIntToPtr( + CreateAdd(CreatePtrToInt(arrayoop, SharkType::intptr_type()), offset), + PointerType::getUnqual(element_type), + name); +} + +Value* SharkBuilder::CreateArrayAddress(Value* arrayoop, + BasicType basic_type, + ByteSize base_offset, + Value* index, + const char* name) { + return CreateArrayAddress( + arrayoop, + SharkType::to_arrayType(basic_type), + type2aelembytes(basic_type), + base_offset, index, name); +} + +Value* SharkBuilder::CreateArrayAddress(Value* arrayoop, + BasicType basic_type, + Value* index, + const char* name) { + return CreateArrayAddress( + arrayoop, basic_type, + in_ByteSize(arrayOopDesc::base_offset_in_bytes(basic_type)), + index, name); +} + +// Helpers for creating intrinsics and external functions. + +const Type* SharkBuilder::make_type(char type, bool void_ok) { + switch (type) { + // Primitive types + case 'c': + return SharkType::jbyte_type(); + case 'i': + return SharkType::jint_type(); + case 'l': + return SharkType::jlong_type(); + case 'x': + return SharkType::intptr_type(); + case 'f': + return SharkType::jfloat_type(); + case 'd': + return SharkType::jdouble_type(); + + // Pointers to primitive types + case 'C': + case 'I': + case 'L': + case 'X': + case 'F': + case 'D': + return PointerType::getUnqual(make_type(tolower(type), false)); + + // VM objects + case 'T': + return SharkType::thread_type(); + case 'M': + return PointerType::getUnqual(SharkType::monitor_type()); + case 'O': + return SharkType::oop_type(); + + // Miscellaneous + case 'v': + assert(void_ok, "should be"); + return SharkType::void_type(); + case '1': + return SharkType::bit_type(); + + default: + ShouldNotReachHere(); + } +} + +const FunctionType* SharkBuilder::make_ftype(const char* params, + const char* ret) { + std::vector param_types; + for (const char* c = params; *c; c++) + param_types.push_back(make_type(*c, false)); + + assert(strlen(ret) == 1, "should be"); + const Type *return_type = make_type(*ret, true); + + return FunctionType::get(return_type, param_types, false); +} + +// Create an object representing an intrinsic or external function by +// referencing the symbol by name. This is the LLVM-style approach, +// but it cannot be used on functions within libjvm.so its symbols +// are not exported. Note that you cannot make this work simply by +// exporting the symbols, as some symbols have the same names as +// symbols in the standard libraries (eg, atan2, fabs) and would +// obscure them were they visible. +Value* SharkBuilder::make_function(const char* name, + const char* params, + const char* ret) { + return SharkContext::current().get_external(name, make_ftype(params, ret)); +} + +// Create an object representing an external function by inlining a +// function pointer in the code. This is not the LLVM way, but it's +// the only way to access functions in libjvm.so and functions like +// __kernel_dmb on ARM which is accessed via an absolute address. +Value* SharkBuilder::make_function(address func, + const char* params, + const char* ret) { + return CreateIntToPtr( + LLVMValue::intptr_constant((intptr_t) func), + PointerType::getUnqual(make_ftype(params, ret))); +} + +// VM calls + +Value* SharkBuilder::find_exception_handler() { + return make_function( + (address) SharkRuntime::find_exception_handler, "TIi", "i"); +} + +Value* SharkBuilder::monitorenter() { + return make_function((address) SharkRuntime::monitorenter, "TM", "v"); +} + +Value* SharkBuilder::monitorexit() { + return make_function((address) SharkRuntime::monitorexit, "TM", "v"); +} + +Value* SharkBuilder::new_instance() { + return make_function((address) SharkRuntime::new_instance, "Ti", "v"); +} + +Value* SharkBuilder::newarray() { + return make_function((address) SharkRuntime::newarray, "Tii", "v"); +} + +Value* SharkBuilder::anewarray() { + return make_function((address) SharkRuntime::anewarray, "Tii", "v"); +} + +Value* SharkBuilder::multianewarray() { + return make_function((address) SharkRuntime::multianewarray, "TiiI", "v"); +} + +Value* SharkBuilder::register_finalizer() { + return make_function((address) SharkRuntime::register_finalizer, "TO", "v"); +} + +Value* SharkBuilder::safepoint() { + return make_function((address) SafepointSynchronize::block, "T", "v"); +} + +Value* SharkBuilder::throw_ArithmeticException() { + return make_function( + (address) SharkRuntime::throw_ArithmeticException, "TCi", "v"); +} + +Value* SharkBuilder::throw_ArrayIndexOutOfBoundsException() { + return make_function( + (address) SharkRuntime::throw_ArrayIndexOutOfBoundsException, "TCii", "v"); +} + +Value* SharkBuilder::throw_ClassCastException() { + return make_function( + (address) SharkRuntime::throw_ClassCastException, "TCi", "v"); +} + +Value* SharkBuilder::throw_NullPointerException() { + return make_function( + (address) SharkRuntime::throw_NullPointerException, "TCi", "v"); +} + +// High-level non-VM calls + +Value* SharkBuilder::f2i() { + return make_function((address) SharedRuntime::f2i, "f", "i"); +} + +Value* SharkBuilder::f2l() { + return make_function((address) SharedRuntime::f2l, "f", "l"); +} + +Value* SharkBuilder::d2i() { + return make_function((address) SharedRuntime::d2i, "d", "i"); +} + +Value* SharkBuilder::d2l() { + return make_function((address) SharedRuntime::d2l, "d", "l"); +} + +Value* SharkBuilder::is_subtype_of() { + return make_function((address) SharkRuntime::is_subtype_of, "OO", "c"); +} + +Value* SharkBuilder::current_time_millis() { + return make_function((address) os::javaTimeMillis, "", "l"); +} + +Value* SharkBuilder::sin() { + return make_function("llvm.sin.f64", "d", "d"); +} + +Value* SharkBuilder::cos() { + return make_function("llvm.cos.f64", "d", "d"); +} + +Value* SharkBuilder::tan() { + return make_function((address) ::tan, "d", "d"); +} + +Value* SharkBuilder::atan2() { + return make_function((address) ::atan2, "dd", "d"); +} + +Value* SharkBuilder::sqrt() { + return make_function("llvm.sqrt.f64", "d", "d"); +} + +Value* SharkBuilder::log() { + return make_function("llvm.log.f64", "d", "d"); +} + +Value* SharkBuilder::log10() { + return make_function("llvm.log10.f64", "d", "d"); +} + +Value* SharkBuilder::pow() { + return make_function("llvm.pow.f64", "dd", "d"); +} + +Value* SharkBuilder::exp() { + return make_function("llvm.exp.f64", "d", "d"); +} + +Value* SharkBuilder::fabs() { + return make_function((address) ::fabs, "d", "d"); +} + +Value* SharkBuilder::unsafe_field_offset_to_byte_offset() { + extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset); + return make_function((address) Unsafe_field_offset_to_byte_offset, "l", "l"); +} + +Value* SharkBuilder::osr_migration_end() { + return make_function((address) SharedRuntime::OSR_migration_end, "C", "v"); +} + +// Semi-VM calls + +Value* SharkBuilder::throw_StackOverflowError() { + return make_function((address) ZeroStack::handle_overflow, "T", "v"); +} + +Value* SharkBuilder::uncommon_trap() { + return make_function((address) SharkRuntime::uncommon_trap, "Ti", "i"); +} + +Value* SharkBuilder::deoptimized_entry_point() { + return make_function((address) CppInterpreter::main_loop, "iT", "v"); +} + +// Native-Java transition + +Value* SharkBuilder::check_special_condition_for_native_trans() { + return make_function( + (address) JavaThread::check_special_condition_for_native_trans, + "T", "v"); +} + +// Low-level non-VM calls + +// The ARM-specific code here is to work around unimplemented +// atomic exchange and memory barrier intrinsics in LLVM. +// +// Delegating to external functions for these would normally +// incur a speed penalty, but Linux on ARM is a special case +// in that atomic operations on that platform are handled by +// external functions anyway. It would be *preferable* for +// the calls to be hidden away in LLVM, but it's not hurting +// performance so having the calls here is acceptable. +// +// If you are building Shark on a platform without atomic +// exchange and/or memory barrier intrinsics then it is only +// acceptable to mimic this approach if your platform cannot +// perform these operations without delegating to a function. + +#ifdef ARM +static jint zero_cmpxchg_int(volatile jint *ptr, jint oldval, jint newval) { + return Atomic::cmpxchg(newval, ptr, oldval); +} +#endif // ARM + +Value* SharkBuilder::cmpxchg_int() { + return make_function( +#ifdef ARM + (address) zero_cmpxchg_int, +#else + "llvm.atomic.cmp.swap.i32.p0i32", +#endif // ARM + "Iii", "i"); +} + +#ifdef ARM +static intptr_t zero_cmpxchg_ptr(volatile intptr_t* ptr, + intptr_t oldval, + intptr_t newval) { + return Atomic::cmpxchg_ptr(newval, ptr, oldval); +} +#endif // ARM + +Value* SharkBuilder::cmpxchg_ptr() { + return make_function( +#ifdef ARM + (address) zero_cmpxchg_ptr, +#else + "llvm.atomic.cmp.swap.i" LP64_ONLY("64") NOT_LP64("32") ".p0i" LP64_ONLY("64") NOT_LP64("32"), +#endif // ARM + "Xxx", "x"); +} + +Value* SharkBuilder::frame_address() { + return make_function("llvm.frameaddress", "i", "C"); +} + +Value* SharkBuilder::memory_barrier() { + return make_function( +#ifdef ARM + (address) 0xffff0fa0, // __kernel_dmb +#else + "llvm.memory.barrier", +#endif // ARM + "11111", "v"); +} + +Value* SharkBuilder::memset() { +#if SHARK_LLVM_VERSION >= 28 + // LLVM 2.8 added a fifth isVolatile field for memset + // introduced with LLVM r100304 + return make_function("llvm.memset.i32", "Cciii", "v"); +#else + return make_function("llvm.memset.i32", "Ccii", "v"); +#endif +} + +Value* SharkBuilder::unimplemented() { + return make_function((address) report_unimplemented, "Ci", "v"); +} + +Value* SharkBuilder::should_not_reach_here() { + return make_function((address) report_should_not_reach_here, "Ci", "v"); +} + +Value* SharkBuilder::dump() { + return make_function((address) SharkRuntime::dump, "Cx", "v"); +} + +// Public interface to low-level non-VM calls + +CallInst* SharkBuilder::CreateCmpxchgInt(Value* exchange_value, + Value* dst, + Value* compare_value) { + return CreateCall3(cmpxchg_int(), dst, compare_value, exchange_value); +} + +CallInst* SharkBuilder::CreateCmpxchgPtr(Value* exchange_value, + Value* dst, + Value* compare_value) { + return CreateCall3(cmpxchg_ptr(), dst, compare_value, exchange_value); +} + +CallInst* SharkBuilder::CreateGetFrameAddress() { + return CreateCall(frame_address(), LLVMValue::jint_constant(0)); +} + +CallInst *SharkBuilder::CreateMemoryBarrier(int flags) { + Value *args[] = { + LLVMValue::bit_constant((flags & BARRIER_LOADLOAD) ? 1 : 0), + LLVMValue::bit_constant((flags & BARRIER_LOADSTORE) ? 1 : 0), + LLVMValue::bit_constant((flags & BARRIER_STORELOAD) ? 1 : 0), + LLVMValue::bit_constant((flags & BARRIER_STORESTORE) ? 1 : 0), + LLVMValue::bit_constant(1)}; + + return CreateCall(memory_barrier(), args, args + 5); +} + +CallInst* SharkBuilder::CreateMemset(Value* dst, + Value* value, + Value* len, + Value* align) { +#if SHARK_LLVM_VERSION >= 28 + return CreateCall5(memset(), dst, value, len, align, + LLVMValue::jint_constant(0)); +#else + return CreateCall4(memset(), dst, value, len, align); +#endif +} + +CallInst* SharkBuilder::CreateUnimplemented(const char* file, int line) { + return CreateCall2( + unimplemented(), + CreateIntToPtr( + LLVMValue::intptr_constant((intptr_t) file), + PointerType::getUnqual(SharkType::jbyte_type())), + LLVMValue::jint_constant(line)); +} + +CallInst* SharkBuilder::CreateShouldNotReachHere(const char* file, int line) { + return CreateCall2( + should_not_reach_here(), + CreateIntToPtr( + LLVMValue::intptr_constant((intptr_t) file), + PointerType::getUnqual(SharkType::jbyte_type())), + LLVMValue::jint_constant(line)); +} + +#ifndef PRODUCT +CallInst* SharkBuilder::CreateDump(Value* value) { + const char *name; + if (value->hasName()) + // XXX this leaks, but it's only debug code + name = strdup(value->getName().str().c_str()); + else + name = "unnamed_value"; + + if (isa(value->getType())) + value = CreatePtrToInt(value, SharkType::intptr_type()); + else if (value->getType()-> +#if SHARK_LLVM_VERSION >= 27 + isIntegerTy() +#else + isInteger() +#endif + ) + value = CreateIntCast(value, SharkType::intptr_type(), false); + else + Unimplemented(); + + return CreateCall2( + dump(), + CreateIntToPtr( + LLVMValue::intptr_constant((intptr_t) name), + PointerType::getUnqual(SharkType::jbyte_type())), + value); +} +#endif // PRODUCT + +// HotSpot memory barriers + +void SharkBuilder::CreateUpdateBarrierSet(BarrierSet* bs, Value* field) { + if (bs->kind() != BarrierSet::CardTableModRef) + Unimplemented(); + + CreateStore( + LLVMValue::jbyte_constant(CardTableModRefBS::dirty_card), + CreateIntToPtr( + CreateAdd( + LLVMValue::intptr_constant( + (intptr_t) ((CardTableModRefBS *) bs)->byte_map_base), + CreateLShr( + CreatePtrToInt(field, SharkType::intptr_type()), + LLVMValue::intptr_constant(CardTableModRefBS::card_shift))), + PointerType::getUnqual(SharkType::jbyte_type()))); +} + +// Helpers for accessing the code buffer + +Value* SharkBuilder::code_buffer_address(int offset) { + return CreateAdd( + code_buffer()->base_pc(), + LLVMValue::intptr_constant(offset)); +} + +Value* SharkBuilder::CreateInlineOop(jobject object, const char* name) { + return CreateLoad( + CreateIntToPtr( + code_buffer_address(code_buffer()->inline_oop(object)), + PointerType::getUnqual(SharkType::oop_type())), + name); +} + +Value* SharkBuilder::CreateInlineData(void* data, + size_t size, + const Type* type, + const char* name) { + return CreateIntToPtr( + code_buffer_address(code_buffer()->inline_data(data, size)), + type, + name); +} + +// Helpers for creating basic blocks. + +BasicBlock* SharkBuilder::GetBlockInsertionPoint() const { + BasicBlock *cur = GetInsertBlock(); + + // BasicBlock::Create takes an insertBefore argument, so + // we need to find the block _after_ the current block + Function::iterator iter = cur->getParent()->begin(); + Function::iterator end = cur->getParent()->end(); + while (iter != end) { + iter++; + if (&*iter == cur) { + iter++; + break; + } + } + + if (iter == end) + return NULL; + else + return iter; +} + +BasicBlock* SharkBuilder::CreateBlock(BasicBlock* ip, const char* name) const { + return BasicBlock::Create( + SharkContext::current(), name, GetInsertBlock()->getParent(), ip); +} diff --git a/hotspot/src/share/vm/shark/sharkBuilder.hpp b/hotspot/src/share/vm/shark/sharkBuilder.hpp new file mode 100644 index 00000000000..376a9fe6818 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkBuilder.hpp @@ -0,0 +1,209 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * 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. + * + */ + +class SharkBuilder : public llvm::IRBuilder<> { + friend class SharkCompileInvariants; + + public: + SharkBuilder(SharkCodeBuffer* code_buffer); + + // The code buffer we are building into. + private: + SharkCodeBuffer* _code_buffer; + + protected: + SharkCodeBuffer* code_buffer() const { + return _code_buffer; + } + + // Helpers for accessing structures. + public: + llvm::Value* CreateAddressOfStructEntry(llvm::Value* base, + ByteSize offset, + const llvm::Type* type, + const char *name = ""); + llvm::LoadInst* CreateValueOfStructEntry(llvm::Value* base, + ByteSize offset, + const llvm::Type* type, + const char *name = ""); + + // Helpers for accessing arrays. + public: + llvm::LoadInst* CreateArrayLength(llvm::Value* arrayoop); + llvm::Value* CreateArrayAddress(llvm::Value* arrayoop, + const llvm::Type* element_type, + int element_bytes, + ByteSize base_offset, + llvm::Value* index, + const char* name = ""); + llvm::Value* CreateArrayAddress(llvm::Value* arrayoop, + BasicType basic_type, + ByteSize base_offset, + llvm::Value* index, + const char* name = ""); + llvm::Value* CreateArrayAddress(llvm::Value* arrayoop, + BasicType basic_type, + llvm::Value* index, + const char* name = ""); + + // Helpers for creating intrinsics and external functions. + private: + static const llvm::Type* make_type(char type, bool void_ok); + static const llvm::FunctionType* make_ftype(const char* params, + const char* ret); + llvm::Value* make_function(const char* name, + const char* params, + const char* ret); + llvm::Value* make_function(address func, + const char* params, + const char* ret); + + // Intrinsics and external functions, part 1: VM calls. + // These are functions declared with JRT_ENTRY and JRT_EXIT, + // macros which flip the thread from _thread_in_Java to + // _thread_in_vm and back. VM calls always safepoint, and can + // therefore throw exceptions. VM calls require of setup and + // teardown, and must be called with SharkTopLevelBlock::call_vm. + public: + llvm::Value* find_exception_handler(); + llvm::Value* monitorenter(); + llvm::Value* monitorexit(); + llvm::Value* new_instance(); + llvm::Value* newarray(); + llvm::Value* anewarray(); + llvm::Value* multianewarray(); + llvm::Value* register_finalizer(); + llvm::Value* safepoint(); + llvm::Value* throw_ArithmeticException(); + llvm::Value* throw_ArrayIndexOutOfBoundsException(); + llvm::Value* throw_ClassCastException(); + llvm::Value* throw_NullPointerException(); + + // Intrinsics and external functions, part 2: High-level non-VM calls. + // These are called like normal functions. The stack is not set + // up for walking so they must not safepoint or throw exceptions, + // or call anything that might. + public: + llvm::Value* f2i(); + llvm::Value* f2l(); + llvm::Value* d2i(); + llvm::Value* d2l(); + llvm::Value* is_subtype_of(); + llvm::Value* current_time_millis(); + llvm::Value* sin(); + llvm::Value* cos(); + llvm::Value* tan(); + llvm::Value* atan2(); + llvm::Value* sqrt(); + llvm::Value* log(); + llvm::Value* log10(); + llvm::Value* pow(); + llvm::Value* exp(); + llvm::Value* fabs(); + llvm::Value* unsafe_field_offset_to_byte_offset(); + llvm::Value* osr_migration_end(); + + // Intrinsics and external functions, part 3: semi-VM calls. + // These are special cases that do VM call stuff but are invoked + // as though they were normal calls. This is acceptable so long + // as the method that calls them returns to its immediately that + // the semi VM call returns. + public: + llvm::Value* throw_StackOverflowError(); + llvm::Value* uncommon_trap(); + llvm::Value* deoptimized_entry_point(); + + // Intrinsics and external functions, part 4: Native-Java transition. + // This is a special case in that it is invoked during a thread + // state transition. The stack must be set up for walking, and it + // may throw exceptions, but the state is _thread_in_native_trans. + public: + llvm::Value* check_special_condition_for_native_trans(); + + // Intrinsics and external functions, part 5: Low-level non-VM calls. + // These have the same caveats as the high-level non-VM calls + // above. They are not accessed directly; rather, you should + // access them via the various Create* methods below. + private: + llvm::Value* cmpxchg_int(); + llvm::Value* cmpxchg_ptr(); + llvm::Value* frame_address(); + llvm::Value* memory_barrier(); + llvm::Value* memset(); + llvm::Value* unimplemented(); + llvm::Value* should_not_reach_here(); + llvm::Value* dump(); + + // Public interface to low-level non-VM calls. + public: + llvm::CallInst* CreateCmpxchgInt(llvm::Value* exchange_value, + llvm::Value* dst, + llvm::Value* compare_value); + llvm::CallInst* CreateCmpxchgPtr(llvm::Value* exchange_value, + llvm::Value* dst, + llvm::Value* compare_value); + llvm::CallInst* CreateGetFrameAddress(); + llvm::CallInst* CreateMemoryBarrier(int flags); + llvm::CallInst* CreateMemset(llvm::Value* dst, + llvm::Value* value, + llvm::Value* len, + llvm::Value* align); + llvm::CallInst* CreateUnimplemented(const char* file, int line); + llvm::CallInst* CreateShouldNotReachHere(const char* file, int line); + NOT_PRODUCT(llvm::CallInst* CreateDump(llvm::Value* value)); + + // Flags for CreateMemoryBarrier. + public: + enum BarrierFlags { + BARRIER_LOADLOAD = 1, + BARRIER_LOADSTORE = 2, + BARRIER_STORELOAD = 4, + BARRIER_STORESTORE = 8 + }; + + // HotSpot memory barriers + public: + void CreateUpdateBarrierSet(BarrierSet* bs, llvm::Value* field); + + // Helpers for accessing the code buffer. + public: + llvm::Value* code_buffer_address(int offset); + llvm::Value* CreateInlineOop(jobject object, const char* name = ""); + llvm::Value* CreateInlineOop(ciObject* object, const char* name = "") { + return CreateInlineOop(object->constant_encoding(), name); + } + llvm::Value* CreateInlineData(void* data, + size_t size, + const llvm::Type* type, + const char* name = ""); + + // Helpers for creating basic blocks. + // NB don't use unless SharkFunction::CreateBlock is unavailable. + // XXX these are hacky and should be removed. + public: + llvm::BasicBlock* GetBlockInsertionPoint() const; + llvm::BasicBlock* CreateBlock(llvm::BasicBlock* ip, + const char* name="") const; +}; diff --git a/hotspot/src/share/vm/shark/sharkCacheDecache.cpp b/hotspot/src/share/vm/shark/sharkCacheDecache.cpp new file mode 100644 index 00000000000..b9d1c67b802 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkCacheDecache.cpp @@ -0,0 +1,259 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkCacheDecache.cpp.incl" + +using namespace llvm; + +void SharkDecacher::start_frame() { + // Start recording the debug information + _pc_offset = code_buffer()->create_unique_offset(); + _oopmap = new OopMap( + oopmap_slot_munge(stack()->oopmap_frame_size()), + oopmap_slot_munge(arg_size())); + debug_info()->add_safepoint(pc_offset(), oopmap()); +} + +void SharkDecacher::start_stack(int stack_depth) { + // Create the array we'll record our stack slots in + _exparray = new GrowableArray(stack_depth); + + // Set the stack pointer + stack()->CreateStoreStackPointer( + builder()->CreatePtrToInt( + stack()->slot_addr( + stack()->stack_slots_offset() + max_stack() - stack_depth), + SharkType::intptr_type())); +} + +void SharkDecacher::process_stack_slot(int index, + SharkValue** addr, + int offset) { + SharkValue *value = *addr; + + // Write the value to the frame if necessary + if (stack_slot_needs_write(index, value)) { + write_value_to_frame( + SharkType::to_stackType(value->basic_type()), + value->generic_value(), + adjusted_offset(value, offset)); + } + + // Record the value in the oopmap if necessary + if (stack_slot_needs_oopmap(index, value)) { + oopmap()->set_oop(slot2reg(offset)); + } + + // Record the value in the debuginfo if necessary + if (stack_slot_needs_debuginfo(index, value)) { + exparray()->append(slot2lv(offset, stack_location_type(index, addr))); + } +} + +void SharkDecacher::start_monitors(int num_monitors) { + // Create the array we'll record our monitors in + _monarray = new GrowableArray(num_monitors); +} + +void SharkDecacher::process_monitor(int index, int box_offset, int obj_offset) { + oopmap()->set_oop(slot2reg(obj_offset)); + + monarray()->append(new MonitorValue( + slot2lv (obj_offset, Location::oop), + slot2loc(box_offset, Location::normal))); +} + +void SharkDecacher::process_oop_tmp_slot(Value** value, int offset) { + // Decache the temporary oop slot + if (*value) { + write_value_to_frame( + SharkType::oop_type(), + *value, + offset); + + oopmap()->set_oop(slot2reg(offset)); + } +} + +void SharkDecacher::process_method_slot(Value** value, int offset) { + // Decache the method pointer + write_value_to_frame( + SharkType::methodOop_type(), + *value, + offset); + + oopmap()->set_oop(slot2reg(offset)); +} + +void SharkDecacher::process_pc_slot(int offset) { + // Record the PC + builder()->CreateStore( + builder()->code_buffer_address(pc_offset()), + stack()->slot_addr(offset)); +} + +void SharkDecacher::start_locals() { + // Create the array we'll record our local variables in + _locarray = new GrowableArray(max_locals());} + +void SharkDecacher::process_local_slot(int index, + SharkValue** addr, + int offset) { + SharkValue *value = *addr; + + // Write the value to the frame if necessary + if (local_slot_needs_write(index, value)) { + write_value_to_frame( + SharkType::to_stackType(value->basic_type()), + value->generic_value(), + adjusted_offset(value, offset)); + } + + // Record the value in the oopmap if necessary + if (local_slot_needs_oopmap(index, value)) { + oopmap()->set_oop(slot2reg(offset)); + } + + // Record the value in the debuginfo if necessary + if (local_slot_needs_debuginfo(index, value)) { + locarray()->append(slot2lv(offset, local_location_type(index, addr))); + } +} + +void SharkDecacher::end_frame() { + // Record the scope + debug_info()->describe_scope( + pc_offset(), + target(), + bci(), + true, + false, + false, + debug_info()->create_scope_values(locarray()), + debug_info()->create_scope_values(exparray()), + debug_info()->create_monitor_values(monarray())); + + // Finish recording the debug information + debug_info()->end_safepoint(pc_offset()); +} + +void SharkCacher::process_stack_slot(int index, + SharkValue** addr, + int offset) { + SharkValue *value = *addr; + + // Read the value from the frame if necessary + if (stack_slot_needs_read(index, value)) { + *addr = SharkValue::create_generic( + value->type(), + read_value_from_frame( + SharkType::to_stackType(value->basic_type()), + adjusted_offset(value, offset)), + value->zero_checked()); + } +} + +void SharkOSREntryCacher::process_monitor(int index, + int box_offset, + int obj_offset) { + // Copy the monitor from the OSR buffer to the frame + int src_offset = max_locals() + index * 2; + builder()->CreateStore( + builder()->CreateLoad( + CreateAddressOfOSRBufEntry(src_offset, SharkType::intptr_type())), + stack()->slot_addr(box_offset, SharkType::intptr_type())); + builder()->CreateStore( + builder()->CreateLoad( + CreateAddressOfOSRBufEntry(src_offset + 1, SharkType::oop_type())), + stack()->slot_addr(obj_offset, SharkType::oop_type())); +} + +void SharkCacher::process_oop_tmp_slot(Value** value, int offset) { + // Cache the temporary oop + if (*value) + *value = read_value_from_frame(SharkType::oop_type(), offset); +} + +void SharkCacher::process_method_slot(Value** value, int offset) { + // Cache the method pointer + *value = read_value_from_frame(SharkType::methodOop_type(), offset); +} + +void SharkFunctionEntryCacher::process_method_slot(Value** value, int offset) { + // "Cache" the method pointer + *value = method(); +} + +void SharkCacher::process_local_slot(int index, + SharkValue** addr, + int offset) { + SharkValue *value = *addr; + + // Read the value from the frame if necessary + if (local_slot_needs_read(index, value)) { + *addr = SharkValue::create_generic( + value->type(), + read_value_from_frame( + SharkType::to_stackType(value->basic_type()), + adjusted_offset(value, offset)), + value->zero_checked()); + } +} + +Value* SharkOSREntryCacher::CreateAddressOfOSRBufEntry(int offset, + const Type* type) { + Value *result = builder()->CreateStructGEP(osr_buf(), offset); + if (type != SharkType::intptr_type()) + result = builder()->CreateBitCast(result, PointerType::getUnqual(type)); + return result; +} + +void SharkOSREntryCacher::process_local_slot(int index, + SharkValue** addr, + int offset) { + SharkValue *value = *addr; + + // Read the value from the OSR buffer if necessary + if (local_slot_needs_read(index, value)) { + *addr = SharkValue::create_generic( + value->type(), + builder()->CreateLoad( + CreateAddressOfOSRBufEntry( + adjusted_offset(value, max_locals() - 1 - index), + SharkType::to_stackType(value->basic_type()))), + value->zero_checked()); + } +} + +void SharkDecacher::write_value_to_frame(const Type* type, + Value* value, + int offset) { + builder()->CreateStore(value, stack()->slot_addr(offset, type)); +} + +Value* SharkCacher::read_value_from_frame(const Type* type, int offset) { + return builder()->CreateLoad(stack()->slot_addr(offset, type)); +} diff --git a/hotspot/src/share/vm/shark/sharkCacheDecache.hpp b/hotspot/src/share/vm/shark/sharkCacheDecache.hpp new file mode 100644 index 00000000000..9368746566b --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkCacheDecache.hpp @@ -0,0 +1,417 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * 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. + * + */ + +// Class hierarchy: +// - SharkStateScanner +// - SharkCacherDecacher +// - SharkDecacher +// - SharkJavaCallDecacher +// - SharkVMCallDecacher +// - SharkTrapDecacher +// - SharkCacher +// - SharkJavaCallCacher +// - SharkVMCallCacher +// - SharkFunctionEntryCacher +// - SharkNormalEntryCacher +// - SharkOSREntryCacher + +class SharkCacherDecacher : public SharkStateScanner { + protected: + SharkCacherDecacher(SharkFunction* function) + : SharkStateScanner(function) {} + + // Helper + protected: + static int adjusted_offset(SharkValue* value, int offset) { + if (value->is_two_word()) + offset--; + return offset; + } +}; + +class SharkDecacher : public SharkCacherDecacher { + protected: + SharkDecacher(SharkFunction* function, int bci) + : SharkCacherDecacher(function), _bci(bci) {} + + private: + int _bci; + + protected: + int bci() const { + return _bci; + } + + private: + int _pc_offset; + OopMap* _oopmap; + GrowableArray* _exparray; + GrowableArray* _monarray; + GrowableArray* _locarray; + + private: + int pc_offset() const { + return _pc_offset; + } + OopMap* oopmap() const { + return _oopmap; + } + GrowableArray* exparray() const { + return _exparray; + } + GrowableArray* monarray() const { + return _monarray; + } + GrowableArray* locarray() const { + return _locarray; + } + + // Callbacks + protected: + void start_frame(); + + void start_stack(int stack_depth); + void process_stack_slot(int index, SharkValue** value, int offset); + + void start_monitors(int num_monitors); + void process_monitor(int index, int box_offset, int obj_offset); + + void process_oop_tmp_slot(llvm::Value** value, int offset); + void process_method_slot(llvm::Value** value, int offset); + void process_pc_slot(int offset); + + void start_locals(); + void process_local_slot(int index, SharkValue** value, int offset); + + void end_frame(); + + // oopmap and debuginfo helpers + private: + static int oopmap_slot_munge(int offset) { + return SharkStack::oopmap_slot_munge(offset); + } + static VMReg slot2reg(int offset) { + return SharkStack::slot2reg(offset); + } + static Location slot2loc(int offset, Location::Type type) { + return Location::new_stk_loc(type, offset * wordSize); + } + static LocationValue* slot2lv(int offset, Location::Type type) { + return new LocationValue(slot2loc(offset, type)); + } + static Location::Type location_type(SharkValue** addr, bool maybe_two_word) { + // low addresses this end + // Type 32-bit 64-bit + // ---------------------------------------------------- + // stack[0] local[3] jobject oop oop + // stack[1] local[2] NULL normal lng + // stack[2] local[1] jlong normal invalid + // stack[3] local[0] jint normal normal + // + // high addresses this end + + SharkValue *value = *addr; + if (value) { + if (value->is_jobject()) + return Location::oop; +#ifdef _LP64 + if (value->is_two_word()) + return Location::invalid; +#endif // _LP64 + return Location::normal; + } + else { + if (maybe_two_word) { + value = *(addr - 1); + if (value && value->is_two_word()) { +#ifdef _LP64 + if (value->is_jlong()) + return Location::lng; + if (value->is_jdouble()) + return Location::dbl; + ShouldNotReachHere(); +#else + return Location::normal; +#endif // _LP64 + } + } + return Location::invalid; + } + } + + // Stack slot helpers + protected: + virtual bool stack_slot_needs_write(int index, SharkValue* value) = 0; + virtual bool stack_slot_needs_oopmap(int index, SharkValue* value) = 0; + virtual bool stack_slot_needs_debuginfo(int index, SharkValue* value) = 0; + + static Location::Type stack_location_type(int index, SharkValue** addr) { + return location_type(addr, *addr == NULL); + } + + // Local slot helpers + protected: + virtual bool local_slot_needs_write(int index, SharkValue* value) = 0; + virtual bool local_slot_needs_oopmap(int index, SharkValue* value) = 0; + virtual bool local_slot_needs_debuginfo(int index, SharkValue* value) = 0; + + static Location::Type local_location_type(int index, SharkValue** addr) { + return location_type(addr, index > 0); + } + + // Writer helper + protected: + void write_value_to_frame(const llvm::Type* type, + llvm::Value* value, + int offset); +}; + +class SharkJavaCallDecacher : public SharkDecacher { + public: + SharkJavaCallDecacher(SharkFunction* function, int bci, ciMethod* callee) + : SharkDecacher(function, bci), _callee(callee) {} + + private: + ciMethod* _callee; + + protected: + ciMethod* callee() const { + return _callee; + } + + // Stack slot helpers + protected: + bool stack_slot_needs_write(int index, SharkValue* value) { + return value && (index < callee()->arg_size() || value->is_jobject()); + } + bool stack_slot_needs_oopmap(int index, SharkValue* value) { + return value && value->is_jobject() && index >= callee()->arg_size(); + } + bool stack_slot_needs_debuginfo(int index, SharkValue* value) { + return index >= callee()->arg_size(); + } + + // Local slot helpers + protected: + bool local_slot_needs_write(int index, SharkValue* value) { + return value && value->is_jobject(); + } + bool local_slot_needs_oopmap(int index, SharkValue* value) { + return value && value->is_jobject(); + } + bool local_slot_needs_debuginfo(int index, SharkValue* value) { + return true; + } +}; + +class SharkVMCallDecacher : public SharkDecacher { + public: + SharkVMCallDecacher(SharkFunction* function, int bci) + : SharkDecacher(function, bci) {} + + // Stack slot helpers + protected: + bool stack_slot_needs_write(int index, SharkValue* value) { + return value && value->is_jobject(); + } + bool stack_slot_needs_oopmap(int index, SharkValue* value) { + return value && value->is_jobject(); + } + bool stack_slot_needs_debuginfo(int index, SharkValue* value) { + return true; + } + + // Local slot helpers + protected: + bool local_slot_needs_write(int index, SharkValue* value) { + return value && value->is_jobject(); + } + bool local_slot_needs_oopmap(int index, SharkValue* value) { + return value && value->is_jobject(); + } + bool local_slot_needs_debuginfo(int index, SharkValue* value) { + return true; + } +}; + +class SharkTrapDecacher : public SharkDecacher { + public: + SharkTrapDecacher(SharkFunction* function, int bci) + : SharkDecacher(function, bci) {} + + // Stack slot helpers + protected: + bool stack_slot_needs_write(int index, SharkValue* value) { + return value != NULL; + } + bool stack_slot_needs_oopmap(int index, SharkValue* value) { + return value && value->is_jobject(); + } + bool stack_slot_needs_debuginfo(int index, SharkValue* value) { + return true; + } + + // Local slot helpers + protected: + bool local_slot_needs_write(int index, SharkValue* value) { + return value != NULL; + } + bool local_slot_needs_oopmap(int index, SharkValue* value) { + return value && value->is_jobject(); + } + bool local_slot_needs_debuginfo(int index, SharkValue* value) { + return true; + } +}; + +class SharkCacher : public SharkCacherDecacher { + protected: + SharkCacher(SharkFunction* function) + : SharkCacherDecacher(function) {} + + // Callbacks + protected: + void process_stack_slot(int index, SharkValue** value, int offset); + + void process_oop_tmp_slot(llvm::Value** value, int offset); + virtual void process_method_slot(llvm::Value** value, int offset); + + virtual void process_local_slot(int index, SharkValue** value, int offset); + + // Stack slot helper + protected: + virtual bool stack_slot_needs_read(int index, SharkValue* value) = 0; + + // Local slot helper + protected: + virtual bool local_slot_needs_read(int index, SharkValue* value) { + return value && value->is_jobject(); + } + + // Writer helper + protected: + llvm::Value* read_value_from_frame(const llvm::Type* type, int offset); +}; + +class SharkJavaCallCacher : public SharkCacher { + public: + SharkJavaCallCacher(SharkFunction* function, ciMethod* callee) + : SharkCacher(function), _callee(callee) {} + + private: + ciMethod* _callee; + + protected: + ciMethod* callee() const { + return _callee; + } + + // Stack slot helper + protected: + bool stack_slot_needs_read(int index, SharkValue* value) { + return value && (index < callee()->return_type()->size() || + value->is_jobject()); + } +}; + +class SharkVMCallCacher : public SharkCacher { + public: + SharkVMCallCacher(SharkFunction* function) + : SharkCacher(function) {} + + // Stack slot helper + protected: + bool stack_slot_needs_read(int index, SharkValue* value) { + return value && value->is_jobject(); + } +}; + +class SharkFunctionEntryCacher : public SharkCacher { + public: + SharkFunctionEntryCacher(SharkFunction* function, llvm::Value* method) + : SharkCacher(function), _method(method) {} + + private: + llvm::Value* _method; + + private: + llvm::Value* method() const { + return _method; + } + + // Method slot callback + protected: + void process_method_slot(llvm::Value** value, int offset); + + // Stack slot helper + protected: + bool stack_slot_needs_read(int index, SharkValue* value) { + ShouldNotReachHere(); // entry block shouldn't have stack + } + + // Local slot helper + protected: + bool local_slot_needs_read(int index, SharkValue* value) { + return value != NULL; + } +}; + +class SharkNormalEntryCacher : public SharkFunctionEntryCacher { + public: + SharkNormalEntryCacher(SharkFunction* function, llvm::Value* method) + : SharkFunctionEntryCacher(function, method) {} +}; + +class SharkOSREntryCacher : public SharkFunctionEntryCacher { + public: + SharkOSREntryCacher(SharkFunction* function, + llvm::Value* method, + llvm::Value* osr_buf) + : SharkFunctionEntryCacher(function, method), + _osr_buf( + builder()->CreateBitCast( + osr_buf, + llvm::PointerType::getUnqual( + llvm::ArrayType::get( + SharkType::intptr_type(), + max_locals() + max_monitors() * 2)))) {} + + private: + llvm::Value* _osr_buf; + + private: + llvm::Value* osr_buf() const { + return _osr_buf; + } + + // Callbacks + protected: + void process_monitor(int index, int box_offset, int obj_offset); + void process_local_slot(int index, SharkValue** value, int offset); + + // Helper + private: + llvm::Value* CreateAddressOfOSRBufEntry(int offset, const llvm::Type* type); +}; diff --git a/hotspot/src/share/vm/shark/sharkCodeBuffer.hpp b/hotspot/src/share/vm/shark/sharkCodeBuffer.hpp new file mode 100644 index 00000000000..6ead2c3ba39 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkCodeBuffer.hpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009 Red Hat, Inc. + * 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. + * + */ + +class SharkCodeBuffer : public StackObj { + public: + SharkCodeBuffer(MacroAssembler* masm) + : _masm(masm), _base_pc(NULL) {} + + private: + MacroAssembler* _masm; + llvm::Value* _base_pc; + + private: + MacroAssembler* masm() const { + return _masm; + } + + public: + llvm::Value* base_pc() const { + return _base_pc; + } + void set_base_pc(llvm::Value* base_pc) { + assert(_base_pc == NULL, "only do this once"); + _base_pc = base_pc; + } + + // Allocate some space in the buffer and return its address. + // This buffer will have been relocated by the time the method + // is installed, so you can't inline the result in code. + public: + void* malloc(size_t size) const { + masm()->align(BytesPerWord); + void *result = masm()->pc(); + masm()->advance(size); + return result; + } + + // Create a unique offset in the buffer. + public: + int create_unique_offset() const { + int offset = masm()->offset(); + masm()->advance(1); + return offset; + } + + // Inline an oop into the buffer and return its offset. + public: + int inline_oop(jobject object) const { + masm()->align(BytesPerWord); + int offset = masm()->offset(); + masm()->store_oop(object); + return offset; + } + + // Inline a block of non-oop data into the buffer and return its offset. + public: + int inline_data(void *src, size_t size) const { + masm()->align(BytesPerWord); + int offset = masm()->offset(); + void *dst = masm()->pc(); + masm()->advance(size); + memcpy(dst, src, size); + return offset; + } +}; diff --git a/hotspot/src/share/vm/shark/sharkCompiler.cpp b/hotspot/src/share/vm/shark/sharkCompiler.cpp new file mode 100644 index 00000000000..d20e3167fa4 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkCompiler.cpp @@ -0,0 +1,340 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkCompiler.cpp.incl" + +#include + +using namespace llvm; + +#if SHARK_LLVM_VERSION >= 27 +namespace { + cl::opt + MCPU("mcpu"); + + cl::list + MAttrs("mattr", + cl::CommaSeparated); +} +#endif + +SharkCompiler::SharkCompiler() + : AbstractCompiler() { + // Create the lock to protect the memory manager and execution engine + _execution_engine_lock = new Monitor(Mutex::leaf, "SharkExecutionEngineLock"); + MutexLocker locker(execution_engine_lock()); + + // Make LLVM safe for multithreading + if (!llvm_start_multithreaded()) + fatal("llvm_start_multithreaded() failed"); + + // Initialize the native target + InitializeNativeTarget(); + + // Create the two contexts which we'll use + _normal_context = new SharkContext("normal"); + _native_context = new SharkContext("native"); + + // Create the memory manager + _memory_manager = new SharkMemoryManager(); + +#if SHARK_LLVM_VERSION >= 27 + // Finetune LLVM for the current host CPU. + StringMap Features; + bool gotCpuFeatures = llvm::sys::getHostCPUFeatures(Features); + std::string cpu("-mcpu=" + llvm::sys::getHostCPUName()); + + std::vector args; + args.push_back(""); // program name + args.push_back(cpu.c_str()); + + std::string mattr("-mattr="); + if(gotCpuFeatures){ + for(StringMap::iterator I = Features.begin(), + E = Features.end(); I != E; ++I){ + if(I->second){ + std::string attr(I->first()); + mattr+="+"+attr+","; + } + } + args.push_back(mattr.c_str()); + } + + args.push_back(0); // terminator + cl::ParseCommandLineOptions(args.size() - 1, (char **) &args[0]); + + // Create the JIT + std::string ErrorMsg; + + EngineBuilder builder(_normal_context->module()); + builder.setMCPU(MCPU); + builder.setMAttrs(MAttrs); + builder.setJITMemoryManager(memory_manager()); + builder.setEngineKind(EngineKind::JIT); + builder.setErrorStr(&ErrorMsg); + _execution_engine = builder.create(); + + if (!execution_engine()) { + if (!ErrorMsg.empty()) + printf("Error while creating Shark JIT: %s\n",ErrorMsg.c_str()); + else + printf("Unknown error while creating Shark JIT\n"); + exit(1); + } + + execution_engine()->addModule( + _native_context->module()); +#else + _execution_engine = ExecutionEngine::createJIT( + _normal_context->module_provider(), + NULL, memory_manager(), CodeGenOpt::Default); + execution_engine()->addModuleProvider( + _native_context->module_provider()); +#endif + + // All done + mark_initialized(); +} + +void SharkCompiler::initialize() { + ShouldNotCallThis(); +} + +void SharkCompiler::compile_method(ciEnv* env, + ciMethod* target, + int entry_bci) { + assert(is_initialized(), "should be"); + ResourceMark rm; + const char *name = methodname( + target->holder()->name()->as_utf8(), target->name()->as_utf8()); + + // Do the typeflow analysis + ciTypeFlow *flow; + if (entry_bci == InvocationEntryBci) + flow = target->get_flow_analysis(); + else + flow = target->get_osr_flow_analysis(entry_bci); + if (flow->failing()) + return; + if (SharkPrintTypeflowOf != NULL) { + if (!fnmatch(SharkPrintTypeflowOf, name, 0)) + flow->print_on(tty); + } + + // Create the recorders + Arena arena; + env->set_oop_recorder(new OopRecorder(&arena)); + OopMapSet oopmaps; + env->set_debug_info(new DebugInformationRecorder(env->oop_recorder())); + env->debug_info()->set_oopmaps(&oopmaps); + env->set_dependencies(new Dependencies(env)); + + // Create the code buffer and builder + CodeBuffer hscb("Shark", 256 * K, 64 * K); + hscb.initialize_oop_recorder(env->oop_recorder()); + MacroAssembler *masm = new MacroAssembler(&hscb); + SharkCodeBuffer cb(masm); + SharkBuilder builder(&cb); + + // Emit the entry point + SharkEntry *entry = (SharkEntry *) cb.malloc(sizeof(SharkEntry)); + + // Build the LLVM IR for the method + Function *function = SharkFunction::build(env, &builder, flow, name); + + // Generate native code. It's unpleasant that we have to drop into + // the VM to do this -- it blocks safepoints -- but I can't see any + // other way to handle the locking. + { + ThreadInVMfromNative tiv(JavaThread::current()); + generate_native_code(entry, function, name); + } + + // Install the method into the VM + CodeOffsets offsets; + offsets.set_value(CodeOffsets::Deopt, 0); + offsets.set_value(CodeOffsets::Exceptions, 0); + offsets.set_value(CodeOffsets::Verified_Entry, + target->is_static() ? 0 : wordSize); + + ExceptionHandlerTable handler_table; + ImplicitExceptionTable inc_table; + + env->register_method(target, + entry_bci, + &offsets, + 0, + &hscb, + 0, + &oopmaps, + &handler_table, + &inc_table, + this, + env->comp_level(), + false, + false); +} + +nmethod* SharkCompiler::generate_native_wrapper(MacroAssembler* masm, + methodHandle target, + BasicType* arg_types, + BasicType return_type) { + assert(is_initialized(), "should be"); + ResourceMark rm; + const char *name = methodname( + target->klass_name()->as_utf8(), target->name()->as_utf8()); + + // Create the code buffer and builder + SharkCodeBuffer cb(masm); + SharkBuilder builder(&cb); + + // Emit the entry point + SharkEntry *entry = (SharkEntry *) cb.malloc(sizeof(SharkEntry)); + + // Build the LLVM IR for the method + SharkNativeWrapper *wrapper = SharkNativeWrapper::build( + &builder, target, name, arg_types, return_type); + + // Generate native code + generate_native_code(entry, wrapper->function(), name); + + // Return the nmethod for installation in the VM + return nmethod::new_native_nmethod(target, + masm->code(), + 0, + 0, + wrapper->frame_size(), + wrapper->receiver_offset(), + wrapper->lock_offset(), + wrapper->oop_maps()); +} + +void SharkCompiler::generate_native_code(SharkEntry* entry, + Function* function, + const char* name) { + // Print the LLVM bitcode, if requested + if (SharkPrintBitcodeOf != NULL) { + if (!fnmatch(SharkPrintBitcodeOf, name, 0)) + function->dump(); + } + + // Compile to native code + address code = NULL; + context()->add_function(function); + { + MutexLocker locker(execution_engine_lock()); + free_queued_methods(); + + if (SharkPrintAsmOf != NULL) { +#if SHARK_LLVM_VERSION >= 27 +#ifndef NDEBUG + if (!fnmatch(SharkPrintAsmOf, name, 0)) { + llvm::SetCurrentDebugType(X86_ONLY("x86-emitter") NOT_X86("jit")); + llvm::DebugFlag = true; + } + else { + llvm::SetCurrentDebugType(""); + llvm::DebugFlag = false; + } +#endif // !NDEBUG +#else + // NB you need to patch LLVM with http://tinyurl.com/yf3baln for this + std::vector args; + args.push_back(""); // program name + if (!fnmatch(SharkPrintAsmOf, name, 0)) + args.push_back("-debug-only=x86-emitter"); + else + args.push_back("-debug-only=none"); + args.push_back(0); // terminator + cl::ParseCommandLineOptions(args.size() - 1, (char **) &args[0]); +#endif // SHARK_LLVM_VERSION + } + memory_manager()->set_entry_for_function(function, entry); + code = (address) execution_engine()->getPointerToFunction(function); + } + entry->set_entry_point(code); + entry->set_function(function); + entry->set_context(context()); + address code_start = entry->code_start(); + address code_limit = entry->code_limit(); + + // Register generated code for profiling, etc + if (JvmtiExport::should_post_dynamic_code_generated()) + JvmtiExport::post_dynamic_code_generated(name, code_start, code_limit); + + // Print debug information, if requested + if (SharkTraceInstalls) { + tty->print_cr( + " [%p-%p): %s (%d bytes code)", + code_start, code_limit, name, code_limit - code_start); + } +} + +void SharkCompiler::free_compiled_method(address code) { + // This method may only be called when the VM is at a safepoint. + // All _thread_in_vm threads will be waiting for the safepoint to + // finish with the exception of the VM thread, so we can consider + // ourself the owner of the execution engine lock even though we + // can't actually acquire it at this time. + assert(Thread::current()->is_VM_thread(), "must be called by VM thread"); + assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); + + SharkEntry *entry = (SharkEntry *) code; + entry->context()->push_to_free_queue(entry->function()); +} + +void SharkCompiler::free_queued_methods() { + // The free queue is protected by the execution engine lock + assert(execution_engine_lock()->owned_by_self(), "should be"); + + while (true) { + Function *function = context()->pop_from_free_queue(); + if (function == NULL) + break; + + execution_engine()->freeMachineCodeForFunction(function); + function->eraseFromParent(); + } +} + +const char* SharkCompiler::methodname(const char* klass, const char* method) { + char *buf = NEW_RESOURCE_ARRAY(char, strlen(klass) + 2 + strlen(method) + 1); + + char *dst = buf; + for (const char *c = klass; *c; c++) { + if (*c == '/') + *(dst++) = '.'; + else + *(dst++) = *c; + } + *(dst++) = ':'; + *(dst++) = ':'; + for (const char *c = method; *c; c++) { + *(dst++) = *c; + } + *(dst++) = '\0'; + return buf; +} diff --git a/hotspot/src/share/vm/shark/sharkCompiler.hpp b/hotspot/src/share/vm/shark/sharkCompiler.hpp new file mode 100644 index 00000000000..ddac631527b --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkCompiler.hpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * 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. + * + */ + +class SharkContext; + +class SharkCompiler : public AbstractCompiler { + public: + // Creation + SharkCompiler(); + + // Name of this compiler + const char *name() { return "shark"; } + + // Missing feature tests + bool supports_native() { return true; } + bool supports_osr() { return true; } + + // Customization + bool needs_adapters() { return false; } + bool needs_stubs() { return false; } + + // Initialization + void initialize(); + + // Compile a normal (bytecode) method and install it in the VM + void compile_method(ciEnv* env, ciMethod* target, int entry_bci); + + // Generate a wrapper for a native (JNI) method + nmethod* generate_native_wrapper(MacroAssembler* masm, + methodHandle target, + BasicType* arg_types, + BasicType return_type); + + // Free compiled methods (and native wrappers) + void free_compiled_method(address code); + + // Each thread generating IR needs its own context. The normal + // context is used for bytecode methods, and is protected from + // multiple simultaneous accesses by being restricted to the + // compiler thread. The native context is used for JNI methods, + // and is protected from multiple simultaneous accesses by the + // adapter handler library lock. + private: + SharkContext* _normal_context; + SharkContext* _native_context; + + public: + SharkContext* context() const { + if (JavaThread::current()->is_Compiler_thread()) { + return _normal_context; + } + else { + assert(AdapterHandlerLibrary_lock->owned_by_self(), "should be"); + return _native_context; + } + } + + // The LLVM execution engine is the JIT we use to generate native + // code. It is thread safe, but we need to protect it with a lock + // of our own because otherwise LLVM's lock and HotSpot's locks + // interleave and deadlock. The SharkMemoryManager is not thread + // safe, and is protected by the same lock as the execution engine. + private: + Monitor* _execution_engine_lock; + SharkMemoryManager* _memory_manager; + llvm::ExecutionEngine* _execution_engine; + + private: + Monitor* execution_engine_lock() const { + return _execution_engine_lock; + } + SharkMemoryManager* memory_manager() const { + assert(execution_engine_lock()->owned_by_self(), "should be"); + return _memory_manager; + } + llvm::ExecutionEngine* execution_engine() const { + assert(execution_engine_lock()->owned_by_self(), "should be"); + return _execution_engine; + } + + // Global access + public: + static SharkCompiler* compiler() { + AbstractCompiler *compiler = + CompileBroker::compiler(CompLevel_fast_compile); + assert(compiler->is_shark() && compiler->is_initialized(), "should be"); + return (SharkCompiler *) compiler; + } + + // Helpers + private: + static const char* methodname(const char* klass, const char* method); + void generate_native_code(SharkEntry* entry, + llvm::Function* function, + const char* name); + void free_queued_methods(); +}; diff --git a/hotspot/src/share/vm/shark/sharkConstant.cpp b/hotspot/src/share/vm/shark/sharkConstant.cpp new file mode 100644 index 00000000000..439632bd8e3 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkConstant.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkConstant.cpp.incl" + +using namespace llvm; + +SharkConstant* SharkConstant::for_ldc(ciBytecodeStream *iter) { + ciConstant constant = iter->get_constant(); + ciType *type = NULL; + if (constant.basic_type() == T_OBJECT) { + ciEnv *env = ciEnv::current(); + if (constant.as_object()->is_klass()) + type = env->Class_klass(); + else + type = env->String_klass(); + } + return new SharkConstant(constant, type); +} + +SharkConstant* SharkConstant::for_field(ciBytecodeStream *iter) { + bool will_link; + ciField *field = iter->get_field(will_link); + assert(will_link, "typeflow responsibility"); + + return new SharkConstant(field->constant_value(), field->type()); +} + +SharkConstant::SharkConstant(ciConstant constant, ciType *type) { + SharkValue *value = NULL; + + switch (constant.basic_type()) { + case T_BOOLEAN: + case T_BYTE: + case T_CHAR: + case T_SHORT: + case T_INT: + value = SharkValue::jint_constant(constant.as_int()); + break; + + case T_LONG: + value = SharkValue::jlong_constant(constant.as_long()); + break; + + case T_FLOAT: + value = SharkValue::jfloat_constant(constant.as_float()); + break; + + case T_DOUBLE: + value = SharkValue::jdouble_constant(constant.as_double()); + break; + + case T_OBJECT: + case T_ARRAY: + break; + + case T_ILLEGAL: + // out of memory + _is_loaded = false; + return; + + default: + tty->print_cr("Unhandled type %s", type2name(constant.basic_type())); + ShouldNotReachHere(); + } + + // Handle primitive types. We create SharkValues for these + // now; doing so doesn't emit any code, and it allows us to + // delegate a bunch of stuff to the SharkValue code. + if (value) { + _value = value; + _is_loaded = true; + _is_nonzero = value->zero_checked(); + _is_two_word = value->is_two_word(); + return; + } + + // Handle reference types. This is tricky because some + // ciObjects are psuedo-objects that refer to oops which + // have yet to be created. We need to spot the unloaded + // objects (which differ between ldc* and get*, thanks!) + ciObject *object = constant.as_object(); + assert(type != NULL, "shouldn't be"); + if (object->is_klass()) { + // The constant returned for a klass is the ciKlass + // for the entry, but we want the java_mirror. + ciKlass *klass = object->as_klass(); + if (!klass->is_loaded()) { + _is_loaded = false; + return; + } + object = klass->java_mirror(); + } + if (object->is_null_object() || !object->can_be_constant()) { + _is_loaded = false; + return; + } + + _value = NULL; + _object = object; + _type = type; + _is_loaded = true; + _is_nonzero = true; + _is_two_word = false; +} diff --git a/hotspot/src/share/vm/shark/sharkConstant.hpp b/hotspot/src/share/vm/shark/sharkConstant.hpp new file mode 100644 index 00000000000..83b7374269e --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkConstant.hpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009 Red Hat, Inc. + * 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. + * + */ + +class SharkConstant : public ResourceObj { + public: + static SharkConstant* for_ldc(ciBytecodeStream* iter); + static SharkConstant* for_field(ciBytecodeStream* iter); + + private: + SharkConstant(ciConstant constant, ciType* type); + + private: + SharkValue* _value; + ciObject* _object; + ciType* _type; + bool _is_loaded; + bool _is_nonzero; + bool _is_two_word; + + public: + bool is_loaded() const { + return _is_loaded; + } + bool is_nonzero() const { + assert(is_loaded(), "should be"); + return _is_nonzero; + } + bool is_two_word() const { + assert(is_loaded(), "should be"); + return _is_two_word; + } + + public: + SharkValue* value(SharkBuilder* builder) { + assert(is_loaded(), "should be"); + if (_value == NULL) { + _value = SharkValue::create_generic( + _type, builder->CreateInlineOop(_object), _is_nonzero); + } + return _value; + } +}; diff --git a/hotspot/src/share/vm/shark/sharkContext.cpp b/hotspot/src/share/vm/shark/sharkContext.cpp new file mode 100644 index 00000000000..052199fcb82 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkContext.cpp @@ -0,0 +1,180 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009, 2010 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkContext.cpp.incl" + +using namespace llvm; + +SharkContext::SharkContext(const char* name) + : LLVMContext(), + _free_queue(NULL) { + // Create a module to build our functions into + _module = new Module(name, *this); + + // Create basic types + _void_type = Type::getVoidTy(*this); + _bit_type = Type::getInt1Ty(*this); + _jbyte_type = Type::getInt8Ty(*this); + _jshort_type = Type::getInt16Ty(*this); + _jint_type = Type::getInt32Ty(*this); + _jlong_type = Type::getInt64Ty(*this); + _jfloat_type = Type::getFloatTy(*this); + _jdouble_type = Type::getDoubleTy(*this); + + // Create compound types + _itableOffsetEntry_type = PointerType::getUnqual( + ArrayType::get(jbyte_type(), itableOffsetEntry::size() * wordSize)); + + _klass_type = PointerType::getUnqual( + ArrayType::get(jbyte_type(), sizeof(Klass))); + + _jniEnv_type = PointerType::getUnqual( + ArrayType::get(jbyte_type(), sizeof(JNIEnv))); + + _jniHandleBlock_type = PointerType::getUnqual( + ArrayType::get(jbyte_type(), sizeof(JNIHandleBlock))); + + _methodOop_type = PointerType::getUnqual( + ArrayType::get(jbyte_type(), sizeof(methodOopDesc))); + + _monitor_type = ArrayType::get( + jbyte_type(), frame::interpreter_frame_monitor_size() * wordSize); + + _oop_type = PointerType::getUnqual( + ArrayType::get(jbyte_type(), sizeof(oopDesc))); + + _thread_type = PointerType::getUnqual( + ArrayType::get(jbyte_type(), sizeof(JavaThread))); + + _zeroStack_type = PointerType::getUnqual( + ArrayType::get(jbyte_type(), sizeof(ZeroStack))); + + std::vector params; + params.push_back(methodOop_type()); + params.push_back(intptr_type()); + params.push_back(thread_type()); + _entry_point_type = FunctionType::get(jint_type(), params, false); + + params.clear(); + params.push_back(methodOop_type()); + params.push_back(PointerType::getUnqual(jbyte_type())); + params.push_back(intptr_type()); + params.push_back(thread_type()); + _osr_entry_point_type = FunctionType::get(jint_type(), params, false); + + // Create mappings + for (int i = 0; i < T_CONFLICT; i++) { + switch (i) { + case T_BOOLEAN: + _to_stackType[i] = jint_type(); + _to_arrayType[i] = jbyte_type(); + break; + + case T_BYTE: + _to_stackType[i] = jint_type(); + _to_arrayType[i] = jbyte_type(); + break; + + case T_CHAR: + _to_stackType[i] = jint_type(); + _to_arrayType[i] = jshort_type(); + break; + + case T_SHORT: + _to_stackType[i] = jint_type(); + _to_arrayType[i] = jshort_type(); + break; + + case T_INT: + _to_stackType[i] = jint_type(); + _to_arrayType[i] = jint_type(); + break; + + case T_LONG: + _to_stackType[i] = jlong_type(); + _to_arrayType[i] = jlong_type(); + break; + + case T_FLOAT: + _to_stackType[i] = jfloat_type(); + _to_arrayType[i] = jfloat_type(); + break; + + case T_DOUBLE: + _to_stackType[i] = jdouble_type(); + _to_arrayType[i] = jdouble_type(); + break; + + case T_OBJECT: + case T_ARRAY: + _to_stackType[i] = oop_type(); + _to_arrayType[i] = oop_type(); + break; + + case T_ADDRESS: + _to_stackType[i] = intptr_type(); + _to_arrayType[i] = NULL; + break; + + default: + _to_stackType[i] = NULL; + _to_arrayType[i] = NULL; + } + } +} + +class SharkFreeQueueItem : public CHeapObj { + public: + SharkFreeQueueItem(llvm::Function* function, SharkFreeQueueItem *next) + : _function(function), _next(next) {} + + private: + llvm::Function* _function; + SharkFreeQueueItem* _next; + + public: + llvm::Function* function() const { + return _function; + } + SharkFreeQueueItem* next() const { + return _next; + } +}; + +void SharkContext::push_to_free_queue(Function* function) { + _free_queue = new SharkFreeQueueItem(function, _free_queue); +} + +Function* SharkContext::pop_from_free_queue() { + if (_free_queue == NULL) + return NULL; + + SharkFreeQueueItem *item = _free_queue; + Function *function = item->function(); + _free_queue = item->next(); + delete item; + return function; +} diff --git a/hotspot/src/share/vm/shark/sharkContext.hpp b/hotspot/src/share/vm/shark/sharkContext.hpp new file mode 100644 index 00000000000..15f294943e6 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkContext.hpp @@ -0,0 +1,187 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009, 2010 Red Hat, Inc. + * 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. + * + */ + +// The LLVMContext class allows multiple instances of LLVM to operate +// independently of each other in a multithreaded context. We extend +// this here to store things in Shark that are LLVMContext-specific. + +class SharkFreeQueueItem; + +class SharkContext : public llvm::LLVMContext { + public: + SharkContext(const char* name); + + private: + llvm::Module* _module; + +#if SHARK_LLVM_VERSION >= 27 + public: +#else + private: +#endif + llvm::Module* module() const { + return _module; + } + + // Get this thread's SharkContext + public: + static SharkContext& current() { + return *SharkCompiler::compiler()->context(); + } + + // Module accessors + public: +#if SHARK_LLVM_VERSION < 27 + llvm::ModuleProvider* module_provider() const { + return new llvm::ExistingModuleProvider(module()); + } +#endif + void add_function(llvm::Function* function) const { + module()->getFunctionList().push_back(function); + } + llvm::Constant* get_external(const char* name, + const llvm::FunctionType* sig) { + return module()->getOrInsertFunction(name, sig); + } + + // Basic types + private: + const llvm::Type* _void_type; + const llvm::IntegerType* _bit_type; + const llvm::IntegerType* _jbyte_type; + const llvm::IntegerType* _jshort_type; + const llvm::IntegerType* _jint_type; + const llvm::IntegerType* _jlong_type; + const llvm::Type* _jfloat_type; + const llvm::Type* _jdouble_type; + + public: + const llvm::Type* void_type() const { + return _void_type; + } + const llvm::IntegerType* bit_type() const { + return _bit_type; + } + const llvm::IntegerType* jbyte_type() const { + return _jbyte_type; + } + const llvm::IntegerType* jshort_type() const { + return _jshort_type; + } + const llvm::IntegerType* jint_type() const { + return _jint_type; + } + const llvm::IntegerType* jlong_type() const { + return _jlong_type; + } + const llvm::Type* jfloat_type() const { + return _jfloat_type; + } + const llvm::Type* jdouble_type() const { + return _jdouble_type; + } + const llvm::IntegerType* intptr_type() const { + return LP64_ONLY(jlong_type()) NOT_LP64(jint_type()); + } + + // Compound types + private: + const llvm::PointerType* _itableOffsetEntry_type; + const llvm::PointerType* _jniEnv_type; + const llvm::PointerType* _jniHandleBlock_type; + const llvm::PointerType* _klass_type; + const llvm::PointerType* _methodOop_type; + const llvm::ArrayType* _monitor_type; + const llvm::PointerType* _oop_type; + const llvm::PointerType* _thread_type; + const llvm::PointerType* _zeroStack_type; + const llvm::FunctionType* _entry_point_type; + const llvm::FunctionType* _osr_entry_point_type; + + public: + const llvm::PointerType* itableOffsetEntry_type() const { + return _itableOffsetEntry_type; + } + const llvm::PointerType* jniEnv_type() const { + return _jniEnv_type; + } + const llvm::PointerType* jniHandleBlock_type() const { + return _jniHandleBlock_type; + } + const llvm::PointerType* klass_type() const { + return _klass_type; + } + const llvm::PointerType* methodOop_type() const { + return _methodOop_type; + } + const llvm::ArrayType* monitor_type() const { + return _monitor_type; + } + const llvm::PointerType* oop_type() const { + return _oop_type; + } + const llvm::PointerType* thread_type() const { + return _thread_type; + } + const llvm::PointerType* zeroStack_type() const { + return _zeroStack_type; + } + const llvm::FunctionType* entry_point_type() const { + return _entry_point_type; + } + const llvm::FunctionType* osr_entry_point_type() const { + return _osr_entry_point_type; + } + + // Mappings + private: + const llvm::Type* _to_stackType[T_CONFLICT]; + const llvm::Type* _to_arrayType[T_CONFLICT]; + + private: + const llvm::Type* map_type(const llvm::Type* const* table, + BasicType type) const { + assert(type >= 0 && type < T_CONFLICT, "unhandled type"); + const llvm::Type* result = table[type]; + assert(type != NULL, "unhandled type"); + return result; + } + + public: + const llvm::Type* to_stackType(BasicType type) const { + return map_type(_to_stackType, type); + } + const llvm::Type* to_arrayType(BasicType type) const { + return map_type(_to_arrayType, type); + } + + // Functions queued for freeing + private: + SharkFreeQueueItem* _free_queue; + + public: + void push_to_free_queue(llvm::Function* function); + llvm::Function* pop_from_free_queue(); +}; diff --git a/hotspot/src/share/vm/shark/sharkEntry.hpp b/hotspot/src/share/vm/shark/sharkEntry.hpp new file mode 100644 index 00000000000..dc2226028f8 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkEntry.hpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * 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. + * + */ + +class SharkContext; + +class SharkEntry : public ZeroEntry { + private: + address _code_limit; + SharkContext* _context; + llvm::Function* _function; + + public: + address code_start() const { + return entry_point(); + } + address code_limit() const { + return _code_limit; + } + SharkContext* context() const { + return _context; + } + llvm::Function* function() const { + return _function; + } + + public: + void set_code_limit(address code_limit) { + _code_limit = code_limit; + } + void set_context(SharkContext* context) { + _context = context; + } + void set_function(llvm::Function* function) { + _function = function; + } +}; diff --git a/hotspot/src/share/vm/shark/sharkFunction.cpp b/hotspot/src/share/vm/shark/sharkFunction.cpp new file mode 100644 index 00000000000..46f8d91c6d0 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkFunction.cpp @@ -0,0 +1,188 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkFunction.cpp.incl" + +using namespace llvm; + +void SharkFunction::initialize(const char *name) { + // Create the function + _function = Function::Create( + entry_point_type(), + GlobalVariable::InternalLinkage, + name); + + // Get our arguments + Function::arg_iterator ai = function()->arg_begin(); + Argument *method = ai++; + method->setName("method"); + Argument *osr_buf = NULL; + if (is_osr()) { + osr_buf = ai++; + osr_buf->setName("osr_buf"); + } + Argument *base_pc = ai++; + base_pc->setName("base_pc"); + code_buffer()->set_base_pc(base_pc); + Argument *thread = ai++; + thread->setName("thread"); + set_thread(thread); + + // Create the list of blocks + set_block_insertion_point(NULL); + _blocks = NEW_RESOURCE_ARRAY(SharkTopLevelBlock*, block_count()); + for (int i = 0; i < block_count(); i++) { + ciTypeFlow::Block *b = flow()->pre_order_at(i); + + // Work around a bug in pre_order_at() that does not return + // the correct pre-ordering. If pre_order_at() were correct + // this line could simply be: + // _blocks[i] = new SharkTopLevelBlock(this, b); + _blocks[b->pre_order()] = new SharkTopLevelBlock(this, b); + } + + // Walk the tree from the start block to determine which + // blocks are entered and which blocks require phis + SharkTopLevelBlock *start_block = block(flow()->start_block_num()); + assert(start_block->start() == flow()->start_bci(), "blocks out of order"); + start_block->enter(); + + // Initialize all entered blocks + for (int i = 0; i < block_count(); i++) { + if (block(i)->entered()) + block(i)->initialize(); + } + + // Create and push our stack frame + set_block_insertion_point(&function()->front()); + builder()->SetInsertPoint(CreateBlock()); + _stack = SharkStack::CreateBuildAndPushFrame(this, method); + + // Create the entry state + SharkState *entry_state; + if (is_osr()) { + entry_state = new SharkOSREntryState(start_block, method, osr_buf); + + // Free the OSR buffer + builder()->CreateCall(builder()->osr_migration_end(), osr_buf); + } + else { + entry_state = new SharkNormalEntryState(start_block, method); + + // Lock if necessary + if (is_synchronized()) { + SharkTopLevelBlock *locker = + new SharkTopLevelBlock(this, start_block->ciblock()); + locker->add_incoming(entry_state); + + set_block_insertion_point(start_block->entry_block()); + locker->acquire_method_lock(); + + entry_state = locker->current_state(); + } + } + + // Transition into the method proper + start_block->add_incoming(entry_state); + builder()->CreateBr(start_block->entry_block()); + + // Parse the blocks + for (int i = 0; i < block_count(); i++) { + if (!block(i)->entered()) + continue; + + if (i + 1 < block_count()) + set_block_insertion_point(block(i + 1)->entry_block()); + else + set_block_insertion_point(NULL); + + block(i)->emit_IR(); + } + do_deferred_zero_checks(); +} + +class DeferredZeroCheck : public SharkTargetInvariants { + public: + DeferredZeroCheck(SharkTopLevelBlock* block, SharkValue* value) + : SharkTargetInvariants(block), + _block(block), + _value(value), + _bci(block->bci()), + _state(block->current_state()->copy()), + _check_block(builder()->GetInsertBlock()), + _continue_block(function()->CreateBlock("not_zero")) { + builder()->SetInsertPoint(continue_block()); + } + + private: + SharkTopLevelBlock* _block; + SharkValue* _value; + int _bci; + SharkState* _state; + BasicBlock* _check_block; + BasicBlock* _continue_block; + + public: + SharkTopLevelBlock* block() const { + return _block; + } + SharkValue* value() const { + return _value; + } + int bci() const { + return _bci; + } + SharkState* state() const { + return _state; + } + BasicBlock* check_block() const { + return _check_block; + } + BasicBlock* continue_block() const { + return _continue_block; + } + + public: + SharkFunction* function() const { + return block()->function(); + } + + public: + void process() const { + builder()->SetInsertPoint(check_block()); + block()->do_deferred_zero_check(value(), bci(), state(), continue_block()); + } +}; + +void SharkFunction::add_deferred_zero_check(SharkTopLevelBlock* block, + SharkValue* value) { + deferred_zero_checks()->append(new DeferredZeroCheck(block, value)); +} + +void SharkFunction::do_deferred_zero_checks() { + for (int i = 0; i < deferred_zero_checks()->length(); i++) + deferred_zero_checks()->at(i)->process(); +} diff --git a/hotspot/src/share/vm/shark/sharkFunction.hpp b/hotspot/src/share/vm/shark/sharkFunction.hpp new file mode 100644 index 00000000000..bb4c3b66cc3 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkFunction.hpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * 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. + * + */ + +class SharkTopLevelBlock; +class DeferredZeroCheck; + +class SharkFunction : public SharkTargetInvariants { + friend class SharkStackWithNormalFrame; + + public: + static llvm::Function* build(ciEnv* env, + SharkBuilder* builder, + ciTypeFlow* flow, + const char* name) { + SharkFunction function(env, builder, flow, name); + return function.function(); + } + + private: + SharkFunction(ciEnv* env, + SharkBuilder* builder, + ciTypeFlow* flow, + const char* name) + : SharkTargetInvariants(env, builder, flow) { initialize(name); } + + private: + void initialize(const char* name); + + private: + llvm::Function* _function; + SharkTopLevelBlock** _blocks; + GrowableArray _deferred_zero_checks; + SharkStack* _stack; + + public: + llvm::Function* function() const { + return _function; + } + int block_count() const { + return flow()->block_count(); + } + SharkTopLevelBlock* block(int i) const { + assert(i < block_count(), "should be"); + return _blocks[i]; + } + GrowableArray* deferred_zero_checks() { + return &_deferred_zero_checks; + } + SharkStack* stack() const { + return _stack; + } + + // On-stack replacement + private: + bool is_osr() const { + return flow()->is_osr_flow(); + } + const llvm::FunctionType* entry_point_type() const { + if (is_osr()) + return SharkType::osr_entry_point_type(); + else + return SharkType::entry_point_type(); + } + + // Block management + private: + llvm::BasicBlock* _block_insertion_point; + + void set_block_insertion_point(llvm::BasicBlock* block_insertion_point) { + _block_insertion_point = block_insertion_point; + } + llvm::BasicBlock* block_insertion_point() const { + return _block_insertion_point; + } + + public: + llvm::BasicBlock* CreateBlock(const char* name = "") const { + return llvm::BasicBlock::Create( + SharkContext::current(), name, function(), block_insertion_point()); + } + + // Deferred zero checks + public: + void add_deferred_zero_check(SharkTopLevelBlock* block, + SharkValue* value); + + private: + void do_deferred_zero_checks(); +}; diff --git a/hotspot/src/share/vm/shark/sharkInliner.cpp b/hotspot/src/share/vm/shark/sharkInliner.cpp new file mode 100644 index 00000000000..a7599e3fe81 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkInliner.cpp @@ -0,0 +1,749 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkInliner.cpp.incl" + +using namespace llvm; + +class SharkInlineBlock : public SharkBlock { + public: + SharkInlineBlock(ciMethod* target, SharkState* state) + : SharkBlock(state, target), + _outer_state(state), + _entry_state(new SharkState(this)) { + for (int i = target->max_locals() - 1; i >= 0; i--) { + SharkValue *value = NULL; + if (i < target->arg_size()) + value = outer_state()->pop(); + entry_state()->set_local(i, value); + } + } + + private: + SharkState* _outer_state; + SharkState* _entry_state; + + private: + SharkState* outer_state() { + return _outer_state; + } + SharkState* entry_state() { + return _entry_state; + } + + public: + void emit_IR() { + parse_bytecode(0, target()->code_size()); + } + + private: + void do_return(BasicType type) { + if (type != T_VOID) { + SharkValue *result = pop_result(type); + outer_state()->push(result); + if (result->is_two_word()) + outer_state()->push(NULL); + } + } +}; + +class SharkInlinerHelper : public StackObj { + public: + SharkInlinerHelper(ciMethod* target, SharkState* entry_state) + : _target(target), + _entry_state(entry_state), + _iter(target) {} + + private: + ciBytecodeStream _iter; + SharkState* _entry_state; + ciMethod* _target; + + public: + ciBytecodeStream* iter() { + return &_iter; + } + SharkState* entry_state() const { + return _entry_state; + } + ciMethod* target() const { + return _target; + } + + public: + Bytecodes::Code bc() { + return iter()->cur_bc(); + } + int max_locals() const { + return target()->max_locals(); + } + int max_stack() const { + return target()->max_stack(); + } + + // Inlinability check + public: + bool is_inlinable(); + + private: + void initialize_for_check(); + + bool do_getstatic() { + return do_field_access(true, false); + } + bool do_getfield() { + return do_field_access(true, true); + } + bool do_putfield() { + return do_field_access(false, true); + } + bool do_field_access(bool is_get, bool is_field); + + // Local variables for inlinability check + private: + bool* _locals; + + public: + bool* local_addr(int index) const { + assert(index >= 0 && index < max_locals(), "bad local variable index"); + return &_locals[index]; + } + bool local(int index) const { + return *local_addr(index); + } + void set_local(int index, bool value) { + *local_addr(index) = value; + } + + // Expression stack for inlinability check + private: + bool* _stack; + bool* _sp; + + public: + int stack_depth() const { + return _sp - _stack; + } + bool* stack_addr(int slot) const { + assert(slot >= 0 && slot < stack_depth(), "bad stack slot"); + return &_sp[-(slot + 1)]; + } + void push(bool value) { + assert(stack_depth() < max_stack(), "stack overrun"); + *(_sp++) = value; + } + bool pop() { + assert(stack_depth() > 0, "stack underrun"); + return *(--_sp); + } + + // Methods for two-word locals + public: + void push_pair_local(int index) { + push(local(index)); + push(local(index + 1)); + } + void pop_pair_local(int index) { + set_local(index + 1, pop()); + set_local(index, pop()); + } + + // Code generation + public: + void do_inline() { + (new SharkInlineBlock(target(), entry_state()))->emit_IR(); + } +}; + +// Quick checks so we can bail out before doing too much +bool SharkInliner::may_be_inlinable(ciMethod *target) { + // We can't inline native methods + if (target->is_native()) + return false; + + // Not much point inlining abstract ones, and in any + // case we'd need a stack frame to throw the exception + if (target->is_abstract()) + return false; + + // Don't inline anything huge + if (target->code_size() > SharkMaxInlineSize) + return false; + + // Monitors aren't allowed without a frame to put them in + if (target->is_synchronized() || target->has_monitor_bytecodes()) + return false; + + // We don't do control flow + if (target->has_exception_handlers() || target->has_jsrs()) + return false; + + // Don't try to inline constructors, as they must + // eventually call Object. which we can't inline. + // Note that this catches too, but why would + // we be compiling that? + if (target->is_initializer()) + return false; + + // Mustn't inline Object. + // Should be caught by the above, but just in case... + if (target->intrinsic_id() == vmIntrinsics::_Object_init) + return false; + + return true; +} + +// Full-on detailed check, for methods that pass the quick checks +// Inlined methods have no stack frame, so we can't do anything +// that would require one. This means no safepoints (and hence +// no loops) and no VM calls. No VM calls means, amongst other +// things, that no exceptions can be created, which means no null +// checks or divide-by-zero checks are allowed. The lack of null +// checks in particular would eliminate practically everything, +// but we can get around that restriction by relying on the zero- +// check eliminator to strip the checks. To do that, we need to +// walk through the method, tracking which values are and are not +// zero-checked. +bool SharkInlinerHelper::is_inlinable() { + ResourceMark rm; + initialize_for_check(); + + SharkConstant *sc; + bool a, b, c, d; + + iter()->reset_to_bci(0); + while (iter()->next() != ciBytecodeStream::EOBC()) { + switch (bc()) { + case Bytecodes::_nop: + break; + + case Bytecodes::_aconst_null: + push(false); + break; + + case Bytecodes::_iconst_0: + push(false); + break; + case Bytecodes::_iconst_m1: + case Bytecodes::_iconst_1: + case Bytecodes::_iconst_2: + case Bytecodes::_iconst_3: + case Bytecodes::_iconst_4: + case Bytecodes::_iconst_5: + push(true); + break; + + case Bytecodes::_lconst_0: + push(false); + push(false); + break; + case Bytecodes::_lconst_1: + push(true); + push(false); + break; + + case Bytecodes::_fconst_0: + case Bytecodes::_fconst_1: + case Bytecodes::_fconst_2: + push(false); + break; + + case Bytecodes::_dconst_0: + case Bytecodes::_dconst_1: + push(false); + push(false); + break; + + case Bytecodes::_bipush: + push(iter()->get_constant_u1() != 0); + break; + case Bytecodes::_sipush: + push(iter()->get_constant_u2() != 0); + break; + + case Bytecodes::_ldc: + case Bytecodes::_ldc_w: + case Bytecodes::_ldc2_w: + sc = SharkConstant::for_ldc(iter()); + if (!sc->is_loaded()) + return false; + push(sc->is_nonzero()); + if (sc->is_two_word()) + push(false); + break; + + case Bytecodes::_iload_0: + case Bytecodes::_fload_0: + case Bytecodes::_aload_0: + push(local(0)); + break; + case Bytecodes::_lload_0: + case Bytecodes::_dload_0: + push_pair_local(0); + break; + + case Bytecodes::_iload_1: + case Bytecodes::_fload_1: + case Bytecodes::_aload_1: + push(local(1)); + break; + case Bytecodes::_lload_1: + case Bytecodes::_dload_1: + push_pair_local(1); + break; + + case Bytecodes::_iload_2: + case Bytecodes::_fload_2: + case Bytecodes::_aload_2: + push(local(2)); + break; + case Bytecodes::_lload_2: + case Bytecodes::_dload_2: + push_pair_local(2); + break; + + case Bytecodes::_iload_3: + case Bytecodes::_fload_3: + case Bytecodes::_aload_3: + push(local(3)); + break; + case Bytecodes::_lload_3: + case Bytecodes::_dload_3: + push_pair_local(3); + break; + + case Bytecodes::_iload: + case Bytecodes::_fload: + case Bytecodes::_aload: + push(local(iter()->get_index())); + break; + case Bytecodes::_lload: + case Bytecodes::_dload: + push_pair_local(iter()->get_index()); + break; + + case Bytecodes::_istore_0: + case Bytecodes::_fstore_0: + case Bytecodes::_astore_0: + set_local(0, pop()); + break; + case Bytecodes::_lstore_0: + case Bytecodes::_dstore_0: + pop_pair_local(0); + break; + + case Bytecodes::_istore_1: + case Bytecodes::_fstore_1: + case Bytecodes::_astore_1: + set_local(1, pop()); + break; + case Bytecodes::_lstore_1: + case Bytecodes::_dstore_1: + pop_pair_local(1); + break; + + case Bytecodes::_istore_2: + case Bytecodes::_fstore_2: + case Bytecodes::_astore_2: + set_local(2, pop()); + break; + case Bytecodes::_lstore_2: + case Bytecodes::_dstore_2: + pop_pair_local(2); + break; + + case Bytecodes::_istore_3: + case Bytecodes::_fstore_3: + case Bytecodes::_astore_3: + set_local(3, pop()); + break; + case Bytecodes::_lstore_3: + case Bytecodes::_dstore_3: + pop_pair_local(3); + break; + + case Bytecodes::_istore: + case Bytecodes::_fstore: + case Bytecodes::_astore: + set_local(iter()->get_index(), pop()); + break; + case Bytecodes::_lstore: + case Bytecodes::_dstore: + pop_pair_local(iter()->get_index()); + break; + + case Bytecodes::_pop: + pop(); + break; + case Bytecodes::_pop2: + pop(); + pop(); + break; + case Bytecodes::_swap: + a = pop(); + b = pop(); + push(a); + push(b); + break; + case Bytecodes::_dup: + a = pop(); + push(a); + push(a); + break; + case Bytecodes::_dup_x1: + a = pop(); + b = pop(); + push(a); + push(b); + push(a); + break; + case Bytecodes::_dup_x2: + a = pop(); + b = pop(); + c = pop(); + push(a); + push(c); + push(b); + push(a); + break; + case Bytecodes::_dup2: + a = pop(); + b = pop(); + push(b); + push(a); + push(b); + push(a); + break; + case Bytecodes::_dup2_x1: + a = pop(); + b = pop(); + c = pop(); + push(b); + push(a); + push(c); + push(b); + push(a); + break; + case Bytecodes::_dup2_x2: + a = pop(); + b = pop(); + c = pop(); + d = pop(); + push(b); + push(a); + push(d); + push(c); + push(b); + push(a); + break; + + case Bytecodes::_getfield: + if (!do_getfield()) + return false; + break; + case Bytecodes::_getstatic: + if (!do_getstatic()) + return false; + break; + case Bytecodes::_putfield: + if (!do_putfield()) + return false; + break; + + case Bytecodes::_iadd: + case Bytecodes::_isub: + case Bytecodes::_imul: + case Bytecodes::_iand: + case Bytecodes::_ixor: + case Bytecodes::_ishl: + case Bytecodes::_ishr: + case Bytecodes::_iushr: + pop(); + pop(); + push(false); + break; + case Bytecodes::_ior: + a = pop(); + b = pop(); + push(a && b); + break; + case Bytecodes::_idiv: + case Bytecodes::_irem: + if (!pop()) + return false; + pop(); + push(false); + break; + case Bytecodes::_ineg: + break; + + case Bytecodes::_ladd: + case Bytecodes::_lsub: + case Bytecodes::_lmul: + case Bytecodes::_land: + case Bytecodes::_lxor: + pop(); + pop(); + pop(); + pop(); + push(false); + push(false); + break; + case Bytecodes::_lor: + a = pop(); + b = pop(); + push(a && b); + break; + case Bytecodes::_ldiv: + case Bytecodes::_lrem: + pop(); + if (!pop()) + return false; + pop(); + pop(); + push(false); + push(false); + break; + case Bytecodes::_lneg: + break; + case Bytecodes::_lshl: + case Bytecodes::_lshr: + case Bytecodes::_lushr: + pop(); + pop(); + pop(); + push(false); + push(false); + break; + + case Bytecodes::_fadd: + case Bytecodes::_fsub: + case Bytecodes::_fmul: + case Bytecodes::_fdiv: + case Bytecodes::_frem: + pop(); + pop(); + push(false); + break; + case Bytecodes::_fneg: + break; + + case Bytecodes::_dadd: + case Bytecodes::_dsub: + case Bytecodes::_dmul: + case Bytecodes::_ddiv: + case Bytecodes::_drem: + pop(); + pop(); + pop(); + pop(); + push(false); + push(false); + break; + case Bytecodes::_dneg: + break; + + case Bytecodes::_iinc: + set_local(iter()->get_index(), false); + break; + + case Bytecodes::_lcmp: + pop(); + pop(); + pop(); + pop(); + push(false); + break; + + case Bytecodes::_fcmpl: + case Bytecodes::_fcmpg: + pop(); + pop(); + push(false); + break; + + case Bytecodes::_dcmpl: + case Bytecodes::_dcmpg: + pop(); + pop(); + pop(); + pop(); + push(false); + break; + + case Bytecodes::_i2l: + push(false); + break; + case Bytecodes::_i2f: + pop(); + push(false); + break; + case Bytecodes::_i2d: + pop(); + push(false); + push(false); + break; + + case Bytecodes::_l2i: + case Bytecodes::_l2f: + pop(); + pop(); + push(false); + break; + case Bytecodes::_l2d: + pop(); + pop(); + push(false); + push(false); + break; + + case Bytecodes::_f2i: + pop(); + push(false); + break; + case Bytecodes::_f2l: + case Bytecodes::_f2d: + pop(); + push(false); + push(false); + break; + + case Bytecodes::_d2i: + case Bytecodes::_d2f: + pop(); + pop(); + push(false); + break; + case Bytecodes::_d2l: + pop(); + pop(); + push(false); + push(false); + break; + + case Bytecodes::_i2b: + case Bytecodes::_i2c: + case Bytecodes::_i2s: + pop(); + push(false); + break; + + case Bytecodes::_return: + case Bytecodes::_ireturn: + case Bytecodes::_lreturn: + case Bytecodes::_freturn: + case Bytecodes::_dreturn: + case Bytecodes::_areturn: + break; + + default: + return false; + } + } + + return true; +} + +void SharkInlinerHelper::initialize_for_check() { + _locals = NEW_RESOURCE_ARRAY(bool, max_locals()); + _stack = NEW_RESOURCE_ARRAY(bool, max_stack()); + + memset(_locals, 0, max_locals() * sizeof(bool)); + for (int i = 0; i < target()->arg_size(); i++) { + SharkValue *arg = entry_state()->stack(target()->arg_size() - 1 - i); + if (arg && arg->zero_checked()) + set_local(i, true); + } + + _sp = _stack; +} + +bool SharkInlinerHelper::do_field_access(bool is_get, bool is_field) { + assert(is_get || is_field, "can't inline putstatic"); + + // If the holder isn't linked then there isn't a lot we can do + if (!target()->holder()->is_linked()) + return false; + + // Get the field + bool will_link; + ciField *field = iter()->get_field(will_link); + if (!will_link) + return false; + + // If the field is mismatched then an exception needs throwing + if (is_field == field->is_static()) + return false; + + // Pop the value off the stack if necessary + if (!is_get) { + pop(); + if (field->type()->is_two_word()) + pop(); + } + + // Pop and null-check the receiver if necessary + if (is_field) { + if (!pop()) + return false; + } + + // Push the result if necessary + if (is_get) { + bool result_pushed = false; + if (field->is_constant()) { + SharkConstant *sc = SharkConstant::for_field(iter()); + if (sc->is_loaded()) { + push(sc->is_nonzero()); + result_pushed = true; + } + } + + if (!result_pushed) + push(false); + + if (field->type()->is_two_word()) + push(false); + } + + return true; +} + +bool SharkInliner::attempt_inline(ciMethod *target, SharkState *state) { + if (SharkIntrinsics::is_intrinsic(target)) { + SharkIntrinsics::inline_intrinsic(target, state); + return true; + } + + if (may_be_inlinable(target)) { + SharkInlinerHelper inliner(target, state); + if (inliner.is_inlinable()) { + inliner.do_inline(); + return true; + } + } + return false; +} diff --git a/hotspot/src/share/vm/shark/sharkInliner.hpp b/hotspot/src/share/vm/shark/sharkInliner.hpp new file mode 100644 index 00000000000..ee37eb71543 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkInliner.hpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009 Red Hat, Inc. + * 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. + * + */ + +class SharkInliner : public AllStatic { + public: + static bool attempt_inline(ciMethod* target, SharkState* state); + + private: + static bool may_be_inlinable(ciMethod* target); +}; diff --git a/hotspot/src/share/vm/shark/sharkIntrinsics.cpp b/hotspot/src/share/vm/shark/sharkIntrinsics.cpp new file mode 100644 index 00000000000..1ad042b2de3 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkIntrinsics.cpp @@ -0,0 +1,277 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkIntrinsics.cpp.incl" + +using namespace llvm; + +bool SharkIntrinsics::is_intrinsic(ciMethod *target) { + switch (target->intrinsic_id()) { + case vmIntrinsics::_none: + return false; + + // java.lang.Math + case vmIntrinsics::_min: + case vmIntrinsics::_max: + case vmIntrinsics::_dabs: + case vmIntrinsics::_dsin: + case vmIntrinsics::_dcos: + case vmIntrinsics::_dtan: + case vmIntrinsics::_datan2: + case vmIntrinsics::_dsqrt: + case vmIntrinsics::_dlog: + case vmIntrinsics::_dlog10: + case vmIntrinsics::_dpow: + case vmIntrinsics::_dexp: + return true; + + // java.lang.Object + case vmIntrinsics::_getClass: + return true; + + // java.lang.System + case vmIntrinsics::_currentTimeMillis: + return true; + + // java.lang.Thread + case vmIntrinsics::_currentThread: + return true; + + // sun.misc.Unsafe + case vmIntrinsics::_compareAndSwapInt: + return true; + + default: + if (SharkPerformanceWarnings) { + warning( + "unhandled intrinsic vmIntrinsic::%s", + vmIntrinsics::name_at(target->intrinsic_id())); + } + } + return false; +} + +void SharkIntrinsics::inline_intrinsic(ciMethod *target, SharkState *state) { + SharkIntrinsics intrinsic(state, target); + intrinsic.do_intrinsic(); +} + +void SharkIntrinsics::do_intrinsic() { + switch (target()->intrinsic_id()) { + // java.lang.Math + case vmIntrinsics::_min: + do_Math_minmax(llvm::ICmpInst::ICMP_SLE); + break; + case vmIntrinsics::_max: + do_Math_minmax(llvm::ICmpInst::ICMP_SGE); + break; + case vmIntrinsics::_dabs: + do_Math_1to1(builder()->fabs()); + break; + case vmIntrinsics::_dsin: + do_Math_1to1(builder()->sin()); + break; + case vmIntrinsics::_dcos: + do_Math_1to1(builder()->cos()); + break; + case vmIntrinsics::_dtan: + do_Math_1to1(builder()->tan()); + break; + case vmIntrinsics::_datan2: + do_Math_2to1(builder()->atan2()); + break; + case vmIntrinsics::_dsqrt: + do_Math_1to1(builder()->sqrt()); + break; + case vmIntrinsics::_dlog: + do_Math_1to1(builder()->log()); + break; + case vmIntrinsics::_dlog10: + do_Math_1to1(builder()->log10()); + break; + case vmIntrinsics::_dpow: + do_Math_2to1(builder()->pow()); + break; + case vmIntrinsics::_dexp: + do_Math_1to1(builder()->exp()); + break; + + // java.lang.Object + case vmIntrinsics::_getClass: + do_Object_getClass(); + break; + + // java.lang.System + case vmIntrinsics::_currentTimeMillis: + do_System_currentTimeMillis(); + break; + + // java.lang.Thread + case vmIntrinsics::_currentThread: + do_Thread_currentThread(); + break; + + // sun.misc.Unsafe + case vmIntrinsics::_compareAndSwapInt: + do_Unsafe_compareAndSwapInt(); + break; + + default: + ShouldNotReachHere(); + } +} + +void SharkIntrinsics::do_Math_minmax(ICmpInst::Predicate p) { + // Pop the arguments + SharkValue *sb = state()->pop(); + SharkValue *sa = state()->pop(); + Value *a = sa->jint_value(); + Value *b = sb->jint_value(); + + // Perform the test + BasicBlock *ip = builder()->GetBlockInsertionPoint(); + BasicBlock *return_a = builder()->CreateBlock(ip, "return_a"); + BasicBlock *return_b = builder()->CreateBlock(ip, "return_b"); + BasicBlock *done = builder()->CreateBlock(ip, "done"); + + builder()->CreateCondBr(builder()->CreateICmp(p, a, b), return_a, return_b); + + builder()->SetInsertPoint(return_a); + builder()->CreateBr(done); + + builder()->SetInsertPoint(return_b); + builder()->CreateBr(done); + + builder()->SetInsertPoint(done); + PHINode *phi = builder()->CreatePHI(a->getType(), "result"); + phi->addIncoming(a, return_a); + phi->addIncoming(b, return_b); + + // Push the result + state()->push( + SharkValue::create_jint( + phi, + sa->zero_checked() && sb->zero_checked())); +} + +void SharkIntrinsics::do_Math_1to1(Value *function) { + SharkValue *empty = state()->pop(); + assert(empty == NULL, "should be"); + state()->push( + SharkValue::create_jdouble( + builder()->CreateCall( + function, state()->pop()->jdouble_value()))); + state()->push(NULL); +} + +void SharkIntrinsics::do_Math_2to1(Value *function) { + SharkValue *empty = state()->pop(); + assert(empty == NULL, "should be"); + Value *y = state()->pop()->jdouble_value(); + empty = state()->pop(); + assert(empty == NULL, "should be"); + Value *x = state()->pop()->jdouble_value(); + + state()->push( + SharkValue::create_jdouble( + builder()->CreateCall2(function, x, y))); + state()->push(NULL); +} + +void SharkIntrinsics::do_Object_getClass() { + Value *klass = builder()->CreateValueOfStructEntry( + state()->pop()->jobject_value(), + in_ByteSize(oopDesc::klass_offset_in_bytes()), + SharkType::oop_type(), + "klass"); + + Value *klass_part = builder()->CreateAddressOfStructEntry( + klass, + in_ByteSize(klassOopDesc::klass_part_offset_in_bytes()), + SharkType::klass_type(), + "klass_part"); + + state()->push( + SharkValue::create_jobject( + builder()->CreateValueOfStructEntry( + klass_part, + in_ByteSize(Klass::java_mirror_offset_in_bytes()), + SharkType::oop_type(), + "java_mirror"), + true)); +} + +void SharkIntrinsics::do_System_currentTimeMillis() { + state()->push( + SharkValue::create_jlong( + builder()->CreateCall(builder()->current_time_millis()), + false)); + state()->push(NULL); +} + +void SharkIntrinsics::do_Thread_currentThread() { + state()->push( + SharkValue::create_jobject( + builder()->CreateValueOfStructEntry( + thread(), JavaThread::threadObj_offset(), + SharkType::oop_type(), + "threadObj"), + true)); +} + +void SharkIntrinsics::do_Unsafe_compareAndSwapInt() { + // Pop the arguments + Value *x = state()->pop()->jint_value(); + Value *e = state()->pop()->jint_value(); + SharkValue *empty = state()->pop(); + assert(empty == NULL, "should be"); + Value *offset = state()->pop()->jlong_value(); + Value *object = state()->pop()->jobject_value(); + Value *unsafe = state()->pop()->jobject_value(); + + // Convert the offset + offset = builder()->CreateCall( + builder()->unsafe_field_offset_to_byte_offset(), + offset); + + // Locate the field + Value *addr = builder()->CreateIntToPtr( + builder()->CreateAdd( + builder()->CreatePtrToInt(object, SharkType::intptr_type()), + builder()->CreateIntCast(offset, SharkType::intptr_type(), true)), + PointerType::getUnqual(SharkType::jint_type()), + "addr"); + + // Perform the operation + Value *result = builder()->CreateCmpxchgInt(x, addr, e); + + // Push the result + state()->push( + SharkValue::create_jint( + builder()->CreateIntCast( + builder()->CreateICmpEQ(result, e), SharkType::jint_type(), true), + false)); +} diff --git a/hotspot/src/share/vm/shark/sharkIntrinsics.hpp b/hotspot/src/share/vm/shark/sharkIntrinsics.hpp new file mode 100644 index 00000000000..a9f337b6ba7 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkIntrinsics.hpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009 Red Hat, Inc. + * 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. + * + */ + +class SharkIntrinsics : public SharkTargetInvariants { + public: + static bool is_intrinsic(ciMethod* target); + static void inline_intrinsic(ciMethod* target, SharkState* state); + + private: + SharkIntrinsics(SharkState* state, ciMethod* target) + : SharkTargetInvariants(state, target), _state(state) {} + + private: + SharkState* _state; + + private: + SharkState* state() const { + return _state; + } + + private: + void do_intrinsic(); + + private: + void do_Math_minmax(llvm::ICmpInst::Predicate p); + void do_Math_1to1(llvm::Value* function); + void do_Math_2to1(llvm::Value* function); + void do_Object_getClass(); + void do_System_currentTimeMillis(); + void do_Thread_currentThread(); + void do_Unsafe_compareAndSwapInt(); +}; diff --git a/hotspot/src/share/vm/shark/sharkInvariants.cpp b/hotspot/src/share/vm/shark/sharkInvariants.cpp new file mode 100644 index 00000000000..93ddc64e43f --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkInvariants.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkInvariants.cpp.incl" + +int SharkTargetInvariants::count_monitors() { + int result = 0; + if (is_synchronized() || target()->has_monitor_bytecodes()) { + for (int i = 0; i < flow()->block_count(); i++) { + result = MAX2(result, flow()->pre_order_at(i)->monitor_count()); + } + } + return result; +} diff --git a/hotspot/src/share/vm/shark/sharkInvariants.hpp b/hotspot/src/share/vm/shark/sharkInvariants.hpp new file mode 100644 index 00000000000..787aedf5f7c --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkInvariants.hpp @@ -0,0 +1,167 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * 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. + * + */ + +// Base classes used to track various values through the compilation. +// SharkCompileInvariants is used to track values which remain the +// same for the top-level method and any inlined methods it may have +// (ie for the whole compilation). SharkTargetInvariants is used to +// track values which differ between methods. + +class SharkCompileInvariants : public ResourceObj { + protected: + SharkCompileInvariants(ciEnv* env, SharkBuilder* builder) + : _env(env), + _builder(builder), + _thread(NULL) {} + + SharkCompileInvariants(const SharkCompileInvariants* parent) + : _env(parent->_env), + _builder(parent->_builder), + _thread(parent->_thread) {} + + private: + ciEnv* _env; + SharkBuilder* _builder; + llvm::Value* _thread; + + // Top-level broker for HotSpot's Compiler Interface. + // + // Its main purpose is to allow the various CI classes to access + // oops in the VM without having to worry about safepointing. In + // addition to this it acts as a holder for various recorders and + // memory allocators. + // + // Accessing this directly is kind of ugly, so it's private. Add + // new accessors below if you need something from it. + private: + ciEnv* env() const { + assert(_env != NULL, "env not available"); + return _env; + } + + // The SharkBuilder that is used to build LLVM IR. + protected: + SharkBuilder* builder() const { + return _builder; + } + + // Pointer to this thread's JavaThread object. This is not + // available until a short way into SharkFunction creation + // so a setter is required. Assertions are used to enforce + // invariance. + protected: + llvm::Value* thread() const { + assert(_thread != NULL, "thread not available"); + return _thread; + } + void set_thread(llvm::Value* thread) { + assert(_thread == NULL, "thread already set"); + _thread = thread; + } + + // Objects that handle various aspects of the compilation. + protected: + DebugInformationRecorder* debug_info() const { + return env()->debug_info(); + } + Dependencies* dependencies() const { + return env()->dependencies(); + } + SharkCodeBuffer* code_buffer() const { + return builder()->code_buffer(); + } + + // Commonly used classes + protected: + ciInstanceKlass* java_lang_Object_klass() const { + return env()->Object_klass(); + } + ciInstanceKlass* java_lang_Throwable_klass() const { + return env()->Throwable_klass(); + } +}; + +class SharkTargetInvariants : public SharkCompileInvariants { + protected: + SharkTargetInvariants(ciEnv* env, SharkBuilder* builder, ciTypeFlow* flow) + : SharkCompileInvariants(env, builder), + _target(flow->method()), + _flow(flow), + _max_monitors(count_monitors()) {} + + SharkTargetInvariants(const SharkCompileInvariants* parent, ciMethod* target) + : SharkCompileInvariants(parent), + _target(target), + _flow(NULL), + _max_monitors(count_monitors()) {} + + SharkTargetInvariants(const SharkTargetInvariants* parent) + : SharkCompileInvariants(parent), + _target(parent->_target), + _flow(parent->_flow), + _max_monitors(parent->_max_monitors) {} + + private: + int count_monitors(); + + private: + ciMethod* _target; + ciTypeFlow* _flow; + int _max_monitors; + + // The method being compiled. + protected: + ciMethod* target() const { + return _target; + } + + // Typeflow analysis of the method being compiled. + protected: + ciTypeFlow* flow() const { + assert(_flow != NULL, "typeflow not available"); + return _flow; + } + + // Properties of the method. + protected: + int max_locals() const { + return target()->max_locals(); + } + int max_stack() const { + return target()->max_stack(); + } + int max_monitors() const { + return _max_monitors; + } + int arg_size() const { + return target()->arg_size(); + } + bool is_static() const { + return target()->is_static(); + } + bool is_synchronized() const { + return target()->is_synchronized(); + } +}; diff --git a/hotspot/src/share/vm/shark/sharkMemoryManager.cpp b/hotspot/src/share/vm/shark/sharkMemoryManager.cpp new file mode 100644 index 00000000000..37334a4e8af --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkMemoryManager.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkMemoryManager.cpp.incl" + +using namespace llvm; + +void SharkMemoryManager::AllocateGOT() { + mm()->AllocateGOT(); +} + +unsigned char* SharkMemoryManager::getGOTBase() const { + return mm()->getGOTBase(); +} + +unsigned char* SharkMemoryManager::allocateStub(const GlobalValue* F, + unsigned StubSize, + unsigned Alignment) { + return mm()->allocateStub(F, StubSize, Alignment); +} + +unsigned char* SharkMemoryManager::startFunctionBody(const Function* F, + uintptr_t& ActualSize) { + return mm()->startFunctionBody(F, ActualSize); +} + +void SharkMemoryManager::endFunctionBody(const Function* F, + unsigned char* FunctionStart, + unsigned char* FunctionEnd) { + mm()->endFunctionBody(F, FunctionStart, FunctionEnd); + + SharkEntry *entry = get_entry_for_function(F); + if (entry != NULL) + entry->set_code_limit(FunctionEnd); +} + +unsigned char* SharkMemoryManager::startExceptionTable(const Function* F, + uintptr_t& ActualSize) { + return mm()->startExceptionTable(F, ActualSize); +} + +void SharkMemoryManager::endExceptionTable(const Function* F, + unsigned char* TableStart, + unsigned char* TableEnd, + unsigned char* FrameRegister) { + mm()->endExceptionTable(F, TableStart, TableEnd, FrameRegister); +} + +void SharkMemoryManager::setMemoryWritable() { + mm()->setMemoryWritable(); +} + +void SharkMemoryManager::setMemoryExecutable() { + mm()->setMemoryExecutable(); +} + +#if SHARK_LLVM_VERSION >= 27 +void SharkMemoryManager::deallocateExceptionTable(void *ptr) { + mm()->deallocateExceptionTable(ptr); +} + +void SharkMemoryManager::deallocateFunctionBody(void *ptr) { + mm()->deallocateFunctionBody(ptr); +} +#else +void SharkMemoryManager::deallocateMemForFunction(const Function* F) { + return mm()->deallocateMemForFunction(F); +} +#endif + +uint8_t* SharkMemoryManager::allocateGlobal(uintptr_t Size, + unsigned int Alignment) { + return mm()->allocateGlobal(Size, Alignment); +} + +#if SHARK_LLVM_VERSION < 27 +void* SharkMemoryManager::getDlsymTable() const { + return mm()->getDlsymTable(); +} + +void SharkMemoryManager::SetDlsymTable(void *ptr) { + mm()->SetDlsymTable(ptr); +} +#endif + +void SharkMemoryManager::setPoisonMemory(bool poison) { + mm()->setPoisonMemory(poison); +} + +unsigned char *SharkMemoryManager::allocateSpace(intptr_t Size, + unsigned int Alignment) { + return mm()->allocateSpace(Size, Alignment); +} diff --git a/hotspot/src/share/vm/shark/sharkMemoryManager.hpp b/hotspot/src/share/vm/shark/sharkMemoryManager.hpp new file mode 100644 index 00000000000..c2884d0b17b --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkMemoryManager.hpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009 Red Hat, Inc. + * 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. + * + */ + +// SharkMemoryManager wraps the LLVM JIT Memory Manager. We could use +// this to run our own memory allocation policies, but for now all we +// use it for is figuring out where the resulting native code ended up. + +class SharkMemoryManager : public llvm::JITMemoryManager { + public: + SharkMemoryManager() + : _mm(llvm::JITMemoryManager::CreateDefaultMemManager()) {} + + private: + llvm::JITMemoryManager* _mm; + + private: + llvm::JITMemoryManager* mm() const { + return _mm; + } + + private: + std::map _entry_map; + + public: + void set_entry_for_function(const llvm::Function* function, + SharkEntry* entry) { + _entry_map[function] = entry; + } + SharkEntry* get_entry_for_function(const llvm::Function* function) { + return _entry_map[function]; + } + + public: + void AllocateGOT(); + unsigned char* getGOTBase() const; + unsigned char* allocateStub(const llvm::GlobalValue* F, + unsigned StubSize, + unsigned Alignment); + unsigned char* startFunctionBody(const llvm::Function* F, + uintptr_t& ActualSize); + void endFunctionBody(const llvm::Function* F, + unsigned char* FunctionStart, + unsigned char* FunctionEnd); + unsigned char* startExceptionTable(const llvm::Function* F, + uintptr_t& ActualSize); + void endExceptionTable(const llvm::Function* F, + unsigned char* TableStart, + unsigned char* TableEnd, + unsigned char* FrameRegister); +#if SHARK_LLVM_VERSION < 27 + void* getDlsymTable() const; + void SetDlsymTable(void *ptr); +#endif + void setPoisonMemory(bool); + uint8_t* allocateGlobal(uintptr_t, unsigned int); + void setMemoryWritable(); + void setMemoryExecutable(); +#if SHARK_LLVM_VERSION >= 27 + void deallocateExceptionTable(void *ptr); + void deallocateFunctionBody(void *ptr); +#else + void deallocateMemForFunction(const llvm::Function* F); +#endif + unsigned char *allocateSpace(intptr_t Size, + unsigned int Alignment); +}; diff --git a/hotspot/src/share/vm/shark/sharkNativeWrapper.cpp b/hotspot/src/share/vm/shark/sharkNativeWrapper.cpp new file mode 100644 index 00000000000..b46ad80025e --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkNativeWrapper.cpp @@ -0,0 +1,352 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009, 2010 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkNativeWrapper.cpp.incl" + +using namespace llvm; + +void SharkNativeWrapper::initialize(const char *name) { + // Create the function + _function = Function::Create( + SharkType::entry_point_type(), + GlobalVariable::InternalLinkage, + name); + + // Get our arguments + Function::arg_iterator ai = function()->arg_begin(); + Argument *method = ai++; + method->setName("method"); + Argument *base_pc = ai++; + base_pc->setName("base_pc"); + code_buffer()->set_base_pc(base_pc); + Argument *thread = ai++; + thread->setName("thread"); + set_thread(thread); + + // Create and push our stack frame + builder()->SetInsertPoint(CreateBlock()); + _stack = SharkStack::CreateBuildAndPushFrame(this, method); + NOT_PRODUCT(method = NULL); + + // Create the oopmap. We use the one oopmap for every call site in + // the wrapper, which results in the odd mild inefficiency but is a + // damn sight easier to code. + OopMap *oopmap = new OopMap( + SharkStack::oopmap_slot_munge(stack()->oopmap_frame_size()), + SharkStack::oopmap_slot_munge(arg_size())); + oopmap->set_oop(SharkStack::slot2reg(stack()->method_slot_offset())); + + // Set up the oop_tmp slot if required: + // - For static methods we use it to handlize the class argument + // for the call, and to protect the same during slow path locks + // (if synchronized). + // - For methods returning oops, we use it to protect the return + // value across safepoints or slow path unlocking. + if (is_static() || is_returning_oop()) { + _oop_tmp_slot = stack()->slot_addr( + stack()->oop_tmp_slot_offset(), + SharkType::oop_type(), + "oop_tmp_slot"); + + oopmap->set_oop(SharkStack::slot2reg(stack()->oop_tmp_slot_offset())); + } + + // Set up the monitor slot, for synchronized methods + if (is_synchronized()) { + Unimplemented(); + _lock_slot_offset = 23; + } + + // Start building the argument list + std::vector param_types; + std::vector param_values; + const PointerType *box_type = PointerType::getUnqual(SharkType::oop_type()); + + // First argument is the JNIEnv + param_types.push_back(SharkType::jniEnv_type()); + param_values.push_back( + builder()->CreateAddressOfStructEntry( + thread, + JavaThread::jni_environment_offset(), + SharkType::jniEnv_type(), + "jni_environment")); + + // For static methods, the second argument is the class + if (is_static()) { + builder()->CreateStore( + builder()->CreateInlineOop( + JNIHandles::make_local( + target()->method_holder()->klass_part()->java_mirror())), + oop_tmp_slot()); + + param_types.push_back(box_type); + param_values.push_back(oop_tmp_slot()); + + _receiver_slot_offset = stack()->oop_tmp_slot_offset(); + } + else if (is_returning_oop()) { + // The oop_tmp slot is registered in the oopmap, + // so we need to clear it. This is one of the + // mild inefficiencies I mentioned earlier. + builder()->CreateStore(LLVMValue::null(), oop_tmp_slot()); + } + + // Parse the arguments + for (int i = 0; i < arg_size(); i++) { + int slot_offset = stack()->locals_slots_offset() + arg_size() - 1 - i; + int adjusted_offset = slot_offset; + BasicBlock *null, *not_null, *merge; + Value *box; + PHINode *phi; + + switch (arg_type(i)) { + case T_VOID: + break; + + case T_OBJECT: + case T_ARRAY: + null = CreateBlock("null"); + not_null = CreateBlock("not_null"); + merge = CreateBlock("merge"); + + box = stack()->slot_addr(slot_offset, SharkType::oop_type()); + builder()->CreateCondBr( + builder()->CreateICmp( + ICmpInst::ICMP_EQ, + builder()->CreateLoad(box), + LLVMValue::null()), + null, not_null); + + builder()->SetInsertPoint(null); + builder()->CreateBr(merge); + + builder()->SetInsertPoint(not_null); + builder()->CreateBr(merge); + + builder()->SetInsertPoint(merge); + phi = builder()->CreatePHI(box_type, "boxed_object"); + phi->addIncoming(ConstantPointerNull::get(box_type), null); + phi->addIncoming(box, not_null); + box = phi; + + param_types.push_back(box_type); + param_values.push_back(box); + + oopmap->set_oop(SharkStack::slot2reg(slot_offset)); + + if (i == 0 && !is_static()) + _receiver_slot_offset = slot_offset; + + break; + + case T_LONG: + case T_DOUBLE: + adjusted_offset--; + // fall through + + default: + const Type *param_type = SharkType::to_stackType(arg_type(i)); + + param_types.push_back(param_type); + param_values.push_back( + builder()->CreateLoad(stack()->slot_addr(adjusted_offset, param_type))); + } + } + + // The oopmap is now complete, and everything is written + // into the frame except the PC. + int pc_offset = code_buffer()->create_unique_offset(); + + _oop_maps = new OopMapSet(); + oop_maps()->add_gc_map(pc_offset, oopmap); + + builder()->CreateStore( + builder()->code_buffer_address(pc_offset), + stack()->slot_addr(stack()->pc_slot_offset())); + + // Set up the Java frame anchor + stack()->CreateSetLastJavaFrame(); + + // Lock if necessary + if (is_synchronized()) + Unimplemented(); + + // Change the thread state to _thread_in_native + CreateSetThreadState(_thread_in_native); + + // Make the call + BasicType result_type = target()->result_type(); + const Type* return_type; + if (result_type == T_VOID) + return_type = SharkType::void_type(); + else if (is_returning_oop()) + return_type = box_type; + else + return_type = SharkType::to_arrayType(result_type); + Value* native_function = builder()->CreateIntToPtr( + LLVMValue::intptr_constant((intptr_t) target()->native_function()), + PointerType::getUnqual( + FunctionType::get(return_type, param_types, false))); + Value *result = builder()->CreateCall( + native_function, param_values.begin(), param_values.end()); + + // Start the transition back to _thread_in_Java + CreateSetThreadState(_thread_in_native_trans); + + // Make sure new state is visible in the GC thread + if (os::is_MP()) { + if (UseMembar) + builder()->CreateMemoryBarrier(SharkBuilder::BARRIER_STORELOAD); + else + CreateWriteMemorySerializePage(); + } + + // Handle safepoint operations, pending suspend requests, + // and pending asynchronous exceptions. + BasicBlock *check_thread = CreateBlock("check_thread"); + BasicBlock *do_safepoint = CreateBlock("do_safepoint"); + BasicBlock *safepointed = CreateBlock("safepointed"); + + Value *global_state = builder()->CreateLoad( + builder()->CreateIntToPtr( + LLVMValue::intptr_constant( + (intptr_t) SafepointSynchronize::address_of_state()), + PointerType::getUnqual(SharkType::jint_type())), + "global_state"); + + builder()->CreateCondBr( + builder()->CreateICmpNE( + global_state, + LLVMValue::jint_constant(SafepointSynchronize::_not_synchronized)), + do_safepoint, check_thread); + + builder()->SetInsertPoint(check_thread); + Value *thread_state = builder()->CreateValueOfStructEntry( + thread, + JavaThread::suspend_flags_offset(), + SharkType::jint_type(), + "thread_state"); + + builder()->CreateCondBr( + builder()->CreateICmpNE( + thread_state, + LLVMValue::jint_constant(0)), + do_safepoint, safepointed); + + builder()->SetInsertPoint(do_safepoint); + builder()->CreateCall( + builder()->check_special_condition_for_native_trans(), thread); + builder()->CreateBr(safepointed); + + // Finally we can change the thread state to _thread_in_Java + builder()->SetInsertPoint(safepointed); + CreateSetThreadState(_thread_in_Java); + + // Clear the frame anchor + stack()->CreateResetLastJavaFrame(); + + // If there is a pending exception then we can just unwind and + // return. It seems totally wrong that unlocking is skipped here + // but apparently the template interpreter does this so we do too. + BasicBlock *exception = CreateBlock("exception"); + BasicBlock *no_exception = CreateBlock("no_exception"); + + builder()->CreateCondBr( + builder()->CreateICmpEQ( + CreateLoadPendingException(), + LLVMValue::null()), + no_exception, exception); + + builder()->SetInsertPoint(exception); + CreateResetHandleBlock(); + stack()->CreatePopFrame(0); + builder()->CreateRet(LLVMValue::jint_constant(0)); + + builder()->SetInsertPoint(no_exception); + + // If the result was an oop then unbox it before + // releasing the handle it might be protected by + if (is_returning_oop()) { + BasicBlock *null = builder()->GetInsertBlock(); + BasicBlock *not_null = CreateBlock("not_null"); + BasicBlock *merge = CreateBlock("merge"); + + builder()->CreateCondBr( + builder()->CreateICmpNE(result, ConstantPointerNull::get(box_type)), + not_null, merge); + + builder()->SetInsertPoint(not_null); + Value *unboxed_result = builder()->CreateLoad(result); + builder()->CreateBr(merge); + + builder()->SetInsertPoint(merge); + PHINode *phi = builder()->CreatePHI(SharkType::oop_type(), "result"); + phi->addIncoming(LLVMValue::null(), null); + phi->addIncoming(unboxed_result, not_null); + result = phi; + } + + // Reset handle block + CreateResetHandleBlock(); + + // Unlock if necessary. + if (is_synchronized()) + Unimplemented(); + + // Unwind and return + Value *result_addr = stack()->CreatePopFrame(type2size[result_type]); + if (result_type != T_VOID) { + bool needs_cast = false; + bool is_signed = false; + switch (result_type) { + case T_BOOLEAN: + result = builder()->CreateICmpNE(result, LLVMValue::jbyte_constant(0)); + needs_cast = true; + break; + + case T_CHAR: + needs_cast = true; + break; + + case T_BYTE: + case T_SHORT: + needs_cast = true; + is_signed = true; + break; + } + if (needs_cast) { + result = builder()->CreateIntCast( + result, SharkType::to_stackType(result_type), is_signed); + } + + builder()->CreateStore( + result, + builder()->CreateIntToPtr( + result_addr, + PointerType::getUnqual(SharkType::to_stackType(result_type)))); + } + builder()->CreateRet(LLVMValue::jint_constant(0)); +} diff --git a/hotspot/src/share/vm/shark/sharkNativeWrapper.hpp b/hotspot/src/share/vm/shark/sharkNativeWrapper.hpp new file mode 100644 index 00000000000..6e324fe2ea3 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkNativeWrapper.hpp @@ -0,0 +1,182 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2009 Red Hat, Inc. + * 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. + * + */ + +class SharkNativeWrapper : public SharkCompileInvariants { + friend class SharkStackWithNativeFrame; + + public: + static SharkNativeWrapper* build(SharkBuilder* builder, + methodHandle target, + const char* name, + BasicType* arg_types, + BasicType return_type) { + return new SharkNativeWrapper(builder, + target, + name, + arg_types, + return_type); + } + + private: + SharkNativeWrapper(SharkBuilder* builder, + methodHandle target, + const char* name, + BasicType* arg_types, + BasicType return_type) + : SharkCompileInvariants(NULL, builder), + _target(target), + _arg_types(arg_types), + _return_type(return_type), + _lock_slot_offset(0) { initialize(name); } + + private: + void initialize(const char* name); + + private: + methodHandle _target; + BasicType* _arg_types; + BasicType _return_type; + llvm::Function* _function; + SharkStack* _stack; + llvm::Value* _oop_tmp_slot; + OopMapSet* _oop_maps; + int _receiver_slot_offset; + int _lock_slot_offset; + + // The method being compiled. + protected: + methodHandle target() const { + return _target; + } + + // Properties of the method. + protected: + int arg_size() const { + return target()->size_of_parameters(); + } + BasicType arg_type(int i) const { + return _arg_types[i]; + } + BasicType return_type() const { + return _return_type; + } + bool is_static() const { + return target()->is_static(); + } + bool is_synchronized() const { + return target()->is_synchronized(); + } + bool is_returning_oop() const { + return target()->is_returning_oop(); + } + + // The LLVM function we are building. + public: + llvm::Function* function() const { + return _function; + } + + // The Zero stack and our frame on it. + protected: + SharkStack* stack() const { + return _stack; + } + + // Temporary oop storage. + protected: + llvm::Value* oop_tmp_slot() const { + assert(is_static() || is_returning_oop(), "should be"); + return _oop_tmp_slot; + } + + // Information required by nmethod::new_native_nmethod(). + public: + int frame_size() const { + return stack()->oopmap_frame_size(); + } + ByteSize receiver_offset() const { + return in_ByteSize(_receiver_slot_offset * wordSize); + } + ByteSize lock_offset() const { + return in_ByteSize(_lock_slot_offset * wordSize); + } + OopMapSet* oop_maps() const { + return _oop_maps; + } + + // Helpers. + private: + llvm::BasicBlock* CreateBlock(const char* name = "") const { + return llvm::BasicBlock::Create(SharkContext::current(), name, function()); + } + llvm::Value* thread_state_address() const { + return builder()->CreateAddressOfStructEntry( + thread(), JavaThread::thread_state_offset(), + llvm::PointerType::getUnqual(SharkType::jint_type()), + "thread_state_address"); + } + llvm::Value* pending_exception_address() const { + return builder()->CreateAddressOfStructEntry( + thread(), Thread::pending_exception_offset(), + llvm::PointerType::getUnqual(SharkType::oop_type()), + "pending_exception_address"); + } + void CreateSetThreadState(JavaThreadState state) const { + builder()->CreateStore( + LLVMValue::jint_constant(state), thread_state_address()); + } + void CreateWriteMemorySerializePage() const { + builder()->CreateStore( + LLVMValue::jint_constant(1), + builder()->CreateIntToPtr( + builder()->CreateAdd( + LLVMValue::intptr_constant( + (intptr_t) os::get_memory_serialize_page()), + builder()->CreateAnd( + builder()->CreateLShr( + builder()->CreatePtrToInt(thread(), SharkType::intptr_type()), + LLVMValue::intptr_constant(os::get_serialize_page_shift_count())), + LLVMValue::intptr_constant(os::get_serialize_page_mask()))), + llvm::PointerType::getUnqual(SharkType::jint_type()))); + } + void CreateResetHandleBlock() const { + llvm::Value *active_handles = builder()->CreateValueOfStructEntry( + thread(), + JavaThread::active_handles_offset(), + SharkType::jniHandleBlock_type(), + "active_handles"); + builder()->CreateStore( + LLVMValue::intptr_constant(0), + builder()->CreateAddressOfStructEntry( + active_handles, + in_ByteSize(JNIHandleBlock::top_offset_in_bytes()), + llvm::PointerType::getUnqual(SharkType::intptr_type()), + "top")); + } + llvm::LoadInst* CreateLoadPendingException() const { + return builder()->CreateLoad( + pending_exception_address(), "pending_exception"); + } +}; diff --git a/hotspot/src/share/vm/shark/sharkRuntime.cpp b/hotspot/src/share/vm/shark/sharkRuntime.cpp new file mode 100644 index 00000000000..6e8c1714e08 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkRuntime.cpp @@ -0,0 +1,251 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkRuntime.cpp.incl" + +using namespace llvm; + +JRT_ENTRY(int, SharkRuntime::find_exception_handler(JavaThread* thread, + int* indexes, + int num_indexes)) + constantPoolHandle pool(thread, method(thread)->constants()); + KlassHandle exc_klass(thread, ((oop) tos_at(thread, 0))->klass()); + + for (int i = 0; i < num_indexes; i++) { + klassOop tmp = pool->klass_at(indexes[i], CHECK_0); + KlassHandle chk_klass(thread, tmp); + + if (exc_klass() == chk_klass()) + return i; + + if (exc_klass()->klass_part()->is_subtype_of(chk_klass())) + return i; + } + + return -1; +JRT_END + +JRT_ENTRY(void, SharkRuntime::monitorenter(JavaThread* thread, + BasicObjectLock* lock)) + if (PrintBiasedLockingStatistics) + Atomic::inc(BiasedLocking::slow_path_entry_count_addr()); + + Handle object(thread, lock->obj()); + assert(Universe::heap()->is_in_reserved_or_null(object()), "should be"); + if (UseBiasedLocking) { + // Retry fast entry if bias is revoked to avoid unnecessary inflation + ObjectSynchronizer::fast_enter(object, lock->lock(), true, CHECK); + } else { + ObjectSynchronizer::slow_enter(object, lock->lock(), CHECK); + } + assert(Universe::heap()->is_in_reserved_or_null(lock->obj()), "should be"); +JRT_END + +JRT_ENTRY(void, SharkRuntime::monitorexit(JavaThread* thread, + BasicObjectLock* lock)) + Handle object(thread, lock->obj()); + assert(Universe::heap()->is_in_reserved_or_null(object()), "should be"); + if (lock == NULL || object()->is_unlocked()) { + THROW(vmSymbols::java_lang_IllegalMonitorStateException()); + } + ObjectSynchronizer::slow_exit(object(), lock->lock(), thread); +JRT_END + +JRT_ENTRY(void, SharkRuntime::new_instance(JavaThread* thread, int index)) + klassOop k_oop = method(thread)->constants()->klass_at(index, CHECK); + instanceKlassHandle klass(THREAD, k_oop); + + // Make sure we are not instantiating an abstract klass + klass->check_valid_for_instantiation(true, CHECK); + + // Make sure klass is initialized + klass->initialize(CHECK); + + // At this point the class may not be fully initialized + // because of recursive initialization. If it is fully + // initialized & has_finalized is not set, we rewrite + // it into its fast version (Note: no locking is needed + // here since this is an atomic byte write and can be + // done more than once). + // + // Note: In case of classes with has_finalized we don't + // rewrite since that saves us an extra check in + // the fast version which then would call the + // slow version anyway (and do a call back into + // Java). + // If we have a breakpoint, then we don't rewrite + // because the _breakpoint bytecode would be lost. + oop obj = klass->allocate_instance(CHECK); + thread->set_vm_result(obj); +JRT_END + +JRT_ENTRY(void, SharkRuntime::newarray(JavaThread* thread, + BasicType type, + int size)) + oop obj = oopFactory::new_typeArray(type, size, CHECK); + thread->set_vm_result(obj); +JRT_END + +JRT_ENTRY(void, SharkRuntime::anewarray(JavaThread* thread, + int index, + int size)) + klassOop klass = method(thread)->constants()->klass_at(index, CHECK); + objArrayOop obj = oopFactory::new_objArray(klass, size, CHECK); + thread->set_vm_result(obj); +JRT_END + +JRT_ENTRY(void, SharkRuntime::multianewarray(JavaThread* thread, + int index, + int ndims, + int* dims)) + klassOop klass = method(thread)->constants()->klass_at(index, CHECK); + oop obj = arrayKlass::cast(klass)->multi_allocate(ndims, dims, CHECK); + thread->set_vm_result(obj); +JRT_END + +JRT_ENTRY(void, SharkRuntime::register_finalizer(JavaThread* thread, + oop object)) + assert(object->is_oop(), "should be"); + assert(object->klass()->klass_part()->has_finalizer(), "should have"); + instanceKlass::register_finalizer(instanceOop(object), CHECK); +JRT_END + +JRT_ENTRY(void, SharkRuntime::throw_ArithmeticException(JavaThread* thread, + const char* file, + int line)) + Exceptions::_throw_msg( + thread, file, line, + vmSymbols::java_lang_ArithmeticException(), + ""); +JRT_END + +JRT_ENTRY(void, SharkRuntime::throw_ArrayIndexOutOfBoundsException( + JavaThread* thread, + const char* file, + int line, + int index)) + char msg[jintAsStringSize]; + snprintf(msg, sizeof(msg), "%d", index); + Exceptions::_throw_msg( + thread, file, line, + vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), + msg); +JRT_END + +JRT_ENTRY(void, SharkRuntime::throw_ClassCastException(JavaThread* thread, + const char* file, + int line)) + Exceptions::_throw_msg( + thread, file, line, + vmSymbols::java_lang_ClassCastException(), + ""); +JRT_END + +JRT_ENTRY(void, SharkRuntime::throw_NullPointerException(JavaThread* thread, + const char* file, + int line)) + Exceptions::_throw_msg( + thread, file, line, + vmSymbols::java_lang_NullPointerException(), + ""); +JRT_END + +// Non-VM calls +// Nothing in these must ever GC! + +void SharkRuntime::dump(const char *name, intptr_t value) { + oop valueOop = (oop) value; + tty->print("%s = ", name); + if (valueOop->is_oop(true)) + valueOop->print_on(tty); + else if (value >= ' ' && value <= '~') + tty->print("'%c' (%d)", value, value); + else + tty->print("%p", value); + tty->print_cr(""); +} + +bool SharkRuntime::is_subtype_of(klassOop check_klass, klassOop object_klass) { + return object_klass->klass_part()->is_subtype_of(check_klass); +} + +int SharkRuntime::uncommon_trap(JavaThread* thread, int trap_request) { + Thread *THREAD = thread; + + // In C2, uncommon_trap_blob creates a frame, so all the various + // deoptimization functions expect to find the frame of the method + // being deopted one frame down on the stack. We create a dummy + // frame to mirror this. + FakeStubFrame *stubframe = FakeStubFrame::build(CHECK_0); + thread->push_zero_frame(stubframe); + + // Initiate the trap + thread->set_last_Java_frame(); + Deoptimization::UnrollBlock *urb = + Deoptimization::uncommon_trap(thread, trap_request); + thread->reset_last_Java_frame(); + + // Pop our dummy frame and the frame being deoptimized + thread->pop_zero_frame(); + thread->pop_zero_frame(); + + // Push skeleton frames + int number_of_frames = urb->number_of_frames(); + for (int i = 0; i < number_of_frames; i++) { + intptr_t size = urb->frame_sizes()[i]; + InterpreterFrame *frame = InterpreterFrame::build(size, CHECK_0); + thread->push_zero_frame(frame); + } + + // Push another dummy frame + stubframe = FakeStubFrame::build(CHECK_0); + thread->push_zero_frame(stubframe); + + // Fill in the skeleton frames + thread->set_last_Java_frame(); + Deoptimization::unpack_frames(thread, Deoptimization::Unpack_uncommon_trap); + thread->reset_last_Java_frame(); + + // Pop our dummy frame + thread->pop_zero_frame(); + + // Fall back into the interpreter + return number_of_frames; +} + +FakeStubFrame* FakeStubFrame::build(TRAPS) { + ZeroStack *stack = ((JavaThread *) THREAD)->zero_stack(); + stack->overflow_check(header_words, CHECK_NULL); + + stack->push(0); // next_frame, filled in later + intptr_t *fp = stack->sp(); + assert(fp - stack->sp() == next_frame_off, "should be"); + + stack->push(FAKE_STUB_FRAME); + assert(fp - stack->sp() == frame_type_off, "should be"); + + return (FakeStubFrame *) fp; +} diff --git a/hotspot/src/share/vm/shark/sharkRuntime.hpp b/hotspot/src/share/vm/shark/sharkRuntime.hpp new file mode 100644 index 00000000000..5467187b392 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkRuntime.hpp @@ -0,0 +1,83 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * 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. + * + */ + +class SharkRuntime : public AllStatic { + // VM calls + public: + static int find_exception_handler(JavaThread* thread, + int* indexes, + int num_indexes); + + static void monitorenter(JavaThread* thread, BasicObjectLock* lock); + static void monitorexit(JavaThread* thread, BasicObjectLock* lock); + + static void new_instance(JavaThread* thread, int index); + static void newarray(JavaThread* thread, BasicType type, int size); + static void anewarray(JavaThread* thread, int index, int size); + static void multianewarray(JavaThread* thread, + int index, + int ndims, + int* dims); + + static void register_finalizer(JavaThread* thread, oop object); + + static void throw_ArithmeticException(JavaThread* thread, + const char* file, + int line); + static void throw_ArrayIndexOutOfBoundsException(JavaThread* thread, + const char* file, + int line, + int index); + static void throw_ClassCastException(JavaThread* thread, + const char* file, + int line); + static void throw_NullPointerException(JavaThread* thread, + const char* file, + int line); + + // Helpers for VM calls + private: + static const SharkFrame* last_frame(JavaThread *thread) { + return thread->last_frame().zero_sharkframe(); + } + static methodOop method(JavaThread *thread) { + return last_frame(thread)->method(); + } + static address bcp(JavaThread *thread, int bci) { + return method(thread)->code_base() + bci; + } + static int two_byte_index(JavaThread *thread, int bci) { + return Bytes::get_Java_u2(bcp(thread, bci) + 1); + } + static intptr_t tos_at(JavaThread *thread, int offset) { + return *(thread->zero_stack()->sp() + offset); + } + + // Non-VM calls + public: + static void dump(const char *name, intptr_t value); + static bool is_subtype_of(klassOop check_klass, klassOop object_klass); + static int uncommon_trap(JavaThread* thread, int trap_request); +}; diff --git a/hotspot/src/share/vm/shark/sharkStack.cpp b/hotspot/src/share/vm/shark/sharkStack.cpp new file mode 100644 index 00000000000..69058e59b1d --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkStack.cpp @@ -0,0 +1,263 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkStack.cpp.incl" + +using namespace llvm; + +void SharkStack::initialize(Value* method) { + bool setup_sp_and_method = (method != NULL); + + int locals_words = max_locals(); + int extra_locals = locals_words - arg_size(); + int header_words = SharkFrame::header_words; + int monitor_words = max_monitors()*frame::interpreter_frame_monitor_size(); + int stack_words = max_stack(); + int frame_words = header_words + monitor_words + stack_words; + + _extended_frame_size = frame_words + locals_words; + + // Update the stack pointer + Value *stack_pointer = builder()->CreateSub( + CreateLoadStackPointer(), + LLVMValue::intptr_constant((frame_words + extra_locals) * wordSize)); + CreateStackOverflowCheck(stack_pointer); + if (setup_sp_and_method) + CreateStoreStackPointer(stack_pointer); + + // Create the frame + _frame = builder()->CreateIntToPtr( + stack_pointer, + PointerType::getUnqual( + ArrayType::get(SharkType::intptr_type(), extended_frame_size())), + "frame"); + int offset = 0; + + // Expression stack + _stack_slots_offset = offset; + offset += stack_words; + + // Monitors + _monitors_slots_offset = offset; + offset += monitor_words; + + // Temporary oop slot + _oop_tmp_slot_offset = offset++; + + // Method pointer + _method_slot_offset = offset++; + if (setup_sp_and_method) { + builder()->CreateStore( + method, slot_addr(method_slot_offset(), SharkType::methodOop_type())); + } + + // Unextended SP + builder()->CreateStore(stack_pointer, slot_addr(offset++)); + + // PC + _pc_slot_offset = offset++; + + // Frame header + builder()->CreateStore( + LLVMValue::intptr_constant(ZeroFrame::SHARK_FRAME), slot_addr(offset++)); + Value *fp = slot_addr(offset++); + + // Local variables + _locals_slots_offset = offset; + offset += locals_words; + + // Push the frame + assert(offset == extended_frame_size(), "should do"); + builder()->CreateStore(CreateLoadFramePointer(), fp); + CreateStoreFramePointer( + builder()->CreatePtrToInt(fp, SharkType::intptr_type())); +} + +// This function should match ZeroStack::overflow_check +void SharkStack::CreateStackOverflowCheck(Value* sp) { + BasicBlock *zero_ok = CreateBlock("zero_stack_ok"); + BasicBlock *overflow = CreateBlock("stack_overflow"); + BasicBlock *abi_ok = CreateBlock("abi_stack_ok"); + + // Check the Zero stack + builder()->CreateCondBr( + builder()->CreateICmpULT(sp, stack_base()), + overflow, zero_ok); + + // Check the ABI stack + builder()->SetInsertPoint(zero_ok); + Value *stack_top = builder()->CreateSub( + builder()->CreateValueOfStructEntry( + thread(), + Thread::stack_base_offset(), + SharkType::intptr_type(), + "abi_base"), + builder()->CreateValueOfStructEntry( + thread(), + Thread::stack_size_offset(), + SharkType::intptr_type(), + "abi_size")); + Value *free_stack = builder()->CreateSub( + builder()->CreatePtrToInt( + builder()->CreateGetFrameAddress(), + SharkType::intptr_type(), + "abi_sp"), + stack_top); + builder()->CreateCondBr( + builder()->CreateICmpULT( + free_stack, + LLVMValue::intptr_constant(StackShadowPages * os::vm_page_size())), + overflow, abi_ok); + + // Handle overflows + builder()->SetInsertPoint(overflow); + builder()->CreateCall(builder()->throw_StackOverflowError(), thread()); + builder()->CreateRet(LLVMValue::jint_constant(0)); + + builder()->SetInsertPoint(abi_ok); +} + +Value* SharkStack::CreatePopFrame(int result_slots) { + assert(result_slots >= 0 && result_slots <= 2, "should be"); + int locals_to_pop = max_locals() - result_slots; + + Value *fp = CreateLoadFramePointer(); + Value *sp = builder()->CreateAdd( + fp, + LLVMValue::intptr_constant((1 + locals_to_pop) * wordSize)); + + CreateStoreStackPointer(sp); + CreateStoreFramePointer( + builder()->CreateLoad( + builder()->CreateIntToPtr( + fp, PointerType::getUnqual(SharkType::intptr_type())))); + + return sp; +} + +Value* SharkStack::slot_addr(int offset, + const Type* type, + const char* name) const { + bool needs_cast = type && type != SharkType::intptr_type(); + + Value* result = builder()->CreateStructGEP( + _frame, offset, needs_cast ? "" : name); + + if (needs_cast) { + result = builder()->CreateBitCast( + result, PointerType::getUnqual(type), name); + } + return result; +} + +// The bits that differentiate stacks with normal and native frames on top + +SharkStack* SharkStack::CreateBuildAndPushFrame(SharkFunction* function, + Value* method) { + return new SharkStackWithNormalFrame(function, method); +} +SharkStack* SharkStack::CreateBuildAndPushFrame(SharkNativeWrapper* wrapper, + Value* method) { + return new SharkStackWithNativeFrame(wrapper, method); +} + +SharkStackWithNormalFrame::SharkStackWithNormalFrame(SharkFunction* function, + Value* method) + : SharkStack(function), _function(function) { + // For normal frames, the stack pointer and the method slot will + // be set during each decache, so it is not necessary to do them + // at the time the frame is created. However, we set them for + // non-PRODUCT builds to make crash dumps easier to understand. + initialize(PRODUCT_ONLY(NULL) NOT_PRODUCT(method)); +} +SharkStackWithNativeFrame::SharkStackWithNativeFrame(SharkNativeWrapper* wrp, + Value* method) + : SharkStack(wrp), _wrapper(wrp) { + initialize(method); +} + +int SharkStackWithNormalFrame::arg_size() const { + return function()->arg_size(); +} +int SharkStackWithNativeFrame::arg_size() const { + return wrapper()->arg_size(); +} + +int SharkStackWithNormalFrame::max_locals() const { + return function()->max_locals(); +} +int SharkStackWithNativeFrame::max_locals() const { + return wrapper()->arg_size(); +} + +int SharkStackWithNormalFrame::max_stack() const { + return function()->max_stack(); +} +int SharkStackWithNativeFrame::max_stack() const { + return 0; +} + +int SharkStackWithNormalFrame::max_monitors() const { + return function()->max_monitors(); +} +int SharkStackWithNativeFrame::max_monitors() const { + return wrapper()->is_synchronized() ? 1 : 0; +} + +BasicBlock* SharkStackWithNormalFrame::CreateBlock(const char* name) const { + return function()->CreateBlock(name); +} +BasicBlock* SharkStackWithNativeFrame::CreateBlock(const char* name) const { + return wrapper()->CreateBlock(name); +} + +address SharkStackWithNormalFrame::interpreter_entry_point() const { + return (address) CppInterpreter::normal_entry; +} +address SharkStackWithNativeFrame::interpreter_entry_point() const { + return (address) CppInterpreter::native_entry; +} + +#ifndef PRODUCT +void SharkStack::CreateAssertLastJavaSPIsNull() const { +#ifdef ASSERT + BasicBlock *fail = CreateBlock("assert_failed"); + BasicBlock *pass = CreateBlock("assert_ok"); + + builder()->CreateCondBr( + builder()->CreateICmpEQ( + builder()->CreateLoad(last_Java_sp_addr()), + LLVMValue::intptr_constant(0)), + pass, fail); + + builder()->SetInsertPoint(fail); + builder()->CreateShouldNotReachHere(__FILE__, __LINE__); + builder()->CreateUnreachable(); + + builder()->SetInsertPoint(pass); +#endif // ASSERT +} +#endif // !PRODUCT diff --git a/hotspot/src/share/vm/shark/sharkStack.hpp b/hotspot/src/share/vm/shark/sharkStack.hpp new file mode 100644 index 00000000000..e31b0a3f17f --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkStack.hpp @@ -0,0 +1,290 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * 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. + * + */ + +class SharkFunction; +class SharkNativeWrapper; +class SharkStackWithNormalFrame; +class SharkStackWithNativeFrame; + +class SharkStack : public SharkCompileInvariants { + public: + static SharkStack* CreateBuildAndPushFrame( + SharkFunction* function, llvm::Value* method); + static SharkStack* CreateBuildAndPushFrame( + SharkNativeWrapper* wrapper, llvm::Value* method); + + protected: + SharkStack(const SharkCompileInvariants* parent) + : SharkCompileInvariants(parent) {} + + protected: + void initialize(llvm::Value* method); + + protected: + void CreateStackOverflowCheck(llvm::Value* sp); + + // Properties of the method being compiled + protected: + virtual int arg_size() const = 0; + virtual int max_locals() const = 0; + virtual int max_stack() const = 0; + virtual int max_monitors() const = 0; + + // BasicBlock creation + protected: + virtual llvm::BasicBlock* CreateBlock(const char* name = "") const = 0; + + // Interpreter entry point for bailouts + protected: + virtual address interpreter_entry_point() const = 0; + + // Interface with the Zero stack + private: + llvm::Value* zero_stack() const { + return builder()->CreateAddressOfStructEntry( + thread(), + JavaThread::zero_stack_offset(), + SharkType::zeroStack_type(), + "zero_stack"); + } + llvm::Value* stack_base() const { + return builder()->CreateValueOfStructEntry( + zero_stack(), + ZeroStack::base_offset(), + SharkType::intptr_type(), + "stack_base"); + } + llvm::Value* stack_pointer_addr() const { + return builder()->CreateAddressOfStructEntry( + zero_stack(), + ZeroStack::sp_offset(), + llvm::PointerType::getUnqual(SharkType::intptr_type()), + "stack_pointer_addr"); + } + llvm::Value* frame_pointer_addr() const { + return builder()->CreateAddressOfStructEntry( + thread(), + JavaThread::top_zero_frame_offset(), + llvm::PointerType::getUnqual(SharkType::intptr_type()), + "frame_pointer_addr"); + } + + public: + llvm::LoadInst* CreateLoadStackPointer(const char *name = "") { + return builder()->CreateLoad(stack_pointer_addr(), name); + } + llvm::StoreInst* CreateStoreStackPointer(llvm::Value* value) { + return builder()->CreateStore(value, stack_pointer_addr()); + } + llvm::LoadInst* CreateLoadFramePointer(const char *name = "") { + return builder()->CreateLoad(frame_pointer_addr(), name); + } + llvm::StoreInst* CreateStoreFramePointer(llvm::Value* value) { + return builder()->CreateStore(value, frame_pointer_addr()); + } + llvm::Value* CreatePopFrame(int result_slots); + + // Interface with the frame anchor + private: + llvm::Value* last_Java_sp_addr() const { + return builder()->CreateAddressOfStructEntry( + thread(), + JavaThread::last_Java_sp_offset(), + llvm::PointerType::getUnqual(SharkType::intptr_type()), + "last_Java_sp_addr"); + } + llvm::Value* last_Java_fp_addr() const { + return builder()->CreateAddressOfStructEntry( + thread(), + JavaThread::last_Java_fp_offset(), + llvm::PointerType::getUnqual(SharkType::intptr_type()), + "last_Java_fp_addr"); + } + + public: + void CreateSetLastJavaFrame() { + // Note that whenever _last_Java_sp != NULL other anchor fields + // must be valid. The profiler apparently depends on this. + NOT_PRODUCT(CreateAssertLastJavaSPIsNull()); + builder()->CreateStore(CreateLoadFramePointer(), last_Java_fp_addr()); + // XXX There's last_Java_pc as well, but I don't think anything uses it + // Also XXX: should we fence here? Zero doesn't... + builder()->CreateStore(CreateLoadStackPointer(), last_Java_sp_addr()); + // Also also XXX: we could probably cache the sp (and the fp we know??) + } + void CreateResetLastJavaFrame() { + builder()->CreateStore(LLVMValue::intptr_constant(0), last_Java_sp_addr()); + } + + private: + void CreateAssertLastJavaSPIsNull() const PRODUCT_RETURN; + + // Our method's frame + private: + llvm::Value* _frame; + int _extended_frame_size; + int _stack_slots_offset; + + public: + int extended_frame_size() const { + return _extended_frame_size; + } + int oopmap_frame_size() const { + return extended_frame_size() - arg_size(); + } + + // Offsets of things in the frame + private: + int _monitors_slots_offset; + int _oop_tmp_slot_offset; + int _method_slot_offset; + int _pc_slot_offset; + int _locals_slots_offset; + + public: + int stack_slots_offset() const { + return _stack_slots_offset; + } + int oop_tmp_slot_offset() const { + return _oop_tmp_slot_offset; + } + int method_slot_offset() const { + return _method_slot_offset; + } + int pc_slot_offset() const { + return _pc_slot_offset; + } + int locals_slots_offset() const { + return _locals_slots_offset; + } + int monitor_offset(int index) const { + assert(index >= 0 && index < max_monitors(), "invalid monitor index"); + return _monitors_slots_offset + + (max_monitors() - 1 - index) * frame::interpreter_frame_monitor_size(); + } + int monitor_object_offset(int index) const { + return monitor_offset(index) + + (BasicObjectLock::obj_offset_in_bytes() >> LogBytesPerWord); + } + int monitor_header_offset(int index) const { + return monitor_offset(index) + + ((BasicObjectLock::lock_offset_in_bytes() + + BasicLock::displaced_header_offset_in_bytes()) >> LogBytesPerWord); + } + + // Addresses of things in the frame + public: + llvm::Value* slot_addr(int offset, + const llvm::Type* type = NULL, + const char* name = "") const; + + llvm::Value* monitor_addr(int index) const { + return slot_addr( + monitor_offset(index), + SharkType::monitor_type(), + "monitor"); + } + llvm::Value* monitor_object_addr(int index) const { + return slot_addr( + monitor_object_offset(index), + SharkType::oop_type(), + "object_addr"); + } + llvm::Value* monitor_header_addr(int index) const { + return slot_addr( + monitor_header_offset(index), + SharkType::intptr_type(), + "displaced_header_addr"); + } + + // oopmap helpers + public: + static int oopmap_slot_munge(int offset) { + return offset << (LogBytesPerWord - LogBytesPerInt); + } + static VMReg slot2reg(int offset) { + return VMRegImpl::stack2reg(oopmap_slot_munge(offset)); + } +}; + +class SharkStackWithNormalFrame : public SharkStack { + friend class SharkStack; + + protected: + SharkStackWithNormalFrame(SharkFunction* function, llvm::Value* method); + + private: + SharkFunction* _function; + + private: + SharkFunction* function() const { + return _function; + } + + // Properties of the method being compiled + private: + int arg_size() const; + int max_locals() const; + int max_stack() const; + int max_monitors() const; + + // BasicBlock creation + private: + llvm::BasicBlock* CreateBlock(const char* name = "") const; + + // Interpreter entry point for bailouts + private: + address interpreter_entry_point() const; +}; + +class SharkStackWithNativeFrame : public SharkStack { + friend class SharkStack; + + protected: + SharkStackWithNativeFrame(SharkNativeWrapper* wrapper, llvm::Value* method); + + private: + SharkNativeWrapper* _wrapper; + + private: + SharkNativeWrapper* wrapper() const { + return _wrapper; + } + + // Properties of the method being compiled + private: + int arg_size() const; + int max_locals() const; + int max_stack() const; + int max_monitors() const; + + // BasicBlock creation + private: + llvm::BasicBlock* CreateBlock(const char* name = "") const; + + // Interpreter entry point for bailouts + private: + address interpreter_entry_point() const; +}; diff --git a/hotspot/src/share/vm/shark/sharkState.cpp b/hotspot/src/share/vm/shark/sharkState.cpp new file mode 100644 index 00000000000..fd6283d0f4e --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkState.cpp @@ -0,0 +1,389 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkState.cpp.incl" + +using namespace llvm; + +void SharkState::initialize(const SharkState *state) { + _locals = NEW_RESOURCE_ARRAY(SharkValue*, max_locals()); + _stack = NEW_RESOURCE_ARRAY(SharkValue*, max_stack()); + + NOT_PRODUCT(memset(_locals, 23, max_locals() * sizeof(SharkValue *))); + NOT_PRODUCT(memset(_stack, 23, max_stack() * sizeof(SharkValue *))); + _sp = _stack; + + if (state) { + for (int i = 0; i < max_locals(); i++) { + SharkValue *value = state->local(i); + if (value) + value = value->clone(); + set_local(i, value); + } + + for (int i = state->stack_depth() - 1; i >= 0; i--) { + SharkValue *value = state->stack(i); + if (value) + value = value->clone(); + push(value); + } + } + + set_num_monitors(state ? state->num_monitors() : 0); +} + +bool SharkState::equal_to(SharkState *other) { + if (target() != other->target()) + return false; + + if (method() != other->method()) + return false; + + if (oop_tmp() != other->oop_tmp()) + return false; + + if (max_locals() != other->max_locals()) + return false; + + if (stack_depth() != other->stack_depth()) + return false; + + if (num_monitors() != other->num_monitors()) + return false; + + if (has_safepointed() != other->has_safepointed()) + return false; + + // Local variables + for (int i = 0; i < max_locals(); i++) { + SharkValue *value = local(i); + SharkValue *other_value = other->local(i); + + if (value == NULL) { + if (other_value != NULL) + return false; + } + else { + if (other_value == NULL) + return false; + + if (!value->equal_to(other_value)) + return false; + } + } + + // Expression stack + for (int i = 0; i < stack_depth(); i++) { + SharkValue *value = stack(i); + SharkValue *other_value = other->stack(i); + + if (value == NULL) { + if (other_value != NULL) + return false; + } + else { + if (other_value == NULL) + return false; + + if (!value->equal_to(other_value)) + return false; + } + } + + return true; +} + +void SharkState::merge(SharkState* other, + BasicBlock* other_block, + BasicBlock* this_block) { + // Method + Value *this_method = this->method(); + Value *other_method = other->method(); + if (this_method != other_method) { + PHINode *phi = builder()->CreatePHI(SharkType::methodOop_type(), "method"); + phi->addIncoming(this_method, this_block); + phi->addIncoming(other_method, other_block); + set_method(phi); + } + + // Temporary oop slot + Value *this_oop_tmp = this->oop_tmp(); + Value *other_oop_tmp = other->oop_tmp(); + if (this_oop_tmp != other_oop_tmp) { + assert(this_oop_tmp && other_oop_tmp, "can't merge NULL with non-NULL"); + PHINode *phi = builder()->CreatePHI(SharkType::oop_type(), "oop_tmp"); + phi->addIncoming(this_oop_tmp, this_block); + phi->addIncoming(other_oop_tmp, other_block); + set_oop_tmp(phi); + } + + // Monitors + assert(this->num_monitors() == other->num_monitors(), "should be"); + + // Local variables + assert(this->max_locals() == other->max_locals(), "should be"); + for (int i = 0; i < max_locals(); i++) { + SharkValue *this_value = this->local(i); + SharkValue *other_value = other->local(i); + assert((this_value == NULL) == (other_value == NULL), "should be"); + if (this_value != NULL) { + char name[18]; + snprintf(name, sizeof(name), "local_%d_", i); + set_local(i, this_value->merge( + builder(), other_value, other_block, this_block, name)); + } + } + + // Expression stack + assert(this->stack_depth() == other->stack_depth(), "should be"); + for (int i = 0; i < stack_depth(); i++) { + SharkValue *this_value = this->stack(i); + SharkValue *other_value = other->stack(i); + assert((this_value == NULL) == (other_value == NULL), "should be"); + if (this_value != NULL) { + char name[18]; + snprintf(name, sizeof(name), "stack_%d_", i); + set_stack(i, this_value->merge( + builder(), other_value, other_block, this_block, name)); + } + } + + // Safepointed status + set_has_safepointed(this->has_safepointed() && other->has_safepointed()); +} + +void SharkState::replace_all(SharkValue* old_value, SharkValue* new_value) { + // Local variables + for (int i = 0; i < max_locals(); i++) { + if (local(i) == old_value) + set_local(i, new_value); + } + + // Expression stack + for (int i = 0; i < stack_depth(); i++) { + if (stack(i) == old_value) + set_stack(i, new_value); + } +} + +SharkNormalEntryState::SharkNormalEntryState(SharkTopLevelBlock* block, + Value* method) + : SharkState(block) { + assert(!block->stack_depth_at_entry(), "entry block shouldn't have stack"); + + // Local variables + for (int i = 0; i < max_locals(); i++) { + ciType *type = block->local_type_at_entry(i); + + SharkValue *value = NULL; + switch (type->basic_type()) { + case T_INT: + case T_LONG: + case T_FLOAT: + case T_DOUBLE: + case T_OBJECT: + case T_ARRAY: + if (i >= arg_size()) { + ShouldNotReachHere(); + } + value = SharkValue::create_generic(type, NULL, i == 0 && !is_static()); + break; + + case ciTypeFlow::StateVector::T_NULL: + value = SharkValue::null(); + break; + + case ciTypeFlow::StateVector::T_BOTTOM: + break; + + case ciTypeFlow::StateVector::T_LONG2: + case ciTypeFlow::StateVector::T_DOUBLE2: + break; + + default: + ShouldNotReachHere(); + } + set_local(i, value); + } + SharkNormalEntryCacher(block->function(), method).scan(this); +} + +SharkOSREntryState::SharkOSREntryState(SharkTopLevelBlock* block, + Value* method, + Value* osr_buf) + : SharkState(block) { + assert(!block->stack_depth_at_entry(), "entry block shouldn't have stack"); + set_num_monitors(block->ciblock()->monitor_count()); + + // Local variables + for (int i = 0; i < max_locals(); i++) { + ciType *type = block->local_type_at_entry(i); + + SharkValue *value = NULL; + switch (type->basic_type()) { + case T_INT: + case T_LONG: + case T_FLOAT: + case T_DOUBLE: + case T_OBJECT: + case T_ARRAY: + value = SharkValue::create_generic(type, NULL, false); + break; + + case ciTypeFlow::StateVector::T_NULL: + value = SharkValue::null(); + break; + + case ciTypeFlow::StateVector::T_BOTTOM: + break; + + case ciTypeFlow::StateVector::T_LONG2: + case ciTypeFlow::StateVector::T_DOUBLE2: + break; + + default: + ShouldNotReachHere(); + } + set_local(i, value); + } + SharkOSREntryCacher(block->function(), method, osr_buf).scan(this); +} + +SharkPHIState::SharkPHIState(SharkTopLevelBlock* block) + : SharkState(block), _block(block) { + BasicBlock *saved_insert_point = builder()->GetInsertBlock(); + builder()->SetInsertPoint(block->entry_block()); + char name[18]; + + // Method + set_method(builder()->CreatePHI(SharkType::methodOop_type(), "method")); + + // Local variables + for (int i = 0; i < max_locals(); i++) { + ciType *type = block->local_type_at_entry(i); + if (type->basic_type() == (BasicType) ciTypeFlow::StateVector::T_NULL) { + // XXX we could do all kinds of clever stuff here + type = ciType::make(T_OBJECT); // XXX what about T_ARRAY? + } + + SharkValue *value = NULL; + switch (type->basic_type()) { + case T_INT: + case T_LONG: + case T_FLOAT: + case T_DOUBLE: + case T_OBJECT: + case T_ARRAY: + snprintf(name, sizeof(name), "local_%d_", i); + value = SharkValue::create_phi( + type, builder()->CreatePHI(SharkType::to_stackType(type), name)); + break; + + case T_ADDRESS: + value = SharkValue::address_constant(type->as_return_address()->bci()); + break; + + case ciTypeFlow::StateVector::T_BOTTOM: + break; + + case ciTypeFlow::StateVector::T_LONG2: + case ciTypeFlow::StateVector::T_DOUBLE2: + break; + + default: + ShouldNotReachHere(); + } + set_local(i, value); + } + + // Expression stack + for (int i = 0; i < block->stack_depth_at_entry(); i++) { + ciType *type = block->stack_type_at_entry(i); + if (type->basic_type() == (BasicType) ciTypeFlow::StateVector::T_NULL) { + // XXX we could do all kinds of clever stuff here + type = ciType::make(T_OBJECT); // XXX what about T_ARRAY? + } + + SharkValue *value = NULL; + switch (type->basic_type()) { + case T_INT: + case T_LONG: + case T_FLOAT: + case T_DOUBLE: + case T_OBJECT: + case T_ARRAY: + snprintf(name, sizeof(name), "stack_%d_", i); + value = SharkValue::create_phi( + type, builder()->CreatePHI(SharkType::to_stackType(type), name)); + break; + + case T_ADDRESS: + value = SharkValue::address_constant(type->as_return_address()->bci()); + break; + + case ciTypeFlow::StateVector::T_LONG2: + case ciTypeFlow::StateVector::T_DOUBLE2: + break; + + default: + ShouldNotReachHere(); + } + push(value); + } + + // Monitors + set_num_monitors(block->ciblock()->monitor_count()); + + builder()->SetInsertPoint(saved_insert_point); +} + +void SharkPHIState::add_incoming(SharkState* incoming_state) { + BasicBlock *predecessor = builder()->GetInsertBlock(); + + // Method + ((PHINode *) method())->addIncoming(incoming_state->method(), predecessor); + + // Local variables + for (int i = 0; i < max_locals(); i++) { + if (local(i) != NULL) + local(i)->addIncoming(incoming_state->local(i), predecessor); + } + + // Expression stack + int stack_depth = block()->stack_depth_at_entry(); + assert(stack_depth == incoming_state->stack_depth(), "should be"); + for (int i = 0; i < stack_depth; i++) { + assert((stack(i) == NULL) == (incoming_state->stack(i) == NULL), "oops"); + if (stack(i)) + stack(i)->addIncoming(incoming_state->stack(i), predecessor); + } + + // Monitors + assert(num_monitors() == incoming_state->num_monitors(), "should be"); + + // Temporary oop slot + assert(oop_tmp() == incoming_state->oop_tmp(), "should be"); +} diff --git a/hotspot/src/share/vm/shark/sharkState.hpp b/hotspot/src/share/vm/shark/sharkState.hpp new file mode 100644 index 00000000000..85d8ea70c49 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkState.hpp @@ -0,0 +1,188 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * 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. + * + */ + +class SharkState : public SharkTargetInvariants { + public: + SharkState(const SharkTargetInvariants* parent) + : SharkTargetInvariants(parent), + _method(NULL), + _oop_tmp(NULL), + _has_safepointed(false) { initialize(NULL); } + + SharkState(const SharkState* state) + : SharkTargetInvariants(state), + _method(state->_method), + _oop_tmp(state->_oop_tmp), + _has_safepointed(state->_has_safepointed) { initialize(state); } + + private: + void initialize(const SharkState* state); + + private: + llvm::Value* _method; + SharkValue** _locals; + SharkValue** _stack; + SharkValue** _sp; + int _num_monitors; + llvm::Value* _oop_tmp; + bool _has_safepointed; + + // Method + public: + llvm::Value** method_addr() { + return &_method; + } + llvm::Value* method() const { + return _method; + } + protected: + void set_method(llvm::Value* method) { + _method = method; + } + + // Local variables + public: + SharkValue** local_addr(int index) const { + assert(index >= 0 && index < max_locals(), "bad local variable index"); + return &_locals[index]; + } + SharkValue* local(int index) const { + return *local_addr(index); + } + void set_local(int index, SharkValue* value) { + *local_addr(index) = value; + } + + // Expression stack + public: + SharkValue** stack_addr(int slot) const { + assert(slot >= 0 && slot < stack_depth(), "bad stack slot"); + return &_sp[-(slot + 1)]; + } + SharkValue* stack(int slot) const { + return *stack_addr(slot); + } + protected: + void set_stack(int slot, SharkValue* value) { + *stack_addr(slot) = value; + } + public: + int stack_depth() const { + return _sp - _stack; + } + void push(SharkValue* value) { + assert(stack_depth() < max_stack(), "stack overrun"); + *(_sp++) = value; + } + SharkValue* pop() { + assert(stack_depth() > 0, "stack underrun"); + return *(--_sp); + } + + // Monitors + public: + int num_monitors() const { + return _num_monitors; + } + void set_num_monitors(int num_monitors) { + _num_monitors = num_monitors; + } + + // Temporary oop slot + public: + llvm::Value** oop_tmp_addr() { + return &_oop_tmp; + } + llvm::Value* oop_tmp() const { + return _oop_tmp; + } + void set_oop_tmp(llvm::Value* oop_tmp) { + _oop_tmp = oop_tmp; + } + + // Safepointed status + public: + bool has_safepointed() const { + return _has_safepointed; + } + void set_has_safepointed(bool has_safepointed) { + _has_safepointed = has_safepointed; + } + + // Comparison + public: + bool equal_to(SharkState* other); + + // Copy and merge + public: + SharkState* copy() const { + return new SharkState(this); + } + void merge(SharkState* other, + llvm::BasicBlock* other_block, + llvm::BasicBlock* this_block); + + // Value replacement + public: + void replace_all(SharkValue* old_value, SharkValue* new_value); +}; + +class SharkTopLevelBlock; + +// SharkNormalEntryState objects are used to create the state +// that the method will be entered with for a normal invocation. +class SharkNormalEntryState : public SharkState { + public: + SharkNormalEntryState(SharkTopLevelBlock* block, + llvm::Value* method); +}; + +// SharkOSREntryState objects are used to create the state +// that the method will be entered with for an OSR invocation. +class SharkOSREntryState : public SharkState { + public: + SharkOSREntryState(SharkTopLevelBlock* block, + llvm::Value* method, + llvm::Value* osr_buf); +}; + +// SharkPHIState objects are used to manage the entry state +// for blocks with more than one entry path or for blocks +// entered from blocks that will be compiled later. +class SharkPHIState : public SharkState { + public: + SharkPHIState(SharkTopLevelBlock* block); + + private: + SharkTopLevelBlock* _block; + + private: + SharkTopLevelBlock* block() const { + return _block; + } + + public: + void add_incoming(SharkState* incoming_state); +}; diff --git a/hotspot/src/share/vm/shark/sharkStateScanner.cpp b/hotspot/src/share/vm/shark/sharkStateScanner.cpp new file mode 100644 index 00000000000..de588b19bcf --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkStateScanner.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkStateScanner.cpp.incl" + +using namespace llvm; + +void SharkStateScanner::scan(SharkState* state) { + start_frame(); + + // Expression stack + stack_integrity_checks(state); + start_stack(state->stack_depth()); + for (int i = state->stack_depth() - 1; i >= 0; i--) { + process_stack_slot( + i, + state->stack_addr(i), + stack()->stack_slots_offset() + + i + max_stack() - state->stack_depth()); + } + end_stack(); + + // Monitors + start_monitors(state->num_monitors()); + for (int i = 0; i < state->num_monitors(); i++) { + process_monitor( + i, + stack()->monitor_offset(i), + stack()->monitor_object_offset(i)); + } + end_monitors(); + + // Frame header + start_frame_header(); + process_oop_tmp_slot( + state->oop_tmp_addr(), stack()->oop_tmp_slot_offset()); + process_method_slot(state->method_addr(), stack()->method_slot_offset()); + process_pc_slot(stack()->pc_slot_offset()); + end_frame_header(); + + // Local variables + locals_integrity_checks(state); + start_locals(); + for (int i = 0; i < max_locals(); i++) { + process_local_slot( + i, + state->local_addr(i), + stack()->locals_slots_offset() + max_locals() - 1 - i); + } + end_locals(); + + end_frame(); +} + +#ifndef PRODUCT +void SharkStateScanner::stack_integrity_checks(SharkState* state) { + for (int i = 0; i < state->stack_depth(); i++) { + if (state->stack(i)) { + if (state->stack(i)->is_two_word()) + assert(state->stack(i - 1) == NULL, "should be"); + } + else { + assert(state->stack(i + 1)->is_two_word(), "should be"); + } + } +} + +void SharkStateScanner::locals_integrity_checks(SharkState* state) { + for (int i = 0; i < max_locals(); i++) { + if (state->local(i)) { + if (state->local(i)->is_two_word()) + assert(state->local(i + 1) == NULL, "should be"); + } + } +} +#endif // !PRODUCT diff --git a/hotspot/src/share/vm/shark/sharkStateScanner.hpp b/hotspot/src/share/vm/shark/sharkStateScanner.hpp new file mode 100644 index 00000000000..74c1294e6ab --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkStateScanner.hpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * 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. + * + */ + +class SharkState; + +class SharkStateScanner : public SharkTargetInvariants { + protected: + SharkStateScanner(SharkFunction* function) + : SharkTargetInvariants(function), _stack(function->stack()) {} + + private: + SharkStack* _stack; + + protected: + SharkStack* stack() const { + return _stack; + } + + // Scan the frame + public: + void scan(SharkState* state); + + // Callbacks + // Note that the offsets supplied to the various process_* callbacks + // are specified in wordSize words from the frame's unextended_sp. + protected: + virtual void start_frame() {} + + virtual void start_stack(int stack_depth) {} + virtual void process_stack_slot(int index, SharkValue** value, int offset) {} + virtual void end_stack() {} + + virtual void start_monitors(int num_monitors) {} + virtual void process_monitor(int index, int box_offset, int obj_offset) {} + virtual void end_monitors() {} + + virtual void start_frame_header() {} + virtual void process_oop_tmp_slot(llvm::Value** value, int offset) {} + virtual void process_method_slot(llvm::Value** value, int offset) {} + virtual void process_pc_slot(int offset) {} + virtual void end_frame_header() {} + + virtual void start_locals() {} + virtual void process_local_slot(int index, SharkValue** value, int offset) {} + virtual void end_locals() {} + + virtual void end_frame() {} + + // Integrity checks + private: + void stack_integrity_checks(SharkState* state) PRODUCT_RETURN; + void locals_integrity_checks(SharkState* state) PRODUCT_RETURN; +}; diff --git a/hotspot/src/share/vm/shark/sharkTopLevelBlock.cpp b/hotspot/src/share/vm/shark/sharkTopLevelBlock.cpp new file mode 100644 index 00000000000..5e93ca587c6 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkTopLevelBlock.cpp @@ -0,0 +1,1995 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkTopLevelBlock.cpp.incl" + +using namespace llvm; + +void SharkTopLevelBlock::scan_for_traps() { + // If typeflow found a trap then don't scan past it + int limit_bci = ciblock()->has_trap() ? ciblock()->trap_bci() : limit(); + + // Scan the bytecode for traps that are always hit + iter()->reset_to_bci(start()); + while (iter()->next_bci() < limit_bci) { + iter()->next(); + + ciField *field; + ciMethod *method; + ciInstanceKlass *klass; + bool will_link; + bool is_field; + + switch (bc()) { + case Bytecodes::_ldc: + case Bytecodes::_ldc_w: + if (!SharkConstant::for_ldc(iter())->is_loaded()) { + set_trap( + Deoptimization::make_trap_request( + Deoptimization::Reason_uninitialized, + Deoptimization::Action_reinterpret), bci()); + return; + } + break; + + case Bytecodes::_getfield: + case Bytecodes::_getstatic: + case Bytecodes::_putfield: + case Bytecodes::_putstatic: + field = iter()->get_field(will_link); + assert(will_link, "typeflow responsibility"); + is_field = (bc() == Bytecodes::_getfield || bc() == Bytecodes::_putfield); + + // If the bytecode does not match the field then bail out to + // the interpreter to throw an IncompatibleClassChangeError + if (is_field == field->is_static()) { + set_trap( + Deoptimization::make_trap_request( + Deoptimization::Reason_unhandled, + Deoptimization::Action_none), bci()); + return; + } + + // Bail out if we are trying to access a static variable + // before the class initializer has completed. + if (!is_field && !field->holder()->is_initialized()) { + if (!static_field_ok_in_clinit(field)) { + set_trap( + Deoptimization::make_trap_request( + Deoptimization::Reason_uninitialized, + Deoptimization::Action_reinterpret), bci()); + return; + } + } + break; + + case Bytecodes::_invokestatic: + case Bytecodes::_invokespecial: + case Bytecodes::_invokevirtual: + case Bytecodes::_invokeinterface: + method = iter()->get_method(will_link); + assert(will_link, "typeflow responsibility"); + + if (!method->holder()->is_linked()) { + set_trap( + Deoptimization::make_trap_request( + Deoptimization::Reason_uninitialized, + Deoptimization::Action_reinterpret), bci()); + return; + } + + if (bc() == Bytecodes::_invokevirtual) { + klass = ciEnv::get_instance_klass_for_declared_method_holder( + iter()->get_declared_method_holder()); + if (!klass->is_linked()) { + set_trap( + Deoptimization::make_trap_request( + Deoptimization::Reason_uninitialized, + Deoptimization::Action_reinterpret), bci()); + return; + } + } + break; + + case Bytecodes::_new: + klass = iter()->get_klass(will_link)->as_instance_klass(); + assert(will_link, "typeflow responsibility"); + + // Bail out if the class is unloaded + if (iter()->is_unresolved_klass() || !klass->is_initialized()) { + set_trap( + Deoptimization::make_trap_request( + Deoptimization::Reason_uninitialized, + Deoptimization::Action_reinterpret), bci()); + return; + } + + // Bail out if the class cannot be instantiated + if (klass->is_abstract() || klass->is_interface() || + klass->name() == ciSymbol::java_lang_Class()) { + set_trap( + Deoptimization::make_trap_request( + Deoptimization::Reason_unhandled, + Deoptimization::Action_reinterpret), bci()); + return; + } + break; + } + } + + // Trap if typeflow trapped (and we didn't before) + if (ciblock()->has_trap()) { + set_trap( + Deoptimization::make_trap_request( + Deoptimization::Reason_unloaded, + Deoptimization::Action_reinterpret, + ciblock()->trap_index()), ciblock()->trap_bci()); + return; + } +} + +bool SharkTopLevelBlock::static_field_ok_in_clinit(ciField* field) { + assert(field->is_static(), "should be"); + + // This code is lifted pretty much verbatim from C2's + // Parse::static_field_ok_in_clinit() in parse3.cpp. + bool access_OK = false; + if (target()->holder()->is_subclass_of(field->holder())) { + if (target()->is_static()) { + if (target()->name() == ciSymbol::class_initializer_name()) { + // It's OK to access static fields from the class initializer + access_OK = true; + } + } + else { + if (target()->name() == ciSymbol::object_initializer_name()) { + // It's also OK to access static fields inside a constructor, + // because any thread calling the constructor must first have + // synchronized on the class by executing a "new" bytecode. + access_OK = true; + } + } + } + return access_OK; +} + +SharkState* SharkTopLevelBlock::entry_state() { + if (_entry_state == NULL) { + assert(needs_phis(), "should do"); + _entry_state = new SharkPHIState(this); + } + return _entry_state; +} + +void SharkTopLevelBlock::add_incoming(SharkState* incoming_state) { + if (needs_phis()) { + ((SharkPHIState *) entry_state())->add_incoming(incoming_state); + } + else if (_entry_state == NULL) { + _entry_state = incoming_state; + } + else { + assert(entry_state()->equal_to(incoming_state), "should be"); + } +} + +void SharkTopLevelBlock::enter(SharkTopLevelBlock* predecessor, + bool is_exception) { + // This block requires phis: + // - if it is entered more than once + // - if it is an exception handler, because in which + // case we assume it's entered more than once. + // - if the predecessor will be compiled after this + // block, in which case we can't simple propagate + // the state forward. + if (!needs_phis() && + (entered() || + is_exception || + (predecessor && predecessor->index() >= index()))) + _needs_phis = true; + + // Recurse into the tree + if (!entered()) { + _entered = true; + + scan_for_traps(); + if (!has_trap()) { + for (int i = 0; i < num_successors(); i++) { + successor(i)->enter(this, false); + } + } + compute_exceptions(); + for (int i = 0; i < num_exceptions(); i++) { + SharkTopLevelBlock *handler = exception(i); + if (handler) + handler->enter(this, true); + } + } +} + +void SharkTopLevelBlock::initialize() { + char name[28]; + snprintf(name, sizeof(name), + "bci_%d%s", + start(), is_backedge_copy() ? "_backedge_copy" : ""); + _entry_block = function()->CreateBlock(name); +} + +void SharkTopLevelBlock::decache_for_Java_call(ciMethod *callee) { + SharkJavaCallDecacher(function(), bci(), callee).scan(current_state()); + for (int i = 0; i < callee->arg_size(); i++) + xpop(); +} + +void SharkTopLevelBlock::cache_after_Java_call(ciMethod *callee) { + if (callee->return_type()->size()) { + ciType *type; + switch (callee->return_type()->basic_type()) { + case T_BOOLEAN: + case T_BYTE: + case T_CHAR: + case T_SHORT: + type = ciType::make(T_INT); + break; + + default: + type = callee->return_type(); + } + + push(SharkValue::create_generic(type, NULL, false)); + } + SharkJavaCallCacher(function(), callee).scan(current_state()); +} + +void SharkTopLevelBlock::decache_for_VM_call() { + SharkVMCallDecacher(function(), bci()).scan(current_state()); +} + +void SharkTopLevelBlock::cache_after_VM_call() { + SharkVMCallCacher(function()).scan(current_state()); +} + +void SharkTopLevelBlock::decache_for_trap() { + SharkTrapDecacher(function(), bci()).scan(current_state()); +} + +void SharkTopLevelBlock::emit_IR() { + builder()->SetInsertPoint(entry_block()); + + // Parse the bytecode + parse_bytecode(start(), limit()); + + // If this block falls through to the next then it won't have been + // terminated by a bytecode and we have to add the branch ourselves + if (falls_through() && !has_trap()) + do_branch(ciTypeFlow::FALL_THROUGH); +} + +SharkTopLevelBlock* SharkTopLevelBlock::bci_successor(int bci) const { + // XXX now with Linear Search Technology (tm) + for (int i = 0; i < num_successors(); i++) { + ciTypeFlow::Block *successor = ciblock()->successors()->at(i); + if (successor->start() == bci) + return function()->block(successor->pre_order()); + } + ShouldNotReachHere(); +} + +void SharkTopLevelBlock::do_zero_check(SharkValue *value) { + if (value->is_phi() && value->as_phi()->all_incomers_zero_checked()) { + function()->add_deferred_zero_check(this, value); + } + else { + BasicBlock *continue_block = function()->CreateBlock("not_zero"); + SharkState *saved_state = current_state(); + set_current_state(saved_state->copy()); + zero_check_value(value, continue_block); + builder()->SetInsertPoint(continue_block); + set_current_state(saved_state); + } + + value->set_zero_checked(true); +} + +void SharkTopLevelBlock::do_deferred_zero_check(SharkValue* value, + int bci, + SharkState* saved_state, + BasicBlock* continue_block) { + if (value->as_phi()->all_incomers_zero_checked()) { + builder()->CreateBr(continue_block); + } + else { + iter()->force_bci(start()); + set_current_state(saved_state); + zero_check_value(value, continue_block); + } +} + +void SharkTopLevelBlock::zero_check_value(SharkValue* value, + BasicBlock* continue_block) { + BasicBlock *zero_block = builder()->CreateBlock(continue_block, "zero"); + + Value *a, *b; + switch (value->basic_type()) { + case T_BYTE: + case T_CHAR: + case T_SHORT: + case T_INT: + a = value->jint_value(); + b = LLVMValue::jint_constant(0); + break; + case T_LONG: + a = value->jlong_value(); + b = LLVMValue::jlong_constant(0); + break; + case T_OBJECT: + case T_ARRAY: + a = value->jobject_value(); + b = LLVMValue::LLVMValue::null(); + break; + default: + tty->print_cr("Unhandled type %s", type2name(value->basic_type())); + ShouldNotReachHere(); + } + + builder()->CreateCondBr( + builder()->CreateICmpNE(a, b), continue_block, zero_block); + + builder()->SetInsertPoint(zero_block); + if (value->is_jobject()) { + call_vm( + builder()->throw_NullPointerException(), + builder()->CreateIntToPtr( + LLVMValue::intptr_constant((intptr_t) __FILE__), + PointerType::getUnqual(SharkType::jbyte_type())), + LLVMValue::jint_constant(__LINE__), + EX_CHECK_NONE); + } + else { + call_vm( + builder()->throw_ArithmeticException(), + builder()->CreateIntToPtr( + LLVMValue::intptr_constant((intptr_t) __FILE__), + PointerType::getUnqual(SharkType::jbyte_type())), + LLVMValue::jint_constant(__LINE__), + EX_CHECK_NONE); + } + + Value *pending_exception = get_pending_exception(); + clear_pending_exception(); + handle_exception(pending_exception, EX_CHECK_FULL); +} + +void SharkTopLevelBlock::check_bounds(SharkValue* array, SharkValue* index) { + BasicBlock *out_of_bounds = function()->CreateBlock("out_of_bounds"); + BasicBlock *in_bounds = function()->CreateBlock("in_bounds"); + + Value *length = builder()->CreateArrayLength(array->jarray_value()); + // we use an unsigned comparison to catch negative values + builder()->CreateCondBr( + builder()->CreateICmpULT(index->jint_value(), length), + in_bounds, out_of_bounds); + + builder()->SetInsertPoint(out_of_bounds); + SharkState *saved_state = current_state()->copy(); + + call_vm( + builder()->throw_ArrayIndexOutOfBoundsException(), + builder()->CreateIntToPtr( + LLVMValue::intptr_constant((intptr_t) __FILE__), + PointerType::getUnqual(SharkType::jbyte_type())), + LLVMValue::jint_constant(__LINE__), + index->jint_value(), + EX_CHECK_NONE); + + Value *pending_exception = get_pending_exception(); + clear_pending_exception(); + handle_exception(pending_exception, EX_CHECK_FULL); + + set_current_state(saved_state); + + builder()->SetInsertPoint(in_bounds); +} + +void SharkTopLevelBlock::check_pending_exception(int action) { + assert(action & EAM_CHECK, "should be"); + + BasicBlock *exception = function()->CreateBlock("exception"); + BasicBlock *no_exception = function()->CreateBlock("no_exception"); + + Value *pending_exception = get_pending_exception(); + builder()->CreateCondBr( + builder()->CreateICmpEQ(pending_exception, LLVMValue::null()), + no_exception, exception); + + builder()->SetInsertPoint(exception); + SharkState *saved_state = current_state()->copy(); + if (action & EAM_MONITOR_FUDGE) { + // The top monitor is marked live, but the exception was thrown + // while setting it up so we need to mark it dead before we enter + // any exception handlers as they will not expect it to be there. + set_num_monitors(num_monitors() - 1); + action ^= EAM_MONITOR_FUDGE; + } + clear_pending_exception(); + handle_exception(pending_exception, action); + set_current_state(saved_state); + + builder()->SetInsertPoint(no_exception); +} + +void SharkTopLevelBlock::compute_exceptions() { + ciExceptionHandlerStream str(target(), start()); + + int exc_count = str.count(); + _exc_handlers = new GrowableArray(exc_count); + _exceptions = new GrowableArray(exc_count); + + int index = 0; + for (; !str.is_done(); str.next()) { + ciExceptionHandler *handler = str.handler(); + if (handler->handler_bci() == -1) + break; + _exc_handlers->append(handler); + + // Try and get this exception's handler from typeflow. We should + // do it this way always, really, except that typeflow sometimes + // doesn't record exceptions, even loaded ones, and sometimes it + // returns them with a different handler bci. Why??? + SharkTopLevelBlock *block = NULL; + ciInstanceKlass* klass; + if (handler->is_catch_all()) { + klass = java_lang_Throwable_klass(); + } + else { + klass = handler->catch_klass(); + } + for (int i = 0; i < ciblock()->exceptions()->length(); i++) { + if (klass == ciblock()->exc_klasses()->at(i)) { + block = function()->block(ciblock()->exceptions()->at(i)->pre_order()); + if (block->start() == handler->handler_bci()) + break; + else + block = NULL; + } + } + + // If typeflow let us down then try and figure it out ourselves + if (block == NULL) { + for (int i = 0; i < function()->block_count(); i++) { + SharkTopLevelBlock *candidate = function()->block(i); + if (candidate->start() == handler->handler_bci()) { + if (block != NULL) { + NOT_PRODUCT(warning("there may be trouble ahead")); + block = NULL; + break; + } + block = candidate; + } + } + } + _exceptions->append(block); + } +} + +void SharkTopLevelBlock::handle_exception(Value* exception, int action) { + if (action & EAM_HANDLE && num_exceptions() != 0) { + // Clear the stack and push the exception onto it + while (xstack_depth()) + pop(); + push(SharkValue::create_jobject(exception, true)); + + // Work out how many options we have to check + bool has_catch_all = exc_handler(num_exceptions() - 1)->is_catch_all(); + int num_options = num_exceptions(); + if (has_catch_all) + num_options--; + + // Marshal any non-catch-all handlers + if (num_options > 0) { + bool all_loaded = true; + for (int i = 0; i < num_options; i++) { + if (!exc_handler(i)->catch_klass()->is_loaded()) { + all_loaded = false; + break; + } + } + + if (all_loaded) + marshal_exception_fast(num_options); + else + marshal_exception_slow(num_options); + } + + // Install the catch-all handler, if present + if (has_catch_all) { + SharkTopLevelBlock* handler = this->exception(num_options); + assert(handler != NULL, "catch-all handler cannot be unloaded"); + + builder()->CreateBr(handler->entry_block()); + handler->add_incoming(current_state()); + return; + } + } + + // No exception handler was found; unwind and return + handle_return(T_VOID, exception); +} + +void SharkTopLevelBlock::marshal_exception_fast(int num_options) { + Value *exception_klass = builder()->CreateValueOfStructEntry( + xstack(0)->jobject_value(), + in_ByteSize(oopDesc::klass_offset_in_bytes()), + SharkType::oop_type(), + "exception_klass"); + + for (int i = 0; i < num_options; i++) { + Value *check_klass = + builder()->CreateInlineOop(exc_handler(i)->catch_klass()); + + BasicBlock *not_exact = function()->CreateBlock("not_exact"); + BasicBlock *not_subtype = function()->CreateBlock("not_subtype"); + + builder()->CreateCondBr( + builder()->CreateICmpEQ(check_klass, exception_klass), + handler_for_exception(i), not_exact); + + builder()->SetInsertPoint(not_exact); + builder()->CreateCondBr( + builder()->CreateICmpNE( + builder()->CreateCall2( + builder()->is_subtype_of(), check_klass, exception_klass), + LLVMValue::jbyte_constant(0)), + handler_for_exception(i), not_subtype); + + builder()->SetInsertPoint(not_subtype); + } +} + +void SharkTopLevelBlock::marshal_exception_slow(int num_options) { + int *indexes = NEW_RESOURCE_ARRAY(int, num_options); + for (int i = 0; i < num_options; i++) + indexes[i] = exc_handler(i)->catch_klass_index(); + + Value *index = call_vm( + builder()->find_exception_handler(), + builder()->CreateInlineData( + indexes, + num_options * sizeof(int), + PointerType::getUnqual(SharkType::jint_type())), + LLVMValue::jint_constant(num_options), + EX_CHECK_NO_CATCH); + + BasicBlock *no_handler = function()->CreateBlock("no_handler"); + SwitchInst *switchinst = builder()->CreateSwitch( + index, no_handler, num_options); + + for (int i = 0; i < num_options; i++) { + switchinst->addCase( + LLVMValue::jint_constant(i), + handler_for_exception(i)); + } + + builder()->SetInsertPoint(no_handler); +} + +BasicBlock* SharkTopLevelBlock::handler_for_exception(int index) { + SharkTopLevelBlock *successor = this->exception(index); + if (successor) { + successor->add_incoming(current_state()); + return successor->entry_block(); + } + else { + return make_trap( + exc_handler(index)->handler_bci(), + Deoptimization::make_trap_request( + Deoptimization::Reason_unhandled, + Deoptimization::Action_reinterpret)); + } +} + +void SharkTopLevelBlock::maybe_add_safepoint() { + if (current_state()->has_safepointed()) + return; + + BasicBlock *orig_block = builder()->GetInsertBlock(); + SharkState *orig_state = current_state()->copy(); + + BasicBlock *do_safepoint = function()->CreateBlock("do_safepoint"); + BasicBlock *safepointed = function()->CreateBlock("safepointed"); + + Value *state = builder()->CreateLoad( + builder()->CreateIntToPtr( + LLVMValue::intptr_constant( + (intptr_t) SafepointSynchronize::address_of_state()), + PointerType::getUnqual(SharkType::jint_type())), + "state"); + + builder()->CreateCondBr( + builder()->CreateICmpEQ( + state, + LLVMValue::jint_constant(SafepointSynchronize::_synchronizing)), + do_safepoint, safepointed); + + builder()->SetInsertPoint(do_safepoint); + call_vm(builder()->safepoint(), EX_CHECK_FULL); + BasicBlock *safepointed_block = builder()->GetInsertBlock(); + builder()->CreateBr(safepointed); + + builder()->SetInsertPoint(safepointed); + current_state()->merge(orig_state, orig_block, safepointed_block); + + current_state()->set_has_safepointed(true); +} + +void SharkTopLevelBlock::maybe_add_backedge_safepoint() { + if (current_state()->has_safepointed()) + return; + + for (int i = 0; i < num_successors(); i++) { + if (successor(i)->can_reach(this)) { + maybe_add_safepoint(); + break; + } + } +} + +bool SharkTopLevelBlock::can_reach(SharkTopLevelBlock* other) { + for (int i = 0; i < function()->block_count(); i++) + function()->block(i)->_can_reach_visited = false; + + return can_reach_helper(other); +} + +bool SharkTopLevelBlock::can_reach_helper(SharkTopLevelBlock* other) { + if (this == other) + return true; + + if (_can_reach_visited) + return false; + _can_reach_visited = true; + + if (!has_trap()) { + for (int i = 0; i < num_successors(); i++) { + if (successor(i)->can_reach_helper(other)) + return true; + } + } + + for (int i = 0; i < num_exceptions(); i++) { + SharkTopLevelBlock *handler = exception(i); + if (handler && handler->can_reach_helper(other)) + return true; + } + + return false; +} + +BasicBlock* SharkTopLevelBlock::make_trap(int trap_bci, int trap_request) { + BasicBlock *trap_block = function()->CreateBlock("trap"); + BasicBlock *orig_block = builder()->GetInsertBlock(); + builder()->SetInsertPoint(trap_block); + + int orig_bci = bci(); + iter()->force_bci(trap_bci); + + do_trap(trap_request); + + builder()->SetInsertPoint(orig_block); + iter()->force_bci(orig_bci); + + return trap_block; +} + +void SharkTopLevelBlock::do_trap(int trap_request) { + decache_for_trap(); + builder()->CreateRet( + builder()->CreateCall2( + builder()->uncommon_trap(), + thread(), + LLVMValue::jint_constant(trap_request))); +} + +void SharkTopLevelBlock::call_register_finalizer(Value *receiver) { + BasicBlock *orig_block = builder()->GetInsertBlock(); + SharkState *orig_state = current_state()->copy(); + + BasicBlock *do_call = function()->CreateBlock("has_finalizer"); + BasicBlock *done = function()->CreateBlock("done"); + + Value *klass = builder()->CreateValueOfStructEntry( + receiver, + in_ByteSize(oopDesc::klass_offset_in_bytes()), + SharkType::oop_type(), + "klass"); + + Value *klass_part = builder()->CreateAddressOfStructEntry( + klass, + in_ByteSize(klassOopDesc::klass_part_offset_in_bytes()), + SharkType::klass_type(), + "klass_part"); + + Value *access_flags = builder()->CreateValueOfStructEntry( + klass_part, + in_ByteSize(Klass::access_flags_offset_in_bytes()), + SharkType::jint_type(), + "access_flags"); + + builder()->CreateCondBr( + builder()->CreateICmpNE( + builder()->CreateAnd( + access_flags, + LLVMValue::jint_constant(JVM_ACC_HAS_FINALIZER)), + LLVMValue::jint_constant(0)), + do_call, done); + + builder()->SetInsertPoint(do_call); + call_vm(builder()->register_finalizer(), receiver, EX_CHECK_FULL); + BasicBlock *branch_block = builder()->GetInsertBlock(); + builder()->CreateBr(done); + + builder()->SetInsertPoint(done); + current_state()->merge(orig_state, orig_block, branch_block); +} + +void SharkTopLevelBlock::handle_return(BasicType type, Value* exception) { + assert (exception == NULL || type == T_VOID, "exception OR result, please"); + + if (num_monitors()) { + // Protect our exception across possible monitor release decaches + if (exception) + set_oop_tmp(exception); + + // We don't need to check for exceptions thrown here. If + // we're returning a value then we just carry on as normal: + // the caller will see the pending exception and handle it. + // If we're returning with an exception then that exception + // takes priority and the release_lock one will be ignored. + while (num_monitors()) + release_lock(EX_CHECK_NONE); + + // Reload the exception we're throwing + if (exception) + exception = get_oop_tmp(); + } + + if (exception) { + builder()->CreateStore(exception, pending_exception_address()); + } + + Value *result_addr = stack()->CreatePopFrame(type2size[type]); + if (type != T_VOID) { + builder()->CreateStore( + pop_result(type)->generic_value(), + builder()->CreateIntToPtr( + result_addr, + PointerType::getUnqual(SharkType::to_stackType(type)))); + } + + builder()->CreateRet(LLVMValue::jint_constant(0)); +} + +void SharkTopLevelBlock::do_arraylength() { + SharkValue *array = pop(); + check_null(array); + Value *length = builder()->CreateArrayLength(array->jarray_value()); + push(SharkValue::create_jint(length, false)); +} + +void SharkTopLevelBlock::do_aload(BasicType basic_type) { + SharkValue *index = pop(); + SharkValue *array = pop(); + + check_null(array); + check_bounds(array, index); + + Value *value = builder()->CreateLoad( + builder()->CreateArrayAddress( + array->jarray_value(), basic_type, index->jint_value())); + + const Type *stack_type = SharkType::to_stackType(basic_type); + if (value->getType() != stack_type) + value = builder()->CreateIntCast(value, stack_type, basic_type != T_CHAR); + + switch (basic_type) { + case T_BYTE: + case T_CHAR: + case T_SHORT: + case T_INT: + push(SharkValue::create_jint(value, false)); + break; + + case T_LONG: + push(SharkValue::create_jlong(value, false)); + break; + + case T_FLOAT: + push(SharkValue::create_jfloat(value)); + break; + + case T_DOUBLE: + push(SharkValue::create_jdouble(value)); + break; + + case T_OBJECT: + // You might expect that array->type()->is_array_klass() would + // always be true, but it isn't. If ciTypeFlow detects that a + // value is always null then that value becomes an untyped null + // object. Shark doesn't presently support this, so a generic + // T_OBJECT is created. In this case we guess the type using + // the BasicType we were supplied. In reality the generated + // code will never be used, as the null value will be caught + // by the above null pointer check. + // http://icedtea.classpath.org/bugzilla/show_bug.cgi?id=324 + push( + SharkValue::create_generic( + array->type()->is_array_klass() ? + ((ciArrayKlass *) array->type())->element_type() : + ciType::make(basic_type), + value, false)); + break; + + default: + tty->print_cr("Unhandled type %s", type2name(basic_type)); + ShouldNotReachHere(); + } +} + +void SharkTopLevelBlock::do_astore(BasicType basic_type) { + SharkValue *svalue = pop(); + SharkValue *index = pop(); + SharkValue *array = pop(); + + check_null(array); + check_bounds(array, index); + + Value *value; + switch (basic_type) { + case T_BYTE: + case T_CHAR: + case T_SHORT: + case T_INT: + value = svalue->jint_value(); + break; + + case T_LONG: + value = svalue->jlong_value(); + break; + + case T_FLOAT: + value = svalue->jfloat_value(); + break; + + case T_DOUBLE: + value = svalue->jdouble_value(); + break; + + case T_OBJECT: + value = svalue->jobject_value(); + // XXX assignability check + break; + + default: + tty->print_cr("Unhandled type %s", type2name(basic_type)); + ShouldNotReachHere(); + } + + const Type *array_type = SharkType::to_arrayType(basic_type); + if (value->getType() != array_type) + value = builder()->CreateIntCast(value, array_type, basic_type != T_CHAR); + + Value *addr = builder()->CreateArrayAddress( + array->jarray_value(), basic_type, index->jint_value(), "addr"); + + builder()->CreateStore(value, addr); + + if (basic_type == T_OBJECT) // XXX or T_ARRAY? + builder()->CreateUpdateBarrierSet(oopDesc::bs(), addr); +} + +void SharkTopLevelBlock::do_return(BasicType type) { + if (target()->intrinsic_id() == vmIntrinsics::_Object_init) + call_register_finalizer(local(0)->jobject_value()); + maybe_add_safepoint(); + handle_return(type, NULL); +} + +void SharkTopLevelBlock::do_athrow() { + SharkValue *exception = pop(); + check_null(exception); + handle_exception(exception->jobject_value(), EX_CHECK_FULL); +} + +void SharkTopLevelBlock::do_goto() { + do_branch(ciTypeFlow::GOTO_TARGET); +} + +void SharkTopLevelBlock::do_jsr() { + push(SharkValue::address_constant(iter()->next_bci())); + do_branch(ciTypeFlow::GOTO_TARGET); +} + +void SharkTopLevelBlock::do_ret() { + assert(local(iter()->get_index())->address_value() == + successor(ciTypeFlow::GOTO_TARGET)->start(), "should be"); + do_branch(ciTypeFlow::GOTO_TARGET); +} + +// All propagation of state from one block to the next (via +// dest->add_incoming) is handled by these methods: +// do_branch +// do_if_helper +// do_switch +// handle_exception + +void SharkTopLevelBlock::do_branch(int successor_index) { + SharkTopLevelBlock *dest = successor(successor_index); + builder()->CreateBr(dest->entry_block()); + dest->add_incoming(current_state()); +} + +void SharkTopLevelBlock::do_if(ICmpInst::Predicate p, + SharkValue* b, + SharkValue* a) { + Value *llvm_a, *llvm_b; + if (a->is_jobject()) { + llvm_a = a->intptr_value(builder()); + llvm_b = b->intptr_value(builder()); + } + else { + llvm_a = a->jint_value(); + llvm_b = b->jint_value(); + } + do_if_helper(p, llvm_b, llvm_a, current_state(), current_state()); +} + +void SharkTopLevelBlock::do_if_helper(ICmpInst::Predicate p, + Value* b, + Value* a, + SharkState* if_taken_state, + SharkState* not_taken_state) { + SharkTopLevelBlock *if_taken = successor(ciTypeFlow::IF_TAKEN); + SharkTopLevelBlock *not_taken = successor(ciTypeFlow::IF_NOT_TAKEN); + + builder()->CreateCondBr( + builder()->CreateICmp(p, a, b), + if_taken->entry_block(), not_taken->entry_block()); + + if_taken->add_incoming(if_taken_state); + not_taken->add_incoming(not_taken_state); +} + +void SharkTopLevelBlock::do_switch() { + int len = switch_table_length(); + + SharkTopLevelBlock *dest_block = successor(ciTypeFlow::SWITCH_DEFAULT); + SwitchInst *switchinst = builder()->CreateSwitch( + pop()->jint_value(), dest_block->entry_block(), len); + dest_block->add_incoming(current_state()); + + for (int i = 0; i < len; i++) { + int dest_bci = switch_dest(i); + if (dest_bci != switch_default_dest()) { + dest_block = bci_successor(dest_bci); + switchinst->addCase( + LLVMValue::jint_constant(switch_key(i)), + dest_block->entry_block()); + dest_block->add_incoming(current_state()); + } + } +} + +ciMethod* SharkTopLevelBlock::improve_virtual_call(ciMethod* caller, + ciInstanceKlass* klass, + ciMethod* dest_method, + ciType* receiver_type) { + // If the method is obviously final then we are already done + if (dest_method->can_be_statically_bound()) + return dest_method; + + // Array methods are all inherited from Object and are monomorphic + if (receiver_type->is_array_klass() && + dest_method->holder() == java_lang_Object_klass()) + return dest_method; + +#ifdef SHARK_CAN_DEOPTIMIZE_ANYWHERE + // This code can replace a virtual call with a direct call if this + // class is the only one in the entire set of loaded classes that + // implements this method. This makes the compiled code dependent + // on other classes that implement the method not being loaded, a + // condition which is enforced by the dependency tracker. If the + // dependency tracker determines a method has become invalid it + // will mark it for recompilation, causing running copies to be + // deoptimized. Shark currently can't deoptimize arbitrarily like + // that, so this optimization cannot be used. + // http://icedtea.classpath.org/bugzilla/show_bug.cgi?id=481 + + // All other interesting cases are instance classes + if (!receiver_type->is_instance_klass()) + return NULL; + + // Attempt to improve the receiver + ciInstanceKlass* actual_receiver = klass; + ciInstanceKlass *improved_receiver = receiver_type->as_instance_klass(); + if (improved_receiver->is_loaded() && + improved_receiver->is_initialized() && + !improved_receiver->is_interface() && + improved_receiver->is_subtype_of(actual_receiver)) { + actual_receiver = improved_receiver; + } + + // Attempt to find a monomorphic target for this call using + // class heirachy analysis. + ciInstanceKlass *calling_klass = caller->holder(); + ciMethod* monomorphic_target = + dest_method->find_monomorphic_target(calling_klass, klass, actual_receiver); + if (monomorphic_target != NULL) { + assert(!monomorphic_target->is_abstract(), "shouldn't be"); + + // Opto has a bunch of type checking here that I don't + // understand. It's to inhibit casting in one direction, + // possibly because objects in Opto can have inexact + // types, but I can't even tell which direction it + // doesn't like. For now I'm going to block *any* cast. + if (monomorphic_target != dest_method) { + if (SharkPerformanceWarnings) { + warning("found monomorphic target, but inhibited cast:"); + tty->print(" dest_method = "); + dest_method->print_short_name(tty); + tty->cr(); + tty->print(" monomorphic_target = "); + monomorphic_target->print_short_name(tty); + tty->cr(); + } + monomorphic_target = NULL; + } + } + + // Replace the virtual call with a direct one. This makes + // us dependent on that target method not getting overridden + // by dynamic class loading. + if (monomorphic_target != NULL) { + dependencies()->assert_unique_concrete_method( + actual_receiver, monomorphic_target); + return monomorphic_target; + } + + // Because Opto distinguishes exact types from inexact ones + // it can perform a further optimization to replace calls + // with non-monomorphic targets if the receiver has an exact + // type. We don't mark types this way, so we can't do this. + +#endif // SHARK_CAN_DEOPTIMIZE_ANYWHERE + + return NULL; +} + +Value *SharkTopLevelBlock::get_direct_callee(ciMethod* method) { + return builder()->CreateBitCast( + builder()->CreateInlineOop(method), + SharkType::methodOop_type(), + "callee"); +} + +Value *SharkTopLevelBlock::get_virtual_callee(SharkValue* receiver, + int vtable_index) { + Value *klass = builder()->CreateValueOfStructEntry( + receiver->jobject_value(), + in_ByteSize(oopDesc::klass_offset_in_bytes()), + SharkType::oop_type(), + "klass"); + + return builder()->CreateLoad( + builder()->CreateArrayAddress( + klass, + SharkType::methodOop_type(), + vtableEntry::size() * wordSize, + in_ByteSize(instanceKlass::vtable_start_offset() * wordSize), + LLVMValue::intptr_constant(vtable_index)), + "callee"); +} + +Value* SharkTopLevelBlock::get_interface_callee(SharkValue *receiver, + ciMethod* method) { + BasicBlock *loop = function()->CreateBlock("loop"); + BasicBlock *got_null = function()->CreateBlock("got_null"); + BasicBlock *not_null = function()->CreateBlock("not_null"); + BasicBlock *next = function()->CreateBlock("next"); + BasicBlock *got_entry = function()->CreateBlock("got_entry"); + + // Locate the receiver's itable + Value *object_klass = builder()->CreateValueOfStructEntry( + receiver->jobject_value(), in_ByteSize(oopDesc::klass_offset_in_bytes()), + SharkType::oop_type(), + "object_klass"); + + Value *vtable_start = builder()->CreateAdd( + builder()->CreatePtrToInt(object_klass, SharkType::intptr_type()), + LLVMValue::intptr_constant( + instanceKlass::vtable_start_offset() * HeapWordSize), + "vtable_start"); + + Value *vtable_length = builder()->CreateValueOfStructEntry( + object_klass, + in_ByteSize(instanceKlass::vtable_length_offset() * HeapWordSize), + SharkType::jint_type(), + "vtable_length"); + vtable_length = + builder()->CreateIntCast(vtable_length, SharkType::intptr_type(), false); + + bool needs_aligning = HeapWordsPerLong > 1; + Value *itable_start = builder()->CreateAdd( + vtable_start, + builder()->CreateShl( + vtable_length, + LLVMValue::intptr_constant(exact_log2(vtableEntry::size() * wordSize))), + needs_aligning ? "" : "itable_start"); + if (needs_aligning) { + itable_start = builder()->CreateAnd( + builder()->CreateAdd( + itable_start, LLVMValue::intptr_constant(BytesPerLong - 1)), + LLVMValue::intptr_constant(~(BytesPerLong - 1)), + "itable_start"); + } + + // Locate this interface's entry in the table + Value *iklass = builder()->CreateInlineOop(method->holder()); + BasicBlock *loop_entry = builder()->GetInsertBlock(); + builder()->CreateBr(loop); + builder()->SetInsertPoint(loop); + PHINode *itable_entry_addr = builder()->CreatePHI( + SharkType::intptr_type(), "itable_entry_addr"); + itable_entry_addr->addIncoming(itable_start, loop_entry); + + Value *itable_entry = builder()->CreateIntToPtr( + itable_entry_addr, SharkType::itableOffsetEntry_type(), "itable_entry"); + + Value *itable_iklass = builder()->CreateValueOfStructEntry( + itable_entry, + in_ByteSize(itableOffsetEntry::interface_offset_in_bytes()), + SharkType::oop_type(), + "itable_iklass"); + + builder()->CreateCondBr( + builder()->CreateICmpEQ(itable_iklass, LLVMValue::null()), + got_null, not_null); + + // A null entry means that the class doesn't implement the + // interface, and wasn't the same as the class checked when + // the interface was resolved. + builder()->SetInsertPoint(got_null); + builder()->CreateUnimplemented(__FILE__, __LINE__); + builder()->CreateUnreachable(); + + builder()->SetInsertPoint(not_null); + builder()->CreateCondBr( + builder()->CreateICmpEQ(itable_iklass, iklass), + got_entry, next); + + builder()->SetInsertPoint(next); + Value *next_entry = builder()->CreateAdd( + itable_entry_addr, + LLVMValue::intptr_constant(itableOffsetEntry::size() * wordSize)); + builder()->CreateBr(loop); + itable_entry_addr->addIncoming(next_entry, next); + + // Locate the method pointer + builder()->SetInsertPoint(got_entry); + Value *offset = builder()->CreateValueOfStructEntry( + itable_entry, + in_ByteSize(itableOffsetEntry::offset_offset_in_bytes()), + SharkType::jint_type(), + "offset"); + offset = + builder()->CreateIntCast(offset, SharkType::intptr_type(), false); + + return builder()->CreateLoad( + builder()->CreateIntToPtr( + builder()->CreateAdd( + builder()->CreateAdd( + builder()->CreateAdd( + builder()->CreatePtrToInt( + object_klass, SharkType::intptr_type()), + offset), + LLVMValue::intptr_constant( + method->itable_index() * itableMethodEntry::size() * wordSize)), + LLVMValue::intptr_constant( + itableMethodEntry::method_offset_in_bytes())), + PointerType::getUnqual(SharkType::methodOop_type())), + "callee"); +} + +void SharkTopLevelBlock::do_call() { + // Set frequently used booleans + bool is_static = bc() == Bytecodes::_invokestatic; + bool is_virtual = bc() == Bytecodes::_invokevirtual; + bool is_interface = bc() == Bytecodes::_invokeinterface; + + // Find the method being called + bool will_link; + ciMethod *dest_method = iter()->get_method(will_link); + assert(will_link, "typeflow responsibility"); + assert(dest_method->is_static() == is_static, "must match bc"); + + // Find the class of the method being called. Note + // that the superclass check in the second assertion + // is to cope with a hole in the spec that allows for + // invokeinterface instructions where the resolved + // method is a virtual method in java.lang.Object. + // javac doesn't generate code like that, but there's + // no reason a compliant Java compiler might not. + ciInstanceKlass *holder_klass = dest_method->holder(); + assert(holder_klass->is_loaded(), "scan_for_traps responsibility"); + assert(holder_klass->is_interface() || + holder_klass->super() == NULL || + !is_interface, "must match bc"); + ciKlass *holder = iter()->get_declared_method_holder(); + ciInstanceKlass *klass = + ciEnv::get_instance_klass_for_declared_method_holder(holder); + + // Find the receiver in the stack. We do this before + // trying to inline because the inliner can only use + // zero-checked values, not being able to perform the + // check itself. + SharkValue *receiver = NULL; + if (!is_static) { + receiver = xstack(dest_method->arg_size() - 1); + check_null(receiver); + } + + // Try to improve non-direct calls + bool call_is_virtual = is_virtual || is_interface; + ciMethod *call_method = dest_method; + if (call_is_virtual) { + ciMethod *optimized_method = improve_virtual_call( + target(), klass, dest_method, receiver->type()); + if (optimized_method) { + call_method = optimized_method; + call_is_virtual = false; + } + } + + // Try to inline the call + if (!call_is_virtual) { + if (SharkInliner::attempt_inline(call_method, current_state())) + return; + } + + // Find the method we are calling + Value *callee; + if (call_is_virtual) { + if (is_virtual) { + assert(klass->is_linked(), "scan_for_traps responsibility"); + int vtable_index = call_method->resolve_vtable_index( + target()->holder(), klass); + assert(vtable_index >= 0, "should be"); + callee = get_virtual_callee(receiver, vtable_index); + } + else { + assert(is_interface, "should be"); + callee = get_interface_callee(receiver, call_method); + } + } + else { + callee = get_direct_callee(call_method); + } + + // Load the SharkEntry from the callee + Value *base_pc = builder()->CreateValueOfStructEntry( + callee, methodOopDesc::from_interpreted_offset(), + SharkType::intptr_type(), + "base_pc"); + + // Load the entry point from the SharkEntry + Value *entry_point = builder()->CreateLoad( + builder()->CreateIntToPtr( + builder()->CreateAdd( + base_pc, + LLVMValue::intptr_constant(in_bytes(ZeroEntry::entry_point_offset()))), + PointerType::getUnqual( + PointerType::getUnqual(SharkType::entry_point_type()))), + "entry_point"); + + // Make the call + decache_for_Java_call(call_method); + Value *deoptimized_frames = builder()->CreateCall3( + entry_point, callee, base_pc, thread()); + + // If the callee got deoptimized then reexecute in the interpreter + BasicBlock *reexecute = function()->CreateBlock("reexecute"); + BasicBlock *call_completed = function()->CreateBlock("call_completed"); + builder()->CreateCondBr( + builder()->CreateICmpNE(deoptimized_frames, LLVMValue::jint_constant(0)), + reexecute, call_completed); + + builder()->SetInsertPoint(reexecute); + builder()->CreateCall2( + builder()->deoptimized_entry_point(), + builder()->CreateSub(deoptimized_frames, LLVMValue::jint_constant(1)), + thread()); + builder()->CreateBr(call_completed); + + // Cache after the call + builder()->SetInsertPoint(call_completed); + cache_after_Java_call(call_method); + + // Check for pending exceptions + check_pending_exception(EX_CHECK_FULL); + + // Mark that a safepoint check has occurred + current_state()->set_has_safepointed(true); +} + +bool SharkTopLevelBlock::static_subtype_check(ciKlass* check_klass, + ciKlass* object_klass) { + // If the class we're checking against is java.lang.Object + // then this is a no brainer. Apparently this can happen + // in reflective code... + if (check_klass == java_lang_Object_klass()) + return true; + + // Perform a subtype check. NB in opto's code for this + // (GraphKit::static_subtype_check) it says that static + // interface types cannot be trusted, and if opto can't + // trust them then I assume we can't either. + if (object_klass->is_loaded() && !object_klass->is_interface()) { + if (object_klass == check_klass) + return true; + + if (check_klass->is_loaded() && object_klass->is_subtype_of(check_klass)) + return true; + } + + return false; +} + +void SharkTopLevelBlock::do_instance_check() { + // Get the class we're checking against + bool will_link; + ciKlass *check_klass = iter()->get_klass(will_link); + + // Get the class of the object we're checking + ciKlass *object_klass = xstack(0)->type()->as_klass(); + + // Can we optimize this check away? + if (static_subtype_check(check_klass, object_klass)) { + if (bc() == Bytecodes::_instanceof) { + pop(); + push(SharkValue::jint_constant(1)); + } + return; + } + + // Need to check this one at runtime + if (will_link) + do_full_instance_check(check_klass); + else + do_trapping_instance_check(check_klass); +} + +bool SharkTopLevelBlock::maybe_do_instanceof_if() { + // Get the class we're checking against + bool will_link; + ciKlass *check_klass = iter()->get_klass(will_link); + + // If the class is unloaded then the instanceof + // cannot possibly succeed. + if (!will_link) + return false; + + // Keep a copy of the object we're checking + SharkValue *old_object = xstack(0); + + // Get the class of the object we're checking + ciKlass *object_klass = old_object->type()->as_klass(); + + // If the instanceof can be optimized away at compile time + // then any subsequent checkcasts will be too so we handle + // it normally. + if (static_subtype_check(check_klass, object_klass)) + return false; + + // Perform the instance check + do_full_instance_check(check_klass); + Value *result = pop()->jint_value(); + + // Create the casted object + SharkValue *new_object = SharkValue::create_generic( + check_klass, old_object->jobject_value(), old_object->zero_checked()); + + // Create two copies of the current state, one with the + // original object and one with all instances of the + // original object replaced with the new, casted object. + SharkState *new_state = current_state(); + SharkState *old_state = new_state->copy(); + new_state->replace_all(old_object, new_object); + + // Perform the check-and-branch + switch (iter()->next_bc()) { + case Bytecodes::_ifeq: + // branch if not an instance + do_if_helper( + ICmpInst::ICMP_EQ, + LLVMValue::jint_constant(0), result, + old_state, new_state); + break; + + case Bytecodes::_ifne: + // branch if an instance + do_if_helper( + ICmpInst::ICMP_NE, + LLVMValue::jint_constant(0), result, + new_state, old_state); + break; + + default: + ShouldNotReachHere(); + } + + return true; +} + +void SharkTopLevelBlock::do_full_instance_check(ciKlass* klass) { + BasicBlock *not_null = function()->CreateBlock("not_null"); + BasicBlock *subtype_check = function()->CreateBlock("subtype_check"); + BasicBlock *is_instance = function()->CreateBlock("is_instance"); + BasicBlock *not_instance = function()->CreateBlock("not_instance"); + BasicBlock *merge1 = function()->CreateBlock("merge1"); + BasicBlock *merge2 = function()->CreateBlock("merge2"); + + enum InstanceCheckStates { + IC_IS_NULL, + IC_IS_INSTANCE, + IC_NOT_INSTANCE, + }; + + // Pop the object off the stack + Value *object = pop()->jobject_value(); + + // Null objects aren't instances of anything + builder()->CreateCondBr( + builder()->CreateICmpEQ(object, LLVMValue::null()), + merge2, not_null); + BasicBlock *null_block = builder()->GetInsertBlock(); + + // Get the class we're checking against + builder()->SetInsertPoint(not_null); + Value *check_klass = builder()->CreateInlineOop(klass); + + // Get the class of the object being tested + Value *object_klass = builder()->CreateValueOfStructEntry( + object, in_ByteSize(oopDesc::klass_offset_in_bytes()), + SharkType::oop_type(), + "object_klass"); + + // Perform the check + builder()->CreateCondBr( + builder()->CreateICmpEQ(check_klass, object_klass), + is_instance, subtype_check); + + builder()->SetInsertPoint(subtype_check); + builder()->CreateCondBr( + builder()->CreateICmpNE( + builder()->CreateCall2( + builder()->is_subtype_of(), check_klass, object_klass), + LLVMValue::jbyte_constant(0)), + is_instance, not_instance); + + builder()->SetInsertPoint(is_instance); + builder()->CreateBr(merge1); + + builder()->SetInsertPoint(not_instance); + builder()->CreateBr(merge1); + + // First merge + builder()->SetInsertPoint(merge1); + PHINode *nonnull_result = builder()->CreatePHI( + SharkType::jint_type(), "nonnull_result"); + nonnull_result->addIncoming( + LLVMValue::jint_constant(IC_IS_INSTANCE), is_instance); + nonnull_result->addIncoming( + LLVMValue::jint_constant(IC_NOT_INSTANCE), not_instance); + BasicBlock *nonnull_block = builder()->GetInsertBlock(); + builder()->CreateBr(merge2); + + // Second merge + builder()->SetInsertPoint(merge2); + PHINode *result = builder()->CreatePHI( + SharkType::jint_type(), "result"); + result->addIncoming(LLVMValue::jint_constant(IC_IS_NULL), null_block); + result->addIncoming(nonnull_result, nonnull_block); + + // Handle the result + if (bc() == Bytecodes::_checkcast) { + BasicBlock *failure = function()->CreateBlock("failure"); + BasicBlock *success = function()->CreateBlock("success"); + + builder()->CreateCondBr( + builder()->CreateICmpNE( + result, LLVMValue::jint_constant(IC_NOT_INSTANCE)), + success, failure); + + builder()->SetInsertPoint(failure); + SharkState *saved_state = current_state()->copy(); + + call_vm( + builder()->throw_ClassCastException(), + builder()->CreateIntToPtr( + LLVMValue::intptr_constant((intptr_t) __FILE__), + PointerType::getUnqual(SharkType::jbyte_type())), + LLVMValue::jint_constant(__LINE__), + EX_CHECK_NONE); + + Value *pending_exception = get_pending_exception(); + clear_pending_exception(); + handle_exception(pending_exception, EX_CHECK_FULL); + + set_current_state(saved_state); + builder()->SetInsertPoint(success); + push(SharkValue::create_generic(klass, object, false)); + } + else { + push( + SharkValue::create_jint( + builder()->CreateIntCast( + builder()->CreateICmpEQ( + result, LLVMValue::jint_constant(IC_IS_INSTANCE)), + SharkType::jint_type(), false), false)); + } +} + +void SharkTopLevelBlock::do_trapping_instance_check(ciKlass* klass) { + BasicBlock *not_null = function()->CreateBlock("not_null"); + BasicBlock *is_null = function()->CreateBlock("null"); + + // Leave the object on the stack so it's there if we trap + builder()->CreateCondBr( + builder()->CreateICmpEQ(xstack(0)->jobject_value(), LLVMValue::null()), + is_null, not_null); + SharkState *saved_state = current_state()->copy(); + + // If it's not null then we need to trap + builder()->SetInsertPoint(not_null); + set_current_state(saved_state->copy()); + do_trap( + Deoptimization::make_trap_request( + Deoptimization::Reason_uninitialized, + Deoptimization::Action_reinterpret)); + + // If it's null then we're ok + builder()->SetInsertPoint(is_null); + set_current_state(saved_state); + if (bc() == Bytecodes::_checkcast) { + push(SharkValue::create_generic(klass, pop()->jobject_value(), false)); + } + else { + pop(); + push(SharkValue::jint_constant(0)); + } +} + +void SharkTopLevelBlock::do_new() { + bool will_link; + ciInstanceKlass* klass = iter()->get_klass(will_link)->as_instance_klass(); + assert(will_link, "typeflow responsibility"); + + BasicBlock *got_tlab = NULL; + BasicBlock *heap_alloc = NULL; + BasicBlock *retry = NULL; + BasicBlock *got_heap = NULL; + BasicBlock *initialize = NULL; + BasicBlock *got_fast = NULL; + BasicBlock *slow_alloc_and_init = NULL; + BasicBlock *got_slow = NULL; + BasicBlock *push_object = NULL; + + SharkState *fast_state = NULL; + + Value *tlab_object = NULL; + Value *heap_object = NULL; + Value *fast_object = NULL; + Value *slow_object = NULL; + Value *object = NULL; + + // The fast path + if (!Klass::layout_helper_needs_slow_path(klass->layout_helper())) { + if (UseTLAB) { + got_tlab = function()->CreateBlock("got_tlab"); + heap_alloc = function()->CreateBlock("heap_alloc"); + } + retry = function()->CreateBlock("retry"); + got_heap = function()->CreateBlock("got_heap"); + initialize = function()->CreateBlock("initialize"); + slow_alloc_and_init = function()->CreateBlock("slow_alloc_and_init"); + push_object = function()->CreateBlock("push_object"); + + size_t size_in_bytes = klass->size_helper() << LogHeapWordSize; + + // Thread local allocation + if (UseTLAB) { + Value *top_addr = builder()->CreateAddressOfStructEntry( + thread(), Thread::tlab_top_offset(), + PointerType::getUnqual(SharkType::intptr_type()), + "top_addr"); + + Value *end = builder()->CreateValueOfStructEntry( + thread(), Thread::tlab_end_offset(), + SharkType::intptr_type(), + "end"); + + Value *old_top = builder()->CreateLoad(top_addr, "old_top"); + Value *new_top = builder()->CreateAdd( + old_top, LLVMValue::intptr_constant(size_in_bytes)); + + builder()->CreateCondBr( + builder()->CreateICmpULE(new_top, end), + got_tlab, heap_alloc); + + builder()->SetInsertPoint(got_tlab); + tlab_object = builder()->CreateIntToPtr( + old_top, SharkType::oop_type(), "tlab_object"); + + builder()->CreateStore(new_top, top_addr); + builder()->CreateBr(initialize); + + builder()->SetInsertPoint(heap_alloc); + } + + // Heap allocation + Value *top_addr = builder()->CreateIntToPtr( + LLVMValue::intptr_constant((intptr_t) Universe::heap()->top_addr()), + PointerType::getUnqual(SharkType::intptr_type()), + "top_addr"); + + Value *end = builder()->CreateLoad( + builder()->CreateIntToPtr( + LLVMValue::intptr_constant((intptr_t) Universe::heap()->end_addr()), + PointerType::getUnqual(SharkType::intptr_type())), + "end"); + + builder()->CreateBr(retry); + builder()->SetInsertPoint(retry); + + Value *old_top = builder()->CreateLoad(top_addr, "top"); + Value *new_top = builder()->CreateAdd( + old_top, LLVMValue::intptr_constant(size_in_bytes)); + + builder()->CreateCondBr( + builder()->CreateICmpULE(new_top, end), + got_heap, slow_alloc_and_init); + + builder()->SetInsertPoint(got_heap); + heap_object = builder()->CreateIntToPtr( + old_top, SharkType::oop_type(), "heap_object"); + + Value *check = builder()->CreateCmpxchgPtr(new_top, top_addr, old_top); + builder()->CreateCondBr( + builder()->CreateICmpEQ(old_top, check), + initialize, retry); + + // Initialize the object + builder()->SetInsertPoint(initialize); + if (tlab_object) { + PHINode *phi = builder()->CreatePHI( + SharkType::oop_type(), "fast_object"); + phi->addIncoming(tlab_object, got_tlab); + phi->addIncoming(heap_object, got_heap); + fast_object = phi; + } + else { + fast_object = heap_object; + } + + builder()->CreateMemset( + builder()->CreateBitCast( + fast_object, PointerType::getUnqual(SharkType::jbyte_type())), + LLVMValue::jbyte_constant(0), + LLVMValue::jint_constant(size_in_bytes), + LLVMValue::jint_constant(HeapWordSize)); + + Value *mark_addr = builder()->CreateAddressOfStructEntry( + fast_object, in_ByteSize(oopDesc::mark_offset_in_bytes()), + PointerType::getUnqual(SharkType::intptr_type()), + "mark_addr"); + + Value *klass_addr = builder()->CreateAddressOfStructEntry( + fast_object, in_ByteSize(oopDesc::klass_offset_in_bytes()), + PointerType::getUnqual(SharkType::oop_type()), + "klass_addr"); + + // Set the mark + intptr_t mark; + if (UseBiasedLocking) { + Unimplemented(); + } + else { + mark = (intptr_t) markOopDesc::prototype(); + } + builder()->CreateStore(LLVMValue::intptr_constant(mark), mark_addr); + + // Set the class + Value *rtklass = builder()->CreateInlineOop(klass); + builder()->CreateStore(rtklass, klass_addr); + got_fast = builder()->GetInsertBlock(); + + builder()->CreateBr(push_object); + builder()->SetInsertPoint(slow_alloc_and_init); + fast_state = current_state()->copy(); + } + + // The slow path + call_vm( + builder()->new_instance(), + LLVMValue::jint_constant(iter()->get_klass_index()), + EX_CHECK_FULL); + slow_object = get_vm_result(); + got_slow = builder()->GetInsertBlock(); + + // Push the object + if (push_object) { + builder()->CreateBr(push_object); + builder()->SetInsertPoint(push_object); + } + if (fast_object) { + PHINode *phi = builder()->CreatePHI(SharkType::oop_type(), "object"); + phi->addIncoming(fast_object, got_fast); + phi->addIncoming(slow_object, got_slow); + object = phi; + current_state()->merge(fast_state, got_fast, got_slow); + } + else { + object = slow_object; + } + + push(SharkValue::create_jobject(object, true)); +} + +void SharkTopLevelBlock::do_newarray() { + BasicType type = (BasicType) iter()->get_index(); + + call_vm( + builder()->newarray(), + LLVMValue::jint_constant(type), + pop()->jint_value(), + EX_CHECK_FULL); + + ciArrayKlass *array_klass = ciArrayKlass::make(ciType::make(type)); + push(SharkValue::create_generic(array_klass, get_vm_result(), true)); +} + +void SharkTopLevelBlock::do_anewarray() { + bool will_link; + ciKlass *klass = iter()->get_klass(will_link); + assert(will_link, "typeflow responsibility"); + + ciObjArrayKlass *array_klass = ciObjArrayKlass::make(klass); + if (!array_klass->is_loaded()) { + Unimplemented(); + } + + call_vm( + builder()->anewarray(), + LLVMValue::jint_constant(iter()->get_klass_index()), + pop()->jint_value(), + EX_CHECK_FULL); + + push(SharkValue::create_generic(array_klass, get_vm_result(), true)); +} + +void SharkTopLevelBlock::do_multianewarray() { + bool will_link; + ciArrayKlass *array_klass = iter()->get_klass(will_link)->as_array_klass(); + assert(will_link, "typeflow responsibility"); + + // The dimensions are stack values, so we use their slots for the + // dimensions array. Note that we are storing them in the reverse + // of normal stack order. + int ndims = iter()->get_dimensions(); + + Value *dimensions = stack()->slot_addr( + stack()->stack_slots_offset() + max_stack() - xstack_depth(), + ArrayType::get(SharkType::jint_type(), ndims), + "dimensions"); + + for (int i = 0; i < ndims; i++) { + builder()->CreateStore( + xstack(ndims - 1 - i)->jint_value(), + builder()->CreateStructGEP(dimensions, i)); + } + + call_vm( + builder()->multianewarray(), + LLVMValue::jint_constant(iter()->get_klass_index()), + LLVMValue::jint_constant(ndims), + builder()->CreateStructGEP(dimensions, 0), + EX_CHECK_FULL); + + // Now we can pop the dimensions off the stack + for (int i = 0; i < ndims; i++) + pop(); + + push(SharkValue::create_generic(array_klass, get_vm_result(), true)); +} + +void SharkTopLevelBlock::acquire_method_lock() { + Value *lockee; + if (target()->is_static()) + lockee = builder()->CreateInlineOop(target()->holder()->java_mirror()); + else + lockee = local(0)->jobject_value(); + + iter()->force_bci(start()); // for the decache in acquire_lock + acquire_lock(lockee, EX_CHECK_NO_CATCH); +} + +void SharkTopLevelBlock::do_monitorenter() { + SharkValue *lockee = pop(); + check_null(lockee); + acquire_lock(lockee->jobject_value(), EX_CHECK_FULL); +} + +void SharkTopLevelBlock::do_monitorexit() { + pop(); // don't need this (monitors are block structured) + release_lock(EX_CHECK_NO_CATCH); +} + +void SharkTopLevelBlock::acquire_lock(Value *lockee, int exception_action) { + BasicBlock *try_recursive = function()->CreateBlock("try_recursive"); + BasicBlock *got_recursive = function()->CreateBlock("got_recursive"); + BasicBlock *not_recursive = function()->CreateBlock("not_recursive"); + BasicBlock *acquired_fast = function()->CreateBlock("acquired_fast"); + BasicBlock *lock_acquired = function()->CreateBlock("lock_acquired"); + + int monitor = num_monitors(); + Value *monitor_addr = stack()->monitor_addr(monitor); + Value *monitor_object_addr = stack()->monitor_object_addr(monitor); + Value *monitor_header_addr = stack()->monitor_header_addr(monitor); + + // Store the object and mark the slot as live + builder()->CreateStore(lockee, monitor_object_addr); + set_num_monitors(monitor + 1); + + // Try a simple lock + Value *mark_addr = builder()->CreateAddressOfStructEntry( + lockee, in_ByteSize(oopDesc::mark_offset_in_bytes()), + PointerType::getUnqual(SharkType::intptr_type()), + "mark_addr"); + + Value *mark = builder()->CreateLoad(mark_addr, "mark"); + Value *disp = builder()->CreateOr( + mark, LLVMValue::intptr_constant(markOopDesc::unlocked_value), "disp"); + builder()->CreateStore(disp, monitor_header_addr); + + Value *lock = builder()->CreatePtrToInt( + monitor_header_addr, SharkType::intptr_type()); + Value *check = builder()->CreateCmpxchgPtr(lock, mark_addr, disp); + builder()->CreateCondBr( + builder()->CreateICmpEQ(disp, check), + acquired_fast, try_recursive); + + // Locking failed, but maybe this thread already owns it + builder()->SetInsertPoint(try_recursive); + Value *addr = builder()->CreateAnd( + disp, + LLVMValue::intptr_constant(~markOopDesc::lock_mask_in_place)); + + // NB we use the entire stack, but JavaThread::is_lock_owned() + // uses a more limited range. I don't think it hurts though... + Value *stack_limit = builder()->CreateValueOfStructEntry( + thread(), Thread::stack_base_offset(), + SharkType::intptr_type(), + "stack_limit"); + + assert(sizeof(size_t) == sizeof(intptr_t), "should be"); + Value *stack_size = builder()->CreateValueOfStructEntry( + thread(), Thread::stack_size_offset(), + SharkType::intptr_type(), + "stack_size"); + + Value *stack_start = + builder()->CreateSub(stack_limit, stack_size, "stack_start"); + + builder()->CreateCondBr( + builder()->CreateAnd( + builder()->CreateICmpUGE(addr, stack_start), + builder()->CreateICmpULT(addr, stack_limit)), + got_recursive, not_recursive); + + builder()->SetInsertPoint(got_recursive); + builder()->CreateStore(LLVMValue::intptr_constant(0), monitor_header_addr); + builder()->CreateBr(acquired_fast); + + // Create an edge for the state merge + builder()->SetInsertPoint(acquired_fast); + SharkState *fast_state = current_state()->copy(); + builder()->CreateBr(lock_acquired); + + // It's not a recursive case so we need to drop into the runtime + builder()->SetInsertPoint(not_recursive); + call_vm( + builder()->monitorenter(), monitor_addr, + exception_action | EAM_MONITOR_FUDGE); + BasicBlock *acquired_slow = builder()->GetInsertBlock(); + builder()->CreateBr(lock_acquired); + + // All done + builder()->SetInsertPoint(lock_acquired); + current_state()->merge(fast_state, acquired_fast, acquired_slow); +} + +void SharkTopLevelBlock::release_lock(int exception_action) { + BasicBlock *not_recursive = function()->CreateBlock("not_recursive"); + BasicBlock *released_fast = function()->CreateBlock("released_fast"); + BasicBlock *slow_path = function()->CreateBlock("slow_path"); + BasicBlock *lock_released = function()->CreateBlock("lock_released"); + + int monitor = num_monitors() - 1; + Value *monitor_addr = stack()->monitor_addr(monitor); + Value *monitor_object_addr = stack()->monitor_object_addr(monitor); + Value *monitor_header_addr = stack()->monitor_header_addr(monitor); + + // If it is recursive then we're already done + Value *disp = builder()->CreateLoad(monitor_header_addr); + builder()->CreateCondBr( + builder()->CreateICmpEQ(disp, LLVMValue::intptr_constant(0)), + released_fast, not_recursive); + + // Try a simple unlock + builder()->SetInsertPoint(not_recursive); + + Value *lock = builder()->CreatePtrToInt( + monitor_header_addr, SharkType::intptr_type()); + + Value *lockee = builder()->CreateLoad(monitor_object_addr); + + Value *mark_addr = builder()->CreateAddressOfStructEntry( + lockee, in_ByteSize(oopDesc::mark_offset_in_bytes()), + PointerType::getUnqual(SharkType::intptr_type()), + "mark_addr"); + + Value *check = builder()->CreateCmpxchgPtr(disp, mark_addr, lock); + builder()->CreateCondBr( + builder()->CreateICmpEQ(lock, check), + released_fast, slow_path); + + // Create an edge for the state merge + builder()->SetInsertPoint(released_fast); + SharkState *fast_state = current_state()->copy(); + builder()->CreateBr(lock_released); + + // Need to drop into the runtime to release this one + builder()->SetInsertPoint(slow_path); + call_vm(builder()->monitorexit(), monitor_addr, exception_action); + BasicBlock *released_slow = builder()->GetInsertBlock(); + builder()->CreateBr(lock_released); + + // All done + builder()->SetInsertPoint(lock_released); + current_state()->merge(fast_state, released_fast, released_slow); + + // The object slot is now dead + set_num_monitors(monitor); +} diff --git a/hotspot/src/share/vm/shark/sharkTopLevelBlock.hpp b/hotspot/src/share/vm/shark/sharkTopLevelBlock.hpp new file mode 100644 index 00000000000..76aba1fd54a --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkTopLevelBlock.hpp @@ -0,0 +1,430 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * 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. + * + */ + +class SharkTopLevelBlock : public SharkBlock { + public: + SharkTopLevelBlock(SharkFunction* function, ciTypeFlow::Block* ciblock) + : SharkBlock(function), + _function(function), + _ciblock(ciblock), + _entered(false), + _has_trap(false), + _needs_phis(false), + _entry_state(NULL), + _entry_block(NULL) {} + + private: + SharkFunction* _function; + ciTypeFlow::Block* _ciblock; + + public: + SharkFunction* function() const { + return _function; + } + ciTypeFlow::Block* ciblock() const { + return _ciblock; + } + + // Function properties + public: + SharkStack* stack() const { + return function()->stack(); + } + + // Typeflow properties + public: + int index() const { + return ciblock()->pre_order(); + } + bool is_backedge_copy() const { + return ciblock()->is_backedge_copy(); + } + int stack_depth_at_entry() const { + return ciblock()->stack_size(); + } + ciType* local_type_at_entry(int index) const { + return ciblock()->local_type_at(index); + } + ciType* stack_type_at_entry(int slot) const { + return ciblock()->stack_type_at(slot); + } + int start() const { + return ciblock()->start(); + } + int limit() const { + return ciblock()->limit(); + } + bool falls_through() const { + return ciblock()->control() == ciBlock::fall_through_bci; + } + int num_successors() const { + return ciblock()->successors()->length(); + } + SharkTopLevelBlock* successor(int index) const { + return function()->block(ciblock()->successors()->at(index)->pre_order()); + } + SharkTopLevelBlock* bci_successor(int bci) const; + + // Exceptions + private: + GrowableArray* _exc_handlers; + GrowableArray* _exceptions; + + private: + void compute_exceptions(); + + private: + int num_exceptions() const { + return _exc_handlers->length(); + } + ciExceptionHandler* exc_handler(int index) const { + return _exc_handlers->at(index); + } + SharkTopLevelBlock* exception(int index) const { + return _exceptions->at(index); + } + + // Traps + private: + bool _has_trap; + int _trap_request; + int _trap_bci; + + void set_trap(int trap_request, int trap_bci) { + assert(!has_trap(), "shouldn't have"); + _has_trap = true; + _trap_request = trap_request; + _trap_bci = trap_bci; + } + + private: + bool has_trap() { + return _has_trap; + } + int trap_request() { + assert(has_trap(), "should have"); + return _trap_request; + } + int trap_bci() { + assert(has_trap(), "should have"); + return _trap_bci; + } + + private: + void scan_for_traps(); + + private: + bool static_field_ok_in_clinit(ciField* field); + + // Entry state + private: + bool _entered; + bool _needs_phis; + + public: + bool entered() const { + return _entered; + } + bool needs_phis() const { + return _needs_phis; + } + + private: + void enter(SharkTopLevelBlock* predecessor, bool is_exception); + + public: + void enter() { + enter(NULL, false); + } + + private: + SharkState* _entry_state; + + private: + SharkState* entry_state(); + + private: + llvm::BasicBlock* _entry_block; + + public: + llvm::BasicBlock* entry_block() const { + return _entry_block; + } + + public: + void initialize(); + + public: + void add_incoming(SharkState* incoming_state); + + // Method + public: + llvm::Value* method() { + return current_state()->method(); + } + + // Temporary oop storage + public: + void set_oop_tmp(llvm::Value* value) { + assert(value, "value must be non-NULL (will be reset by get_oop_tmp)"); + assert(!current_state()->oop_tmp(), "oop_tmp gets and sets must match"); + current_state()->set_oop_tmp(value); + } + llvm::Value* get_oop_tmp() { + llvm::Value* value = current_state()->oop_tmp(); + assert(value, "oop_tmp gets and sets must match"); + current_state()->set_oop_tmp(NULL); + return value; + } + + // Cache and decache + private: + void decache_for_Java_call(ciMethod* callee); + void cache_after_Java_call(ciMethod* callee); + void decache_for_VM_call(); + void cache_after_VM_call(); + void decache_for_trap(); + + // Monitors + private: + int num_monitors() { + return current_state()->num_monitors(); + } + int set_num_monitors(int num_monitors) { + current_state()->set_num_monitors(num_monitors); + } + + // Code generation + public: + void emit_IR(); + + // Branch helpers + private: + void do_branch(int successor_index); + + // Zero checks + private: + void do_zero_check(SharkValue* value); + void zero_check_value(SharkValue* value, llvm::BasicBlock* continue_block); + + public: + void do_deferred_zero_check(SharkValue* value, + int bci, + SharkState* saved_state, + llvm::BasicBlock* continue_block); + // Exceptions + private: + llvm::Value* pending_exception_address() const { + return builder()->CreateAddressOfStructEntry( + thread(), Thread::pending_exception_offset(), + llvm::PointerType::getUnqual(SharkType::oop_type()), + "pending_exception_addr"); + } + llvm::LoadInst* get_pending_exception() const { + return builder()->CreateLoad( + pending_exception_address(), "pending_exception"); + } + void clear_pending_exception() const { + builder()->CreateStore(LLVMValue::null(), pending_exception_address()); + } + public: + enum ExceptionActionMask { + // The actual bitmasks that things test against + EAM_CHECK = 1, // whether to check for pending exceptions + EAM_HANDLE = 2, // whether to attempt to handle pending exceptions + EAM_MONITOR_FUDGE = 4, // whether the monitor count needs adjusting + + // More convenient values for passing + EX_CHECK_NONE = 0, + EX_CHECK_NO_CATCH = EAM_CHECK, + EX_CHECK_FULL = EAM_CHECK | EAM_HANDLE + }; + void check_pending_exception(int action); + void handle_exception(llvm::Value* exception, int action); + void marshal_exception_fast(int num_options); + void marshal_exception_slow(int num_options); + llvm::BasicBlock* handler_for_exception(int index); + + // VM calls + private: + llvm::CallInst* call_vm(llvm::Value* callee, + llvm::Value** args_start, + llvm::Value** args_end, + int exception_action) { + decache_for_VM_call(); + stack()->CreateSetLastJavaFrame(); + llvm::CallInst *res = builder()->CreateCall(callee, args_start, args_end); + stack()->CreateResetLastJavaFrame(); + cache_after_VM_call(); + if (exception_action & EAM_CHECK) { + check_pending_exception(exception_action); + current_state()->set_has_safepointed(true); + } + return res; + } + + public: + llvm::CallInst* call_vm(llvm::Value* callee, + int exception_action) { + llvm::Value *args[] = {thread()}; + return call_vm(callee, args, args + 1, exception_action); + } + llvm::CallInst* call_vm(llvm::Value* callee, + llvm::Value* arg1, + int exception_action) { + llvm::Value *args[] = {thread(), arg1}; + return call_vm(callee, args, args + 2, exception_action); + } + llvm::CallInst* call_vm(llvm::Value* callee, + llvm::Value* arg1, + llvm::Value* arg2, + int exception_action) { + llvm::Value *args[] = {thread(), arg1, arg2}; + return call_vm(callee, args, args + 3, exception_action); + } + llvm::CallInst* call_vm(llvm::Value* callee, + llvm::Value* arg1, + llvm::Value* arg2, + llvm::Value* arg3, + int exception_action) { + llvm::Value *args[] = {thread(), arg1, arg2, arg3}; + return call_vm(callee, args, args + 4, exception_action); + } + + // VM call oop return handling + private: + llvm::LoadInst* get_vm_result() const { + llvm::Value *addr = builder()->CreateAddressOfStructEntry( + thread(), JavaThread::vm_result_offset(), + llvm::PointerType::getUnqual(SharkType::oop_type()), + "vm_result_addr"); + llvm::LoadInst *result = builder()->CreateLoad(addr, "vm_result"); + builder()->CreateStore(LLVMValue::null(), addr); + return result; + } + + // Synchronization + private: + void acquire_lock(llvm::Value* lockee, int exception_action); + void release_lock(int exception_action); + + public: + void acquire_method_lock(); + + // Bounds checks + private: + void check_bounds(SharkValue* array, SharkValue* index); + + // Safepoints + private: + void maybe_add_safepoint(); + void maybe_add_backedge_safepoint(); + + // Loop safepoint removal + private: + bool _can_reach_visited; + + bool can_reach(SharkTopLevelBlock* other); + bool can_reach_helper(SharkTopLevelBlock* other); + + // Traps + private: + llvm::BasicBlock* make_trap(int trap_bci, int trap_request); + void do_trap(int trap_request); + + // Returns + private: + void call_register_finalizer(llvm::Value* receiver); + void handle_return(BasicType type, llvm::Value* exception); + + // arraylength + private: + void do_arraylength(); + + // *aload and *astore + private: + void do_aload(BasicType basic_type); + void do_astore(BasicType basic_type); + + // *return and athrow + private: + void do_return(BasicType type); + void do_athrow(); + + // goto* + private: + void do_goto(); + + // jsr* and ret + private: + void do_jsr(); + void do_ret(); + + // if* + private: + void do_if_helper(llvm::ICmpInst::Predicate p, + llvm::Value* b, + llvm::Value* a, + SharkState* if_taken_state, + SharkState* not_taken_state); + void do_if(llvm::ICmpInst::Predicate p, SharkValue* b, SharkValue* a); + + // tableswitch and lookupswitch + private: + void do_switch(); + + // invoke* + private: + ciMethod* improve_virtual_call(ciMethod* caller, + ciInstanceKlass* klass, + ciMethod* dest_method, + ciType* receiver_type); + llvm::Value* get_direct_callee(ciMethod* method); + llvm::Value* get_virtual_callee(SharkValue* receiver, int vtable_index); + llvm::Value* get_interface_callee(SharkValue* receiver, ciMethod* method); + + void do_call(); + + // checkcast and instanceof + private: + bool static_subtype_check(ciKlass* check_klass, ciKlass* object_klass); + void do_full_instance_check(ciKlass* klass); + void do_trapping_instance_check(ciKlass* klass); + + void do_instance_check(); + bool maybe_do_instanceof_if(); + + // new and *newarray + private: + void do_new(); + void do_newarray(); + void do_anewarray(); + void do_multianewarray(); + + // monitorenter and monitorexit + private: + void do_monitorenter(); + void do_monitorexit(); +}; diff --git a/hotspot/src/share/vm/shark/sharkType.hpp b/hotspot/src/share/vm/shark/sharkType.hpp new file mode 100644 index 00000000000..9c5d9e977c0 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkType.hpp @@ -0,0 +1,112 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * 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. + * + */ + +class SharkType : public AllStatic { + private: + static SharkContext& context() { + return SharkContext::current(); + } + + // Basic types + public: + static const llvm::Type* void_type() { + return context().void_type(); + } + static const llvm::IntegerType* bit_type() { + return context().bit_type(); + } + static const llvm::IntegerType* jbyte_type() { + return context().jbyte_type(); + } + static const llvm::IntegerType* jshort_type() { + return context().jshort_type(); + } + static const llvm::IntegerType* jint_type() { + return context().jint_type(); + } + static const llvm::IntegerType* jlong_type() { + return context().jlong_type(); + } + static const llvm::Type* jfloat_type() { + return context().jfloat_type(); + } + static const llvm::Type* jdouble_type() { + return context().jdouble_type(); + } + static const llvm::IntegerType* intptr_type() { + return context().intptr_type(); + } + + // Compound types + public: + static const llvm::PointerType* itableOffsetEntry_type() { + return context().itableOffsetEntry_type(); + } + static const llvm::PointerType* jniEnv_type() { + return context().jniEnv_type(); + } + static const llvm::PointerType* jniHandleBlock_type() { + return context().jniHandleBlock_type(); + } + static const llvm::PointerType* klass_type() { + return context().klass_type(); + } + static const llvm::PointerType* methodOop_type() { + return context().methodOop_type(); + } + static const llvm::ArrayType* monitor_type() { + return context().monitor_type(); + } + static const llvm::PointerType* oop_type() { + return context().oop_type(); + } + static const llvm::PointerType* thread_type() { + return context().thread_type(); + } + static const llvm::PointerType* zeroStack_type() { + return context().zeroStack_type(); + } + static const llvm::FunctionType* entry_point_type() { + return context().entry_point_type(); + } + static const llvm::FunctionType* osr_entry_point_type() { + return context().osr_entry_point_type(); + } + + // Mappings + public: + static const llvm::Type* to_stackType(BasicType type) { + return context().to_stackType(type); + } + static const llvm::Type* to_stackType(ciType* type) { + return to_stackType(type->basic_type()); + } + static const llvm::Type* to_arrayType(BasicType type) { + return context().to_arrayType(type); + } + static const llvm::Type* to_arrayType(ciType* type) { + return to_arrayType(type->basic_type()); + } +}; diff --git a/hotspot/src/share/vm/shark/sharkValue.cpp b/hotspot/src/share/vm/shark/sharkValue.cpp new file mode 100644 index 00000000000..18b1fa6324b --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkValue.cpp @@ -0,0 +1,260 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_sharkValue.cpp.incl" + +using namespace llvm; + +// Cloning + +SharkValue* SharkNormalValue::clone() const { + return SharkValue::create_generic(type(), generic_value(), zero_checked()); +} +SharkValue* SharkPHIValue::clone() const { + return SharkValue::create_phi(type(), (PHINode *) generic_value(), this); +} +SharkValue* SharkAddressValue::clone() const { + return SharkValue::address_constant(address_value()); +} + +// Casting + +bool SharkValue::is_phi() const { + return false; +} +bool SharkPHIValue::is_phi() const { + return true; +} +SharkPHIValue* SharkValue::as_phi() { + ShouldNotCallThis(); +} +SharkPHIValue* SharkPHIValue::as_phi() { + return this; +} + +// Comparison + +bool SharkNormalValue::equal_to(SharkValue *other) const { + return (this->type() == other->type() && + this->generic_value() == other->generic_value() && + this->zero_checked() == other->zero_checked()); +} +bool SharkAddressValue::equal_to(SharkValue *other) const { + return (this->address_value() == other->address_value()); +} + +// Type access + +ciType* SharkValue::type() const { + ShouldNotCallThis(); +} +ciType* SharkNormalValue::type() const { + return _type; +} + +BasicType SharkNormalValue::basic_type() const { + return type()->basic_type(); +} +BasicType SharkAddressValue::basic_type() const { + return T_ADDRESS; +} + +int SharkNormalValue::size() const { + return type()->size(); +} +int SharkAddressValue::size() const { + return 1; +} + +bool SharkValue::is_jint() const { + return false; +} +bool SharkValue::is_jlong() const { + return false; +} +bool SharkValue::is_jfloat() const { + return false; +} +bool SharkValue::is_jdouble() const { + return false; +} +bool SharkValue::is_jobject() const { + return false; +} +bool SharkValue::is_jarray() const { + return false; +} +bool SharkValue::is_address() const { + return false; +} + +bool SharkNormalValue::is_jint() const { + return llvm_value()->getType() == SharkType::jint_type(); +} +bool SharkNormalValue::is_jlong() const { + return llvm_value()->getType() == SharkType::jlong_type(); +} +bool SharkNormalValue::is_jfloat() const { + return llvm_value()->getType() == SharkType::jfloat_type(); +} +bool SharkNormalValue::is_jdouble() const { + return llvm_value()->getType() == SharkType::jdouble_type(); +} +bool SharkNormalValue::is_jobject() const { + return llvm_value()->getType() == SharkType::oop_type(); +} +bool SharkNormalValue::is_jarray() const { + return basic_type() == T_ARRAY; +} +bool SharkAddressValue::is_address() const { + return true; +} + +// Typed conversions from SharkValues + +Value* SharkValue::jint_value() const { + ShouldNotCallThis(); +} +Value* SharkValue::jlong_value() const { + ShouldNotCallThis(); +} +Value* SharkValue::jfloat_value() const { + ShouldNotCallThis(); +} +Value* SharkValue::jdouble_value() const { + ShouldNotCallThis(); +} +Value* SharkValue::jobject_value() const { + ShouldNotCallThis(); +} +Value* SharkValue::jarray_value() const { + ShouldNotCallThis(); +} +int SharkValue::address_value() const { + ShouldNotCallThis(); +} + +Value* SharkNormalValue::jint_value() const { + assert(is_jint(), "should be"); + return llvm_value(); +} +Value* SharkNormalValue::jlong_value() const { + assert(is_jlong(), "should be"); + return llvm_value(); +} +Value* SharkNormalValue::jfloat_value() const { + assert(is_jfloat(), "should be"); + return llvm_value(); +} +Value* SharkNormalValue::jdouble_value() const { + assert(is_jdouble(), "should be"); + return llvm_value(); +} +Value* SharkNormalValue::jobject_value() const { + assert(is_jobject(), "should be"); + return llvm_value(); +} +Value* SharkNormalValue::jarray_value() const { + // XXX assert(is_jarray(), "should be"); + // XXX http://icedtea.classpath.org/bugzilla/show_bug.cgi?id=324 + assert(is_jobject(), "should be"); + return llvm_value(); +} +int SharkAddressValue::address_value() const { + return _bci; +} + +// Type-losing conversions -- use with care! + +Value* SharkNormalValue::generic_value() const { + return llvm_value(); +} +Value* SharkAddressValue::generic_value() const { + return LLVMValue::intptr_constant(address_value()); +} + +Value* SharkValue::intptr_value(SharkBuilder* builder) const { + ShouldNotCallThis(); +} +Value* SharkNormalValue::intptr_value(SharkBuilder* builder) const { + return builder->CreatePtrToInt(jobject_value(), SharkType::intptr_type()); +} + +// Phi-style stuff for SharkPHIState::add_incoming + +void SharkValue::addIncoming(SharkValue *value, BasicBlock* block) { + ShouldNotCallThis(); +} +void SharkPHIValue::addIncoming(SharkValue *value, BasicBlock* block) { + assert(!is_clone(), "shouldn't be"); + ((llvm::PHINode *) generic_value())->addIncoming( + value->generic_value(), block); + if (!value->zero_checked()) + _all_incomers_zero_checked = false; +} +void SharkAddressValue::addIncoming(SharkValue *value, BasicBlock* block) { + assert(this->equal_to(value), "should be"); +} + +// Phi-style stuff for SharkState::merge + +SharkValue* SharkNormalValue::merge(SharkBuilder* builder, + SharkValue* other, + BasicBlock* other_block, + BasicBlock* this_block, + const char* name) { + assert(type() == other->type(), "should be"); + assert(zero_checked() == other->zero_checked(), "should be"); + + PHINode *phi = builder->CreatePHI(SharkType::to_stackType(type()), name); + phi->addIncoming(this->generic_value(), this_block); + phi->addIncoming(other->generic_value(), other_block); + return SharkValue::create_generic(type(), phi, zero_checked()); +} +SharkValue* SharkAddressValue::merge(SharkBuilder* builder, + SharkValue* other, + BasicBlock* other_block, + BasicBlock* this_block, + const char* name) { + assert(this->equal_to(other), "should be"); + return this; +} + +// Repeated null and divide-by-zero check removal + +bool SharkValue::zero_checked() const { + ShouldNotCallThis(); +} +void SharkValue::set_zero_checked(bool zero_checked) { + ShouldNotCallThis(); +} + +bool SharkNormalValue::zero_checked() const { + return _zero_checked; +} +void SharkNormalValue::set_zero_checked(bool zero_checked) { + _zero_checked = zero_checked; +} diff --git a/hotspot/src/share/vm/shark/sharkValue.hpp b/hotspot/src/share/vm/shark/sharkValue.hpp new file mode 100644 index 00000000000..06fcad1be19 --- /dev/null +++ b/hotspot/src/share/vm/shark/sharkValue.hpp @@ -0,0 +1,332 @@ +/* + * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009 Red Hat, Inc. + * 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. + * + */ + +// Items on the stack and in local variables are tracked using +// SharkValue objects. +// +// All SharkValues are one of two core types, SharkNormalValue +// and SharkAddressValue, but no code outside this file should +// ever refer to those directly. The split is because of the +// way JSRs are handled: the typeflow pass expands them into +// multiple copies, so the return addresses pushed by jsr and +// popped by ret only exist at compile time. Having separate +// classes for these allows us to check that our jsr handling +// is correct, via assertions. +// +// There is one more type, SharkPHIValue, which is a subclass +// of SharkNormalValue with a couple of extra methods. Use of +// SharkPHIValue outside of this file is acceptable, so long +// as it is obtained via SharkValue::as_phi(). + +class SharkBuilder; +class SharkPHIValue; + +class SharkValue : public ResourceObj { + protected: + SharkValue() {} + + // Cloning + public: + virtual SharkValue* clone() const = 0; + + // Casting + public: + virtual bool is_phi() const; + virtual SharkPHIValue* as_phi(); + + // Comparison + public: + virtual bool equal_to(SharkValue* other) const = 0; + + // Type access + public: + virtual BasicType basic_type() const = 0; + virtual ciType* type() const; + + virtual bool is_jint() const; + virtual bool is_jlong() const; + virtual bool is_jfloat() const; + virtual bool is_jdouble() const; + virtual bool is_jobject() const; + virtual bool is_jarray() const; + virtual bool is_address() const; + + virtual int size() const = 0; + + bool is_one_word() const { + return size() == 1; + } + bool is_two_word() const { + return size() == 2; + } + + // Typed conversion from SharkValues + public: + virtual llvm::Value* jint_value() const; + virtual llvm::Value* jlong_value() const; + virtual llvm::Value* jfloat_value() const; + virtual llvm::Value* jdouble_value() const; + virtual llvm::Value* jobject_value() const; + virtual llvm::Value* jarray_value() const; + virtual int address_value() const; + + // Typed conversion to SharkValues + public: + static SharkValue* create_jint(llvm::Value* value, bool zero_checked) { + assert(value->getType() == SharkType::jint_type(), "should be"); + return create_generic(ciType::make(T_INT), value, zero_checked); + } + static SharkValue* create_jlong(llvm::Value* value, bool zero_checked) { + assert(value->getType() == SharkType::jlong_type(), "should be"); + return create_generic(ciType::make(T_LONG), value, zero_checked); + } + static SharkValue* create_jfloat(llvm::Value* value) { + assert(value->getType() == SharkType::jfloat_type(), "should be"); + return create_generic(ciType::make(T_FLOAT), value, false); + } + static SharkValue* create_jdouble(llvm::Value* value) { + assert(value->getType() == SharkType::jdouble_type(), "should be"); + return create_generic(ciType::make(T_DOUBLE), value, false); + } + static SharkValue* create_jobject(llvm::Value* value, bool zero_checked) { + assert(value->getType() == SharkType::oop_type(), "should be"); + return create_generic(ciType::make(T_OBJECT), value, zero_checked); + } + + // Typed conversion from constants of various types + public: + static SharkValue* jint_constant(jint value) { + return create_jint(LLVMValue::jint_constant(value), value != 0); + } + static SharkValue* jlong_constant(jlong value) { + return create_jlong(LLVMValue::jlong_constant(value), value != 0); + } + static SharkValue* jfloat_constant(jfloat value) { + return create_jfloat(LLVMValue::jfloat_constant(value)); + } + static SharkValue* jdouble_constant(jdouble value) { + return create_jdouble(LLVMValue::jdouble_constant(value)); + } + static SharkValue* null() { + return create_jobject(LLVMValue::null(), false); + } + static inline SharkValue* address_constant(int bci); + + // Type-losing conversions -- use with care! + public: + virtual llvm::Value* generic_value() const = 0; + virtual llvm::Value* intptr_value(SharkBuilder* builder) const; + + static inline SharkValue* create_generic(ciType* type, + llvm::Value* value, + bool zero_checked); + static inline SharkValue* create_phi(ciType* type, + llvm::PHINode* phi, + const SharkPHIValue* parent = NULL); + + // Phi-style stuff + public: + virtual void addIncoming(SharkValue* value, llvm::BasicBlock* block); + virtual SharkValue* merge(SharkBuilder* builder, + SharkValue* other, + llvm::BasicBlock* other_block, + llvm::BasicBlock* this_block, + const char* name) = 0; + + // Repeated null and divide-by-zero check removal + public: + virtual bool zero_checked() const; + virtual void set_zero_checked(bool zero_checked); +}; + +class SharkNormalValue : public SharkValue { + friend class SharkValue; + + protected: + SharkNormalValue(ciType* type, llvm::Value* value, bool zero_checked) + : _type(type), _llvm_value(value), _zero_checked(zero_checked) {} + + private: + ciType* _type; + llvm::Value* _llvm_value; + bool _zero_checked; + + private: + llvm::Value* llvm_value() const { + return _llvm_value; + } + + // Cloning + public: + SharkValue* clone() const; + + // Comparison + public: + bool equal_to(SharkValue* other) const; + + // Type access + public: + ciType* type() const; + BasicType basic_type() const; + int size() const; + + public: + bool is_jint() const; + bool is_jlong() const; + bool is_jfloat() const; + bool is_jdouble() const; + bool is_jobject() const; + bool is_jarray() const; + + // Typed conversions to LLVM values + public: + llvm::Value* jint_value() const; + llvm::Value* jlong_value() const; + llvm::Value* jfloat_value() const; + llvm::Value* jdouble_value() const; + llvm::Value* jobject_value() const; + llvm::Value* jarray_value() const; + + // Type-losing conversions, use with care + public: + llvm::Value* generic_value() const; + llvm::Value* intptr_value(SharkBuilder* builder) const; + + // Phi-style stuff + public: + SharkValue* merge(SharkBuilder* builder, + SharkValue* other, + llvm::BasicBlock* other_block, + llvm::BasicBlock* this_block, + const char* name); + + // Repeated null and divide-by-zero check removal + public: + bool zero_checked() const; + void set_zero_checked(bool zero_checked); +}; + +class SharkPHIValue : public SharkNormalValue { + friend class SharkValue; + + protected: + SharkPHIValue(ciType* type, llvm::PHINode* phi, const SharkPHIValue *parent) + : SharkNormalValue(type, phi, parent && parent->zero_checked()), + _parent(parent), + _all_incomers_zero_checked(true) {} + + private: + const SharkPHIValue* _parent; + bool _all_incomers_zero_checked; + + private: + const SharkPHIValue* parent() const { + return _parent; + } + bool is_clone() const { + return parent() != NULL; + } + + public: + bool all_incomers_zero_checked() const { + if (is_clone()) + return parent()->all_incomers_zero_checked(); + + return _all_incomers_zero_checked; + } + + // Cloning + public: + SharkValue* clone() const; + + // Casting + public: + bool is_phi() const; + SharkPHIValue* as_phi(); + + // Phi-style stuff + public: + void addIncoming(SharkValue *value, llvm::BasicBlock* block); +}; + +class SharkAddressValue : public SharkValue { + friend class SharkValue; + + protected: + SharkAddressValue(int bci) + : _bci(bci) {} + + private: + int _bci; + + // Cloning + public: + SharkValue* clone() const; + + // Comparison + public: + bool equal_to(SharkValue* other) const; + + // Type access + public: + BasicType basic_type() const; + int size() const; + bool is_address() const; + + // Typed conversion from SharkValues + public: + int address_value() const; + + // Type-losing conversion -- use with care! + public: + llvm::Value* generic_value() const; + + // Phi-style stuff + public: + void addIncoming(SharkValue *value, llvm::BasicBlock* block); + SharkValue* merge(SharkBuilder* builder, + SharkValue* other, + llvm::BasicBlock* other_block, + llvm::BasicBlock* this_block, + const char* name); +}; + +// SharkValue methods that can't be declared above + +inline SharkValue* SharkValue::create_generic(ciType* type, + llvm::Value* value, + bool zero_checked) { + return new SharkNormalValue(type, value, zero_checked); +} + +inline SharkValue* SharkValue::create_phi(ciType* type, + llvm::PHINode* phi, + const SharkPHIValue* parent) { + return new SharkPHIValue(type, phi, parent); +} + +inline SharkValue* SharkValue::address_constant(int bci) { + return new SharkAddressValue(bci); +} diff --git a/hotspot/src/share/vm/shark/shark_globals.cpp b/hotspot/src/share/vm/shark/shark_globals.cpp new file mode 100644 index 00000000000..50ea5295d97 --- /dev/null +++ b/hotspot/src/share/vm/shark/shark_globals.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008 Red Hat, Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_shark_globals.cpp.incl" + +SHARK_FLAGS(MATERIALIZE_DEVELOPER_FLAG, MATERIALIZE_PD_DEVELOPER_FLAG, MATERIALIZE_PRODUCT_FLAG, MATERIALIZE_PD_PRODUCT_FLAG, MATERIALIZE_DIAGNOSTIC_FLAG, MATERIALIZE_NOTPRODUCT_FLAG) diff --git a/hotspot/src/share/vm/shark/shark_globals.hpp b/hotspot/src/share/vm/shark/shark_globals.hpp new file mode 100644 index 00000000000..f0f7d3bbffa --- /dev/null +++ b/hotspot/src/share/vm/shark/shark_globals.hpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright 2008, 2009, 2010 Red Hat, Inc. + * 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. + * + */ + +#define SHARK_FLAGS(develop, develop_pd, product, product_pd, diagnostic, notproduct) \ + \ + product(intx, MaxNodeLimit, 65000, \ + "Maximum number of nodes") \ + \ + /* inlining */ \ + product(intx, SharkMaxInlineSize, 32, \ + "Maximum bytecode size of methods to inline when using Shark") \ + \ + /* compiler debugging */ \ + develop(ccstr, SharkPrintTypeflowOf, NULL, \ + "Print the typeflow of the specified method") \ + \ + diagnostic(ccstr, SharkPrintBitcodeOf, NULL, \ + "Print the LLVM bitcode of the specified method") \ + \ + diagnostic(ccstr, SharkPrintAsmOf, NULL, \ + "Print the asm of the specified method") \ + \ + develop(bool, SharkTraceBytecodes, false, \ + "Trace bytecode compilation") \ + \ + diagnostic(bool, SharkTraceInstalls, false, \ + "Trace method installation") \ + \ + diagnostic(bool, SharkPerformanceWarnings, false, \ + "Warn about things that could be made faster") \ + +SHARK_FLAGS(DECLARE_DEVELOPER_FLAG, DECLARE_PD_DEVELOPER_FLAG, DECLARE_PRODUCT_FLAG, DECLARE_PD_PRODUCT_FLAG, DECLARE_DIAGNOSTIC_FLAG, DECLARE_NOTPRODUCT_FLAG) diff --git a/hotspot/src/share/vm/utilities/constantTag.cpp b/hotspot/src/share/vm/utilities/constantTag.cpp index f6fb94a63c9..4d0bfe89bfb 100644 --- a/hotspot/src/share/vm/utilities/constantTag.cpp +++ b/hotspot/src/share/vm/utilities/constantTag.cpp @@ -91,6 +91,8 @@ const char* constantTag::internal_name() const { return "MethodHandle"; case JVM_CONSTANT_MethodType : return "MethodType"; + case JVM_CONSTANT_InvokeDynamic : + return "InvokeDynamic"; case JVM_CONSTANT_Object : return "Object"; case JVM_CONSTANT_Utf8 : diff --git a/hotspot/src/share/vm/utilities/constantTag.hpp b/hotspot/src/share/vm/utilities/constantTag.hpp index 97a9fe99104..39e335039e7 100644 --- a/hotspot/src/share/vm/utilities/constantTag.hpp +++ b/hotspot/src/share/vm/utilities/constantTag.hpp @@ -80,13 +80,14 @@ class constantTag VALUE_OBJ_CLASS_SPEC { bool is_method_type() const { return _tag == JVM_CONSTANT_MethodType; } bool is_method_handle() const { return _tag == JVM_CONSTANT_MethodHandle; } + bool is_invoke_dynamic() const { return _tag == JVM_CONSTANT_InvokeDynamic; } constantTag() { _tag = JVM_CONSTANT_Invalid; } constantTag(jbyte tag) { assert((tag >= 0 && tag <= JVM_CONSTANT_NameAndType) || - (tag >= JVM_CONSTANT_MethodHandle && tag <= JVM_CONSTANT_MethodType) || + (tag >= JVM_CONSTANT_MethodHandle && tag <= JVM_CONSTANT_InvokeDynamic) || (tag >= JVM_CONSTANT_InternalMin && tag <= JVM_CONSTANT_InternalMax), "Invalid constant tag"); _tag = tag; } diff --git a/hotspot/src/share/vm/utilities/debug.cpp b/hotspot/src/share/vm/utilities/debug.cpp index 0706ed1c9d6..7b1cd2200b0 100644 --- a/hotspot/src/share/vm/utilities/debug.cpp +++ b/hotspot/src/share/vm/utilities/debug.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -552,140 +552,6 @@ static address same_page(address x, address y) { } } - -static void find(intptr_t x, bool print_pc) { - address addr = (address)x; - - CodeBlob* b = CodeCache::find_blob_unsafe(addr); - if (b != NULL) { - if (b->is_buffer_blob()) { - // the interpreter is generated into a buffer blob - InterpreterCodelet* i = Interpreter::codelet_containing(addr); - if (i != NULL) { - i->print(); - return; - } - if (Interpreter::contains(addr)) { - tty->print_cr(INTPTR_FORMAT " is pointing into interpreter code (not bytecode specific)", addr); - return; - } - // - if (AdapterHandlerLibrary::contains(b)) { - AdapterHandlerLibrary::print_handler(b); - } - // the stubroutines are generated into a buffer blob - StubCodeDesc* d = StubCodeDesc::desc_for(addr); - if (d != NULL) { - d->print(); - if (print_pc) tty->cr(); - return; - } - if (StubRoutines::contains(addr)) { - tty->print_cr(INTPTR_FORMAT " is pointing to an (unnamed) stub routine", addr); - return; - } - // the InlineCacheBuffer is using stubs generated into a buffer blob - if (InlineCacheBuffer::contains(addr)) { - tty->print_cr(INTPTR_FORMAT " is pointing into InlineCacheBuffer", addr); - return; - } - VtableStub* v = VtableStubs::stub_containing(addr); - if (v != NULL) { - v->print(); - return; - } - } - if (print_pc && b->is_nmethod()) { - ResourceMark rm; - tty->print("%#p: Compiled ", addr); - ((nmethod*)b)->method()->print_value_on(tty); - tty->print(" = (CodeBlob*)" INTPTR_FORMAT, b); - tty->cr(); - return; - } - if ( b->is_nmethod()) { - if (b->is_zombie()) { - tty->print_cr(INTPTR_FORMAT " is zombie nmethod", b); - } else if (b->is_not_entrant()) { - tty->print_cr(INTPTR_FORMAT " is non-entrant nmethod", b); - } - } - b->print(); - return; - } - - if (Universe::heap()->is_in(addr)) { - HeapWord* p = Universe::heap()->block_start(addr); - bool print = false; - // If we couldn't find it it just may mean that heap wasn't parseable - // See if we were just given an oop directly - if (p != NULL && Universe::heap()->block_is_obj(p)) { - print = true; - } else if (p == NULL && ((oopDesc*)addr)->is_oop()) { - p = (HeapWord*) addr; - print = true; - } - if (print) { - oop(p)->print(); - if (p != (HeapWord*)x && oop(p)->is_constMethod() && - constMethodOop(p)->contains(addr)) { - Thread *thread = Thread::current(); - HandleMark hm(thread); - methodHandle mh (thread, constMethodOop(p)->method()); - if (!mh->is_native()) { - tty->print_cr("bci_from(%p) = %d; print_codes():", - addr, mh->bci_from(address(x))); - mh->print_codes(); - } - } - return; - } - } else if (Universe::heap()->is_in_reserved(addr)) { - tty->print_cr(INTPTR_FORMAT " is an unallocated location in the heap", addr); - return; - } - - if (JNIHandles::is_global_handle((jobject) addr)) { - tty->print_cr(INTPTR_FORMAT " is a global jni handle", addr); - return; - } - if (JNIHandles::is_weak_global_handle((jobject) addr)) { - tty->print_cr(INTPTR_FORMAT " is a weak global jni handle", addr); - return; - } - if (JNIHandleBlock::any_contains((jobject) addr)) { - tty->print_cr(INTPTR_FORMAT " is a local jni handle", addr); - return; - } - - for(JavaThread *thread = Threads::first(); thread; thread = thread->next()) { - // Check for privilege stack - if (thread->privileged_stack_top() != NULL && thread->privileged_stack_top()->contains(addr)) { - tty->print_cr(INTPTR_FORMAT " is pointing into the privilege stack for thread: " INTPTR_FORMAT, addr, thread); - return; - } - // If the addr is a java thread print information about that. - if (addr == (address)thread) { - thread->print(); - return; - } - } - - // Try an OS specific find - if (os::find(addr)) { - return; - } - - if (print_pc) { - tty->print_cr(INTPTR_FORMAT ": probably in C++ code; check debugger", addr); - Disassembler::decode(same_page(addr-40,addr),same_page(addr+40,addr)); - return; - } - - tty->print_cr(INTPTR_FORMAT " is pointing to unknown location", addr); -} - - class LookForRefInGenClosure : public OopsInGenClosure { public: oop target; @@ -767,7 +633,7 @@ extern "C" void findclass(const char name[]) { // Can we someday rename the other find to hsfind? extern "C" void hsfind(intptr_t x) { Command c("hsfind"); - find(x, false); + os::print_location(tty, x, false); } @@ -778,13 +644,13 @@ extern "C" void hsfindref(intptr_t x) { extern "C" void find(intptr_t x) { Command c("find"); - find(x, false); + os::print_location(tty, x, false); } extern "C" void findpc(intptr_t x) { Command c("findpc"); - find(x, true); + os::print_location(tty, x, true); } diff --git a/hotspot/src/share/vm/utilities/exceptions.cpp b/hotspot/src/share/vm/utilities/exceptions.cpp index 59c6176b80e..ef37af5071b 100644 --- a/hotspot/src/share/vm/utilities/exceptions.cpp +++ b/hotspot/src/share/vm/utilities/exceptions.cpp @@ -117,7 +117,7 @@ void Exceptions::_throw(Thread* thread, const char* file, int line, Handle h_exc (address)h_exception(), file, line, thread); } // for AbortVMOnException flag - NOT_PRODUCT(Exceptions::debug_check_abort(h_exception)); + NOT_PRODUCT(Exceptions::debug_check_abort(h_exception, message)); // Check for special boot-strapping/vm-thread handling if (special_exception(thread, file, line, h_exception)) return; @@ -375,17 +375,26 @@ ExceptionMark::~ExceptionMark() { #ifndef PRODUCT // caller frees value_string if necessary -void Exceptions::debug_check_abort(const char *value_string) { +void Exceptions::debug_check_abort(const char *value_string, const char* message) { if (AbortVMOnException != NULL && value_string != NULL && strstr(value_string, AbortVMOnException)) { - fatal(err_msg("Saw %s, aborting", value_string)); + if (AbortVMOnExceptionMessage == NULL || message == NULL || + strcmp(message, AbortVMOnExceptionMessage) == 0) { + fatal(err_msg("Saw %s, aborting", value_string)); + } } } -void Exceptions::debug_check_abort(Handle exception) { +void Exceptions::debug_check_abort(Handle exception, const char* message) { if (AbortVMOnException != NULL) { ResourceMark rm; - debug_check_abort(instanceKlass::cast(exception()->klass())->external_name()); + if (message == NULL && exception->is_a(SystemDictionary::Throwable_klass())) { + oop msg = java_lang_Throwable::message(exception); + if (msg != NULL) { + message = java_lang_String::as_utf8_string(msg); + } + } + debug_check_abort(instanceKlass::cast(exception()->klass())->external_name(), message); } } #endif diff --git a/hotspot/src/share/vm/utilities/exceptions.hpp b/hotspot/src/share/vm/utilities/exceptions.hpp index a331d03f0cc..245bfa4150d 100644 --- a/hotspot/src/share/vm/utilities/exceptions.hpp +++ b/hotspot/src/share/vm/utilities/exceptions.hpp @@ -143,8 +143,8 @@ class Exceptions { static void throw_stack_overflow_exception(Thread* thread, const char* file, int line); // for AbortVMOnException flag - NOT_PRODUCT(static void debug_check_abort(Handle exception);) - NOT_PRODUCT(static void debug_check_abort(const char *value_string);) + NOT_PRODUCT(static void debug_check_abort(Handle exception, const char* message = NULL);) + NOT_PRODUCT(static void debug_check_abort(const char *value_string, const char* message = NULL);) }; diff --git a/hotspot/src/share/vm/utilities/globalDefinitions.hpp b/hotspot/src/share/vm/utilities/globalDefinitions.hpp index a5a8ae403d2..97d96c21f12 100644 --- a/hotspot/src/share/vm/utilities/globalDefinitions.hpp +++ b/hotspot/src/share/vm/utilities/globalDefinitions.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -345,6 +345,35 @@ inline intptr_t align_object_offset(intptr_t offset) { return align_size_up(offset, HeapWordsPerLong); } +// The expected size in bytes of a cache line, used to pad data structures. +#define DEFAULT_CACHE_LINE_SIZE 64 + +// Bytes needed to pad type to avoid cache-line sharing; alignment should be the +// expected cache line size (a power of two). The first addend avoids sharing +// when the start address is not a multiple of alignment; the second maintains +// alignment of starting addresses that happen to be a multiple. +#define PADDING_SIZE(type, alignment) \ + ((alignment) + align_size_up_(sizeof(type), alignment)) + +// Templates to create a subclass padded to avoid cache line sharing. These are +// effective only when applied to derived-most (leaf) classes. + +// When no args are passed to the base ctor. +template +class Padded: public T { +private: + char _pad_buf_[PADDING_SIZE(T, alignment)]; +}; + +// When either 0 or 1 args may be passed to the base ctor. +template +class Padded01: public T { +public: + Padded01(): T() { } + Padded01(Arg1T arg1): T(arg1) { } +private: + char _pad_buf_[PADDING_SIZE(T, alignment)]; +}; //---------------------------------------------------------------------------------------------------- // Utility macros for compilers diff --git a/hotspot/src/share/vm/utilities/globalDefinitions_gcc.hpp b/hotspot/src/share/vm/utilities/globalDefinitions_gcc.hpp index f069a5377ea..398f01b9471 100644 --- a/hotspot/src/share/vm/utilities/globalDefinitions_gcc.hpp +++ b/hotspot/src/share/vm/utilities/globalDefinitions_gcc.hpp @@ -216,8 +216,16 @@ extern "C" { #define DEBUG_EXCEPTION ::abort(); +#ifdef ARM +#ifdef SOLARIS +#define BREAKPOINT __asm__ volatile (".long 0xe1200070") +#else +#define BREAKPOINT __asm__ volatile (".long 0xe7f001f0") +#endif +#else extern "C" void breakpoint(); #define BREAKPOINT ::breakpoint() +#endif // checking for nanness #ifdef SOLARIS @@ -235,6 +243,12 @@ inline int g_isnan(double f) { return isnan(f); } #error "missing platform-specific definition here" #endif +// GCC 4.3 does not allow 0.0/0.0 to produce a NAN value +#if (__GNUC__ == 4) && (__GNUC_MINOR__ > 2) +#define CAN_USE_NAN_DEFINE 1 +#endif + + // Checking for finiteness inline int g_isfinite(jfloat f) { return finite(f); } diff --git a/hotspot/src/share/vm/utilities/growableArray.hpp b/hotspot/src/share/vm/utilities/growableArray.hpp index becb38ce107..e3941cfcb6f 100644 --- a/hotspot/src/share/vm/utilities/growableArray.hpp +++ b/hotspot/src/share/vm/utilities/growableArray.hpp @@ -97,7 +97,10 @@ class GenericGrowableArray : public ResourceObj { assert(_len >= 0 && _len <= _max, "initial_len too big"); _arena = (c_heap ? (Arena*)1 : NULL); set_nesting(); - assert(!c_heap || allocated_on_C_heap(), "growable array must be on C heap if elements are"); + assert(!on_C_heap() || allocated_on_C_heap(), "growable array must be on C heap if elements are"); + assert(!on_stack() || + (allocated_on_res_area() || allocated_on_stack()), + "growable array must be on stack if elements are not on arena and not on C heap"); } // This GA will use the given arena for storage. @@ -108,6 +111,10 @@ class GenericGrowableArray : public ResourceObj { assert(_len >= 0 && _len <= _max, "initial_len too big"); _arena = arena; assert(on_arena(), "arena has taken on reserved value 0 or 1"); + // Relax next assert to allow object allocation on resource area, + // on stack or embedded into an other object. + assert(allocated_on_arena() || allocated_on_stack(), + "growable array must be on arena or on stack if elements are on arena"); } void* raw_allocate(int elementSize); diff --git a/hotspot/src/share/vm/utilities/macros.hpp b/hotspot/src/share/vm/utilities/macros.hpp index 97b86c13410..4f89f2aebe0 100644 --- a/hotspot/src/share/vm/utilities/macros.hpp +++ b/hotspot/src/share/vm/utilities/macros.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -151,9 +151,11 @@ #if defined(IA32) || defined(AMD64) #define X86 #define X86_ONLY(code) code +#define NOT_X86(code) #else #undef X86 #define X86_ONLY(code) +#define NOT_X86(code) code #endif #ifdef IA32 @@ -188,4 +190,37 @@ #define NOT_SPARC(code) code #endif +#ifdef PPC +#define PPC_ONLY(code) code +#define NOT_PPC(code) +#else +#define PPC_ONLY(code) +#define NOT_PPC(code) code +#endif + +#ifdef E500V2 +#define E500V2_ONLY(code) code +#define NOT_E500V2(code) +#else +#define E500V2_ONLY(code) +#define NOT_E500V2(code) code +#endif + + +#ifdef ARM +#define ARM_ONLY(code) code +#define NOT_ARM(code) +#else +#define ARM_ONLY(code) +#define NOT_ARM(code) code +#endif + +#ifdef JAVASE_EMBEDDED +#define EMBEDDED_ONLY(code) code +#define NOT_EMBEDDED(code) +#else +#define EMBEDDED_ONLY(code) +#define NOT_EMBEDDED(code) code +#endif + #define define_pd_global(type, name, value) const type pd_##name = value; diff --git a/hotspot/src/share/vm/utilities/taskqueue.cpp b/hotspot/src/share/vm/utilities/taskqueue.cpp index 66571581e64..7a001803d96 100644 --- a/hotspot/src/share/vm/utilities/taskqueue.cpp +++ b/hotspot/src/share/vm/utilities/taskqueue.cpp @@ -31,6 +31,48 @@ uint ParallelTaskTerminator::_total_spins = 0; uint ParallelTaskTerminator::_total_peeks = 0; #endif +#if TASKQUEUE_STATS +const char * const TaskQueueStats::_names[last_stat_id] = { + "qpush", "qpop", "qpop-s", "qattempt", "qsteal", "opush", "omax" +}; + +void TaskQueueStats::print_header(unsigned int line, outputStream* const stream, + unsigned int width) +{ + // Use a width w: 1 <= w <= max_width + const unsigned int max_width = 40; + const unsigned int w = MAX2(MIN2(width, max_width), 1U); + + if (line == 0) { // spaces equal in width to the header + const unsigned int hdr_width = w * last_stat_id + last_stat_id - 1; + stream->print("%*s", hdr_width, " "); + } else if (line == 1) { // labels + stream->print("%*s", w, _names[0]); + for (unsigned int i = 1; i < last_stat_id; ++i) { + stream->print(" %*s", w, _names[i]); + } + } else if (line == 2) { // dashed lines + char dashes[max_width + 1]; + memset(dashes, '-', w); + dashes[w] = '\0'; + stream->print("%s", dashes); + for (unsigned int i = 1; i < last_stat_id; ++i) { + stream->print(" %s", dashes); + } + } +} + +void TaskQueueStats::print(outputStream* stream, unsigned int width) const +{ + #define FMT SIZE_FORMAT_W(*) + stream->print(FMT, width, _stats[0]); + for (unsigned int i = 1; i < last_stat_id; ++i) { + stream->print(" " FMT, width, _stats[i]); + } + #undef FMT +} +#endif // TASKQUEUE_STATS + int TaskQueueSetSuper::randomParkAndMiller(int *seed0) { const int a = 16807; const int m = 2147483647; diff --git a/hotspot/src/share/vm/utilities/taskqueue.hpp b/hotspot/src/share/vm/utilities/taskqueue.hpp index 2deba1b9edb..52e89fc8027 100644 --- a/hotspot/src/share/vm/utilities/taskqueue.hpp +++ b/hotspot/src/share/vm/utilities/taskqueue.hpp @@ -22,6 +22,72 @@ * */ +// Simple TaskQueue stats that are collected by default in debug builds. + +#if !defined(TASKQUEUE_STATS) && defined(ASSERT) +#define TASKQUEUE_STATS 1 +#elif !defined(TASKQUEUE_STATS) +#define TASKQUEUE_STATS 0 +#endif + +#if TASKQUEUE_STATS +#define TASKQUEUE_STATS_ONLY(code) code +#else +#define TASKQUEUE_STATS_ONLY(code) +#endif // TASKQUEUE_STATS + +#if TASKQUEUE_STATS +class TaskQueueStats { +public: + enum StatId { + push, // number of taskqueue pushes + pop, // number of taskqueue pops + pop_slow, // subset of taskqueue pops that were done slow-path + steal_attempt, // number of taskqueue steal attempts + steal, // number of taskqueue steals + overflow, // number of overflow pushes + overflow_max_len, // max length of overflow stack + last_stat_id + }; + +public: + inline TaskQueueStats() { reset(); } + + inline void record_push() { ++_stats[push]; } + inline void record_pop() { ++_stats[pop]; } + inline void record_pop_slow() { record_pop(); ++_stats[pop_slow]; } + inline void record_steal(bool success); + inline void record_overflow(size_t new_length); + + inline size_t get(StatId id) const { return _stats[id]; } + inline const size_t* get() const { return _stats; } + + inline void reset(); + + static void print_header(unsigned int line, outputStream* const stream = tty, + unsigned int width = 10); + void print(outputStream* const stream = tty, unsigned int width = 10) const; + +private: + size_t _stats[last_stat_id]; + static const char * const _names[last_stat_id]; +}; + +void TaskQueueStats::record_steal(bool success) { + ++_stats[steal_attempt]; + if (success) ++_stats[steal]; +} + +void TaskQueueStats::record_overflow(size_t new_len) { + ++_stats[overflow]; + if (new_len > _stats[overflow_max_len]) _stats[overflow_max_len] = new_len; +} + +void TaskQueueStats::reset() { + memset(_stats, 0, sizeof(_stats)); +} +#endif // TASKQUEUE_STATS + template class TaskQueueSuper: public CHeapObj { protected: @@ -135,6 +201,8 @@ public: // Total size of queue. static const uint total_size() { return N; } + + TASKQUEUE_STATS_ONLY(TaskQueueStats stats;) }; template @@ -152,6 +220,7 @@ protected: public: using TaskQueueSuper::max_elems; using TaskQueueSuper::size; + TASKQUEUE_STATS_ONLY(using TaskQueueSuper::stats;) private: // Slow paths for push, pop_local. (pop_global has no fast path.) @@ -224,14 +293,14 @@ bool GenericTaskQueue::push_slow(E t, uint dirty_n_elems) { // g++ complains if the volatile result of the assignment is unused. const_cast(_elems[localBot] = t); OrderAccess::release_store(&_bottom, increment_index(localBot)); + TASKQUEUE_STATS_ONLY(stats.record_push()); return true; } return false; } template -bool GenericTaskQueue:: -pop_local_slow(uint localBot, Age oldAge) { +bool GenericTaskQueue::pop_local_slow(uint localBot, Age oldAge) { // This queue was observed to contain exactly one element; either this // thread will claim it, or a competing "pop_global". In either case, // the queue will be logically empty afterwards. Create a new Age value @@ -251,6 +320,7 @@ pop_local_slow(uint localBot, Age oldAge) { if (tempAge == oldAge) { // We win. assert(dirty_size(localBot, _age.top()) != N - 1, "sanity"); + TASKQUEUE_STATS_ONLY(stats.record_pop_slow()); return true; } } @@ -306,6 +376,8 @@ public: typedef GrowableArray overflow_t; typedef GenericTaskQueue taskqueue_t; + TASKQUEUE_STATS_ONLY(using taskqueue_t::stats;) + OverflowTaskQueue(); ~OverflowTaskQueue(); void initialize(); @@ -356,6 +428,7 @@ bool OverflowTaskQueue::push(E t) { if (!taskqueue_t::push(t)) { overflow_stack()->push(t); + TASKQUEUE_STATS_ONLY(stats.record_overflow(overflow_stack()->length())); } return true; } @@ -424,9 +497,13 @@ GenericTaskQueueSet::queue(uint i) { template bool GenericTaskQueueSet::steal(uint queue_num, int* seed, E& t) { - for (uint i = 0; i < 2 * _n; i++) - if (steal_best_of_2(queue_num, seed, t)) + for (uint i = 0; i < 2 * _n; i++) { + if (steal_best_of_2(queue_num, seed, t)) { + TASKQUEUE_STATS_ONLY(queue(queue_num)->stats.record_steal(true)); return true; + } + } + TASKQUEUE_STATS_ONLY(queue(queue_num)->stats.record_steal(false)); return false; } @@ -574,6 +651,7 @@ GenericTaskQueue::push(E t) { // g++ complains if the volatile result of the assignment is unused. const_cast(_elems[localBot] = t); OrderAccess::release_store(&_bottom, increment_index(localBot)); + TASKQUEUE_STATS_ONLY(stats.record_push()); return true; } else { return push_slow(t, dirty_n_elems); @@ -603,6 +681,7 @@ GenericTaskQueue::pop_local(E& t) { idx_t tp = _age.top(); // XXX if (size(localBot, tp) > 0) { assert(dirty_size(localBot, tp) != N - 1, "sanity"); + TASKQUEUE_STATS_ONLY(stats.record_pop()); return true; } else { // Otherwise, the queue contained exactly one element; we take the slow diff --git a/hotspot/src/share/vm/utilities/vmError.cpp b/hotspot/src/share/vm/utilities/vmError.cpp index a63a7b34330..15d66ab9ceb 100644 --- a/hotspot/src/share/vm/utilities/vmError.cpp +++ b/hotspot/src/share/vm/utilities/vmError.cpp @@ -479,8 +479,8 @@ void VMError::report(outputStream* st) { if (fr.sp()) { st->print(", sp=" PTR_FORMAT, fr.sp()); - st->print(", free space=%" INTPTR_FORMAT "k", - ((intptr_t)fr.sp() - (intptr_t)stack_bottom) >> 10); + size_t free_stack_size = pointer_delta(fr.sp(), stack_bottom, 1024); + st->print(", free space=" SIZE_FORMAT "k", free_stack_size); } st->cr(); @@ -687,16 +687,13 @@ void VMError::report(outputStream* st) { # undef END } +VMError* volatile VMError::first_error = NULL; +volatile jlong VMError::first_error_tid = -1; void VMError::report_and_die() { // Don't allocate large buffer on stack static char buffer[O_BUFLEN]; - // First error, and its thread id. We must be able to handle native thread, - // so use thread id instead of Thread* to identify thread. - static VMError* first_error; - static jlong first_error_tid; - // An error could happen before tty is initialized or after it has been // destroyed. Here we use a very simple unbuffered fdStream for printing. // Only out.print_raw() and out.print_raw_cr() should be used, as other diff --git a/hotspot/src/share/vm/utilities/vmError.hpp b/hotspot/src/share/vm/utilities/vmError.hpp index a2bbca37c2a..4cca492995e 100644 --- a/hotspot/src/share/vm/utilities/vmError.hpp +++ b/hotspot/src/share/vm/utilities/vmError.hpp @@ -57,6 +57,10 @@ class VMError : public StackObj { int _current_step; const char * _current_step_info; int _verbose; + // First error, and its thread id. We must be able to handle native thread, + // so use thread id instead of Thread* to identify thread. + static VMError* volatile first_error; + static volatile jlong first_error_tid; // used by reporting about OOM size_t _size; @@ -108,4 +112,7 @@ public: // returns original handler for signal, if it was resetted, or NULL if // signal was not changed by error reporter static address get_resetted_sighandler(int sig); + + // check to see if fatal error reporting is in progress + static bool fatal_error_in_progress() { return first_error != NULL; } }; diff --git a/hotspot/test/compiler/6973329/Test.java b/hotspot/test/compiler/6973329/Test.java new file mode 100644 index 00000000000..caecf8bbdd9 --- /dev/null +++ b/hotspot/test/compiler/6973329/Test.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 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. + */ + +/** + * @test + * @bug 6973329 + * @summary C2 with Zero based COOP produces code with broken anti-dependency on x86 + * + * @run main/othervm -Xbatch -Xcomp -XX:CompileOnly=Test Test + */ + +class A { + A next; + int n; + + public int get_n() { + return n+1; + } +} +public class Test { + + A a; + + void test (A new_next) { + A prev_next = a.next; + a.next = new_next; + if (prev_next == null) { + a.n = a.get_n(); + } + } + + public static void main(String args[]) { + Test t = new Test(); + t.a = new A(); + t.a.n = 1; + t.test(new A()); + if (t.a.n != 2) { + System.out.println("Wrong value: " + t.a.n + " expected: 2"); + System.exit(97); + } + } +} + diff --git a/jaxp/.hgtags b/jaxp/.hgtags index 7aae73ac3d2..78015b4c1f1 100644 --- a/jaxp/.hgtags +++ b/jaxp/.hgtags @@ -77,3 +77,7 @@ d4adf4f2d14c7b79df0a81de884b6b57c6850802 jdk7-b98 d524be5ef62e8b8cb890c59a5d2c19ef0ab50d45 jdk7-b100 17f62a566a2020fd908e77106ed885e0c4e7c14d jdk7-b101 15573625af97d01c4e24549041cba7584da7fe88 jdk7-b102 +b7722e8788644507c10bb69a137de422d0300b24 jdk7-b103 +d42c4acb6424a094bdafe2ad9c8c1c7ca7fb7b7e jdk7-b104 +3233b9a4c12ef2663a356d08bb141c02736c7f49 jdk7-b105 +5ba8469212a6cab95ca652eea414b753be7d245a jdk7-b106 diff --git a/jaxws/.hgtags b/jaxws/.hgtags index f65a239c30b..09adbcc586b 100644 --- a/jaxws/.hgtags +++ b/jaxws/.hgtags @@ -77,3 +77,7 @@ dac23846092ad4956ed41b5278f8686476ae46ef jdk7-b97 bd26d0ce0c3cb43e58a8e2770cc03f26d96ffe5c jdk7-b100 b55ce274490082712f5e002b38d2eed505ca863d jdk7-b101 d8580443d1815d68e0035a0560634e50fa899288 jdk7-b102 +267386d6b923f724309cab855a555e2d86a15c8f jdk7-b103 +bbc4cce6c20aeca4862804a6e8315a2350d43633 jdk7-b104 +39eb4f3031f4a985664cace00fca3bd1eab1e0aa jdk7-b105 +bc45ccc5bcca6cbe4ea433e279d4a93b06ab38c6 jdk7-b106 diff --git a/jdk/.hgtags b/jdk/.hgtags index b21fc77da96..d9cb775cc67 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -78,3 +78,6 @@ b1903d7528d33b521df42bc9291bdcdd2f444a29 jdk7-b97 d58354a69011f3d3354765fa3167567c4c4a9612 jdk7-b101 13029a61b16bec06535d4f0aa98229b358684128 jdk7-b102 6488b70a23cc6dc4b7e00809bc503c2884bafb28 jdk7-b103 +1a92820132a0221c5bdedd42d0888c57ce4cbb34 jdk7-b104 +3b0abcb512807bb6f6d27755bc50103211bde6ee jdk7-b105 +b91ef6b60f4e19bf4592c6dd594c9bac62487519 jdk7-b106 diff --git a/jdk/make/common/Release.gmk b/jdk/make/common/Release.gmk index cf16ea8dd3a..bc40dcc9725 100644 --- a/jdk/make/common/Release.gmk +++ b/jdk/make/common/Release.gmk @@ -571,6 +571,16 @@ $(NOT_RT_JAR_LIST): FRC $(ECHO) "META-INF/services/com.sun.tools.xjc.Plugin" >> $@ $(ECHO) "com/sun/tools/" >> $@ $(ECHO) "sun/jvmstat/" >> $@ + $(ECHO) "sun/nio/cs/ext/" >> $@ + $(ECHO) "sun/awt/HKSCS.class" >> $@ + $(ECHO) "sun/awt/motif/X11GB2312$Decoder.class" >> $@ + $(ECHO) "sun/awt/motif/X11GB2312$Encoder.class" >> $@ + $(ECHO) "sun/awt/motif/X11GB2312.class" >> $@ + $(ECHO) "sun/awt/motif/X11GBK$Encoder.class" >> $@ + $(ECHO) "sun/awt/motif/X11GBK.class" >> $@ + $(ECHO) "sun/awt/motif/X11KSC5601$Decoder.class" >> $@ + $(ECHO) "sun/awt/motif/X11KSC5601$Encoder.class" >> $@ + $(ECHO) "sun/awt/motif/X11KSC5601.class" >> $@ $(ECHO) "sun/rmi/rmic/" >> $@ $(ECHO) "sun/tools/asm/" >> $@ $(ECHO) "sun/tools/java/" >> $@ diff --git a/jdk/make/common/shared/Defs-versions.gmk b/jdk/make/common/shared/Defs-versions.gmk index 327f3a49b01..870ae229f3b 100644 --- a/jdk/make/common/shared/Defs-versions.gmk +++ b/jdk/make/common/shared/Defs-versions.gmk @@ -191,7 +191,7 @@ endif # Generic REQUIRED_ANT_VER = 1.6.3 -REQUIRED_BOOT_VER = 1.5 +REQUIRED_BOOT_VER = 1.6 REQUIRED_FREETYPE_VERSION = 2.3.0 REQUIRED_MAKE_VER = 3.78 REQUIRED_UNZIP_VER = 5.12 diff --git a/jdk/make/docs/Makefile b/jdk/make/docs/Makefile index 20150c81a47..a2aaccb130f 100644 --- a/jdk/make/docs/Makefile +++ b/jdk/make/docs/Makefile @@ -47,9 +47,9 @@ BUG_SUBMIT_LINE = Submit a bug or feature # Url to devdocs page # Was: http://java.sun.com/javase/6/webnotes/devdocs-vs-specs.html -DEV_DOCS_URL-5 = http://java.sun.com/j2se/1.5.0/docs -DEV_DOCS_URL-6 = http://download.oracle.com/docs/cd/E17409_01/javase/6/docs -DEV_DOCS_URL-7 = http://download.oracle.com/docs/cd/E17409_01/javase/7/docs +DEV_DOCS_URL-5 = http://java.sun.com/j2se/1.5.0/docs/index.html +DEV_DOCS_URL-6 = http://download.oracle.com/javase/6/docs/index.html +DEV_DOCS_URL-7 = http://download.oracle.com/javase/7/docs/index.html DEV_DOCS_URL = $(DEV_DOCS_URL-$(JDK_MINOR_VERSION)) # Url to Java Language Spec @@ -84,6 +84,11 @@ ALL_SOURCE_DIRS = $(SHARE_SRC)/classes \ $(SHARE_SRC)/../solaris/classes \ $(SHARE_SRC)/../windows/classes \ $(SHARE_SRC)/doc/stub + +# List of directories that actually exist +ALL_EXISTING_SOURCE_DIRS := $(wildcard $(ALL_SOURCE_DIRS)) + +# List with classpath separator between them EMPTY:= SPACE:= $(EMPTY) $(EMPTY) RELEASEDOCS_SOURCEPATH = \ @@ -240,7 +245,8 @@ include NON_CORE_PKGS.gmk # Default target is same as docs target, create core api and all others it can # -all docs: coredocs otherdocs +all: docs +docs: coredocs otherdocs ################################################################# # Production Targets -- USE THESE TARGETS WHEN: @@ -1178,9 +1184,9 @@ $(TRACING_PACKAGES_FILE): $(DIRECTORY_CACHE) $(call PackageDependencies,$(TRACIN # # Get a cache of all the directories -$(DIRECTORY_CACHE): $(ALL_SOURCE_DIRS) +$(DIRECTORY_CACHE): $(ALL_EXISTING_SOURCE_DIRS) $(prep-target) - @for cp in $(ALL_SOURCE_DIRS) ; do \ + @for cp in $(ALL_EXISTING_SOURCE_DIRS) ; do \ $(ECHO) "$(FIND) $${cp} -type f >> $@"; \ $(FIND) $${cp} -type f >> $@; \ done diff --git a/jdk/make/java/nio/mapfile-linux b/jdk/make/java/nio/mapfile-linux index 028e4150d50..13cc1cd01ec 100644 --- a/jdk/make/java/nio/mapfile-linux +++ b/jdk/make/java/nio/mapfile-linux @@ -119,6 +119,7 @@ SUNWprivate_1.1 { Java_sun_nio_ch_ServerSocketChannelImpl_accept0; Java_sun_nio_ch_ServerSocketChannelImpl_initIDs; Java_sun_nio_ch_SocketChannelImpl_checkConnect; + Java_sun_nio_ch_SocketChannelImpl_sendOutOfBandData; Java_sun_nio_ch_UnixAsynchronousServerSocketChannelImpl_accept0; Java_sun_nio_ch_UnixAsynchronousServerSocketChannelImpl_initIDs; Java_sun_nio_ch_UnixAsynchronousSocketChannelImpl_checkConnect; diff --git a/jdk/make/java/nio/mapfile-solaris b/jdk/make/java/nio/mapfile-solaris index 11a74f36713..2b80e4e801e 100644 --- a/jdk/make/java/nio/mapfile-solaris +++ b/jdk/make/java/nio/mapfile-solaris @@ -106,6 +106,7 @@ SUNWprivate_1.1 { Java_sun_nio_ch_ServerSocketChannelImpl_accept0; Java_sun_nio_ch_ServerSocketChannelImpl_initIDs; Java_sun_nio_ch_SocketChannelImpl_checkConnect; + Java_sun_nio_ch_SocketChannelImpl_sendOutOfBandData; Java_sun_nio_ch_UnixAsynchronousServerSocketChannelImpl_accept0; Java_sun_nio_ch_UnixAsynchronousServerSocketChannelImpl_initIDs; Java_sun_nio_ch_UnixAsynchronousSocketChannelImpl_checkConnect; diff --git a/jdk/make/sun/nio/cs/Makefile b/jdk/make/sun/nio/cs/Makefile index 26437efca82..e1b4d8d7be5 100644 --- a/jdk/make/sun/nio/cs/Makefile +++ b/jdk/make/sun/nio/cs/Makefile @@ -57,6 +57,25 @@ CHARSETS_JAR = $(LIBDIR)/charsets.jar # extcs FILES_genout_extcs = $(FILES_gen_extcs:%.java=$(GENSRCDIR)/%.java) +# +# These sun.awt charsets use sun/nio/cs/ext charsets that only exist +# in JDK7 charsets.jar, which causes problem when build the symbol +# table for rt.jar in Release.gmk. They are now removed from the +# rt.jar when building jdk/jre image (in Release.gmk), so add them +# into charsets.jar here +# +ifeq ($(PLATFORM), windows) +FILES_src += \ + sun/awt/HKSCS.java +else +# Solaris/Linux +FILES_src += \ + sun/awt/HKSCS.java \ + sun/awt/motif/X11GB2312.java \ + sun/awt/motif/X11GBK.java \ + sun/awt/motif/X11KSC5601.java +endif # PLATFORM + # # Rules # diff --git a/jdk/src/share/classes/com/sun/jndi/dns/DnsContextFactory.java b/jdk/src/share/classes/com/sun/jndi/dns/DnsContextFactory.java index c7a15dc6eec..c006ebdb5b9 100644 --- a/jdk/src/share/classes/com/sun/jndi/dns/DnsContextFactory.java +++ b/jdk/src/share/classes/com/sun/jndi/dns/DnsContextFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -132,7 +132,7 @@ public class DnsContextFactory implements InitialContextFactory { throw new ConfigurationException("DNS pseudo-URL required"); } - List servers = new ArrayList(); + List servers = new ArrayList<>(); for (int i = 0; i < urls.length; i++) { String server = urls[i].getHost(); @@ -142,7 +142,7 @@ public class DnsContextFactory implements InitialContextFactory { // No server or port given, so look to underlying platform. // ResolverConfiguration does some limited caching, so the // following is reasonably efficient even if called rapid-fire. - List platformServers = + List platformServers = ResolverConfiguration.open().nameservers(); if (!platformServers.isEmpty()) { servers.addAll(platformServers); @@ -157,8 +157,7 @@ public class DnsContextFactory implements InitialContextFactory { ? server : server + ":" + port); } - return (String[]) servers.toArray( - new String[servers.size()]); + return servers.toArray(new String[servers.size()]); } /* diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java b/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java index 77890393387..4503d261fff 100644 --- a/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java +++ b/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -658,6 +658,11 @@ public final class Connection implements Runnable { } } if (nparent) { + LdapRequest ldr = pendingRequests; + while (ldr != null) { + ldr.notify(); + ldr = ldr.next; + } parent.processConnectionClosure(); } } diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/Filter.java b/jdk/src/share/classes/com/sun/jndi/ldap/Filter.java index b40bdcf6595..626f1f86f95 100644 --- a/jdk/src/share/classes/com/sun/jndi/ldap/Filter.java +++ b/jdk/src/share/classes/com/sun/jndi/ldap/Filter.java @@ -803,8 +803,7 @@ final class Filter { // //////////////////////////////////////////////////////////////////////////// - // private static final boolean dbg = false; - private static final boolean dbg = true; + private static final boolean dbg = false; private static int dbgIndent = 0; private static void dprint(String msg) { diff --git a/jdk/src/share/classes/com/sun/jndi/rmi/registry/RegistryContext.java b/jdk/src/share/classes/com/sun/jndi/rmi/registry/RegistryContext.java index 07173c1028c..4e34eec6229 100644 --- a/jdk/src/share/classes/com/sun/jndi/rmi/registry/RegistryContext.java +++ b/jdk/src/share/classes/com/sun/jndi/rmi/registry/RegistryContext.java @@ -81,7 +81,7 @@ public class RegistryContext implements Context, Referenceable { } RMIClientSocketFactory socketFactory = - (RMIClientSocketFactory) env.get(SOCKET_FACTORY); + (RMIClientSocketFactory) environment.get(SOCKET_FACTORY); registry = getRegistry(host, port, socketFactory); this.host = host; this.port = port; diff --git a/jdk/src/share/classes/com/sun/tools/example/debug/tty/TTYResources.java b/jdk/src/share/classes/com/sun/tools/example/debug/tty/TTYResources.java index 6998ed90b39..2c5e12d5eb8 100644 --- a/jdk/src/share/classes/com/sun/tools/example/debug/tty/TTYResources.java +++ b/jdk/src/share/classes/com/sun/tools/example/debug/tty/TTYResources.java @@ -45,7 +45,7 @@ public class TTYResources extends java.util.ListResourceBundle { * @return the contents of this ResourceBundle. */ public Object[][] getContents() { - return new Object[][] { + Object[][] temp = new Object[][] { // NOTE: The value strings in this file containing "{0}" are // processed by the java.text.MessageFormat class. Any // single quotes appearing in these strings need to be @@ -449,5 +449,7 @@ public class TTYResources extends java.util.ListResourceBundle { "For command help type ''help'' at {0} prompt"}, // END OF MATERIAL TO LOCALIZE }; + + return temp; } } diff --git a/jdk/src/share/classes/java/lang/AutoCloseable.java b/jdk/src/share/classes/java/lang/AutoCloseable.java index 0f7ed8e0dd6..18c28fe887b 100644 --- a/jdk/src/share/classes/java/lang/AutoCloseable.java +++ b/jdk/src/share/classes/java/lang/AutoCloseable.java @@ -41,6 +41,13 @@ public interface AutoCloseable { * be declared to throw more specific exceptions (or no exception * at all, if the close cannot fail). * + *

Note that unlike the {@link java.io.Closeable#close close} + * method of {@link java.io.Closeable}, this {@code close} method + * is not required to be idempotent. In other words, + * calling this {@code close} method more than once may have some + * visible side effect, unlike {@code Closeable.close} which is + * required to have no effect if called more than once. + * * @throws Exception if this resource cannot be closed */ void close() throws Exception; diff --git a/jdk/src/share/classes/java/lang/Throwable.java b/jdk/src/share/classes/java/lang/Throwable.java index 58478f90af4..213f5f86d5c 100644 --- a/jdk/src/share/classes/java/lang/Throwable.java +++ b/jdk/src/share/classes/java/lang/Throwable.java @@ -28,12 +28,12 @@ import java.io.*; import java.util.*; /** - * The Throwable class is the superclass of all errors and + * The {@code Throwable} class is the superclass of all errors and * exceptions in the Java language. Only objects that are instances of this * class (or one of its subclasses) are thrown by the Java Virtual Machine or - * can be thrown by the Java throw statement. Similarly, only + * can be thrown by the Java {@code throw} statement. Similarly, only * this class or one of its subclasses can be the argument type in a - * catch clause. + * {@code catch} clause. * * For the purposes of compile-time checking of exceptions, {@code * Throwable} and any subclass of {@code Throwable} that is not also a @@ -73,11 +73,11 @@ import java.util.*; * permit the method to throw the cause directly. For example, suppose * a persistent collection conforms to the {@link java.util.Collection * Collection} interface, and that its persistence is implemented atop - * java.io. Suppose the internals of the add method + * {@code java.io}. Suppose the internals of the {@code add} method * can throw an {@link java.io.IOException IOException}. The implementation - * can communicate the details of the IOException to its caller - * while conforming to the Collection interface by wrapping the - * IOException in an appropriate unchecked exception. (The + * can communicate the details of the {@code IOException} to its caller + * while conforming to the {@code Collection} interface by wrapping the + * {@code IOException} in an appropriate unchecked exception. (The * specification for the persistent collection should indicate that it is * capable of throwing such exceptions.) * @@ -86,7 +86,7 @@ import java.util.*; * {@link #initCause(Throwable)} method. New throwable classes that * wish to allow causes to be associated with them should provide constructors * that take a cause and delegate (perhaps indirectly) to one of the - * Throwable constructors that takes a cause. For example: + * {@code Throwable} constructors that takes a cause. For example: *

  *     try {
  *         lowLevelOp();
@@ -94,10 +94,10 @@ import  java.util.*;
  *         throw new HighLevelException(le);  // Chaining-aware constructor
  *     }
  * 
- * Because the initCause method is public, it allows a cause to be + * Because the {@code initCause} method is public, it allows a cause to be * associated with any throwable, even a "legacy throwable" whose * implementation predates the addition of the exception chaining mechanism to - * Throwable. For example: + * {@code Throwable}. For example: *
  *     try {
  *         lowLevelOp();
@@ -121,28 +121,28 @@ import  java.util.*;
  * use the standard exception chaining mechanism, while continuing to
  * implement their "legacy" chaining mechanisms for compatibility.
  *
- * 

Further, as of release 1.4, many general purpose Throwable + *

Further, as of release 1.4, many general purpose {@code Throwable} * classes (for example {@link Exception}, {@link RuntimeException}, * {@link Error}) have been retrofitted with constructors that take * a cause. This was not strictly necessary, due to the existence of the - * initCause method, but it is more convenient and expressive to + * {@code initCause} method, but it is more convenient and expressive to * delegate to a constructor that takes a cause. * - *

By convention, class Throwable and its subclasses have two + *

By convention, class {@code Throwable} and its subclasses have two * constructors, one that takes no arguments and one that takes a - * String argument that can be used to produce a detail message. + * {@code String} argument that can be used to produce a detail message. * Further, those subclasses that might likely have a cause associated with * them should have two more constructors, one that takes a - * Throwable (the cause), and one that takes a - * String (the detail message) and a Throwable (the + * {@code Throwable} (the cause), and one that takes a + * {@code String} (the detail message) and a {@code Throwable} (the * cause). * *

Also introduced in release 1.4 is the {@link #getStackTrace()} method, * which allows programmatic access to the stack trace information that was * previously available only in text form, via the various forms of the * {@link #printStackTrace()} method. This information has been added to the - * serialized representation of this class so getStackTrace - * and printStackTrace will operate properly on a throwable that + * serialized representation of this class so {@code getStackTrace} + * and {@code printStackTrace} will operate properly on a throwable that * was obtained by deserialization. * * @author unascribed @@ -162,7 +162,7 @@ public class Throwable implements Serializable { /** * Specific details about the Throwable. For example, for - * FileNotFoundException, this contains the name of + * {@code FileNotFoundException}, this contains the name of * the file that could not be found. * * @serial @@ -212,7 +212,7 @@ public class Throwable implements Serializable { private static final String SUPPRESSED_CAPTION = "Suppressed: "; /** - * Constructs a new throwable with null as its detail message. + * Constructs a new throwable with {@code null} as its detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. * @@ -242,7 +242,7 @@ public class Throwable implements Serializable { /** * Constructs a new throwable with the specified detail message and * cause.

Note that the detail message associated with - * cause is not automatically incorporated in + * {@code cause} is not automatically incorporated in * this throwable's detail message. * *

The {@link #fillInStackTrace()} method is called to initialize @@ -251,7 +251,7 @@ public class Throwable implements Serializable { * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is + * {@link #getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 @@ -264,8 +264,8 @@ public class Throwable implements Serializable { /** * Constructs a new throwable with the specified cause and a detail - * message of (cause==null ? null : cause.toString()) (which - * typically contains the class and detail message of cause). + * message of {@code (cause==null ? null : cause.toString())} (which + * typically contains the class and detail message of {@code cause}). * This constructor is useful for throwables that are little more than * wrappers for other throwables (for example, {@link * java.security.PrivilegedActionException}). @@ -274,7 +274,7 @@ public class Throwable implements Serializable { * the stack trace data in the newly created throwable. * * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is + * {@link #getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 @@ -288,8 +288,8 @@ public class Throwable implements Serializable { /** * Returns the detail message string of this throwable. * - * @return the detail message string of this Throwable instance - * (which may be null). + * @return the detail message string of this {@code Throwable} instance + * (which may be {@code null}). */ public String getMessage() { return detailMessage; @@ -300,7 +300,7 @@ public class Throwable implements Serializable { * Subclasses may override this method in order to produce a * locale-specific message. For subclasses that do not override this * method, the default implementation returns the same result as - * getMessage(). + * {@code getMessage()}. * * @return The localized description of this throwable. * @since JDK1.1 @@ -310,22 +310,22 @@ public class Throwable implements Serializable { } /** - * Returns the cause of this throwable or null if the + * Returns the cause of this throwable or {@code null} if the * cause is nonexistent or unknown. (The cause is the throwable that * caused this throwable to get thrown.) * *

This implementation returns the cause that was supplied via one of - * the constructors requiring a Throwable, or that was set after + * the constructors requiring a {@code Throwable}, or that was set after * creation with the {@link #initCause(Throwable)} method. While it is * typically unnecessary to override this method, a subclass can override * it to return a cause set by some other means. This is appropriate for * a "legacy chained throwable" that predates the addition of chained - * exceptions to Throwable. Note that it is not - * necessary to override any of the PrintStackTrace methods, - * all of which invoke the getCause method to determine the + * exceptions to {@code Throwable}. Note that it is not + * necessary to override any of the {@code PrintStackTrace} methods, + * all of which invoke the {@code getCause} method to determine the * cause of a throwable. * - * @return the cause of this throwable or null if the + * @return the cause of this throwable or {@code null} if the * cause is nonexistent or unknown. * @since 1.4 */ @@ -345,11 +345,11 @@ public class Throwable implements Serializable { * even once. * * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is + * {@link #getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or * unknown.) - * @return a reference to this Throwable instance. - * @throws IllegalArgumentException if cause is this + * @return a reference to this {@code Throwable} instance. + * @throws IllegalArgumentException if {@code cause} is this * throwable. (A throwable cannot be its own cause.) * @throws IllegalStateException if this throwable was * created with {@link #Throwable(Throwable)} or @@ -375,7 +375,7 @@ public class Throwable implements Serializable { *

  • the result of invoking this object's {@link #getLocalizedMessage} * method * - * If getLocalizedMessage returns null, then just + * If {@code getLocalizedMessage} returns {@code null}, then just * the class name is returned. * * @return a string representation of this throwable. @@ -389,8 +389,8 @@ public class Throwable implements Serializable { /** * Prints this throwable and its backtrace to the * standard error stream. This method prints a stack trace for this - * Throwable object on the error output stream that is - * the value of the field System.err. The first line of + * {@code Throwable} object on the error output stream that is + * the value of the field {@code System.err}. The first line of * output contains the result of the {@link #toString()} method for * this object. Remaining lines represent data previously recorded by * the method {@link #fillInStackTrace()}. The format of this @@ -435,7 +435,7 @@ public class Throwable implements Serializable { * at Junk.c(Junk.java:21) * ... 3 more *
  • - * Note the presence of lines containing the characters "...". + * Note the presence of lines containing the characters {@code "..."}. * These lines indicate that the remainder of the stack trace for this * exception matches the indicated number of frames from the bottom of the * stack trace of the exception that was caused by this exception (the @@ -542,14 +542,17 @@ public class Throwable implements Serializable { /** * Prints this throwable and its backtrace to the specified print stream. * - * @param s PrintStream to use for output + * @param s {@code PrintStream} to use for output */ public void printStackTrace(PrintStream s) { printStackTrace(new WrappedPrintStream(s)); } private void printStackTrace(PrintStreamOrWriter s) { - Set dejaVu = new HashSet(); + // Guard against malicious overrides of Throwable.equals by + // using a Set with identity equality semantics. + Set dejaVu = + Collections.newSetFromMap(new IdentityHashMap()); dejaVu.add(this); synchronized (s.lock()) { @@ -616,7 +619,7 @@ public class Throwable implements Serializable { * Prints this throwable and its backtrace to the specified * print writer. * - * @param s PrintWriter to use for output + * @param s {@code PrintWriter} to use for output * @since JDK1.1 */ public void printStackTrace(PrintWriter s) { @@ -669,10 +672,10 @@ public class Throwable implements Serializable { /** * Fills in the execution stack trace. This method records within this - * Throwable object information about the current state of + * {@code Throwable} object information about the current state of * the stack frames for the current thread. * - * @return a reference to this Throwable instance. + * @return a reference to this {@code Throwable} instance. * @see java.lang.Throwable#printStackTrace() */ public synchronized native Throwable fillInStackTrace(); @@ -694,7 +697,7 @@ public class Throwable implements Serializable { * this throwable is permitted to return a zero-length array from this * method. Generally speaking, the array returned by this method will * contain one element for every frame that would be printed by - * printStackTrace. + * {@code printStackTrace}. * * @return an array of stack trace elements representing the stack trace * pertaining to this throwable. @@ -727,14 +730,14 @@ public class Throwable implements Serializable { * read from a serialization stream. * * @param stackTrace the stack trace elements to be associated with - * this Throwable. The specified array is copied by this + * this {@code Throwable}. The specified array is copied by this * call; changes in the specified array after the method invocation - * returns will have no affect on this Throwable's stack + * returns will have no affect on this {@code Throwable}'s stack * trace. * - * @throws NullPointerException if stackTrace is - * null, or if any of the elements of - * stackTrace are null + * @throws NullPointerException if {@code stackTrace} is + * {@code null}, or if any of the elements of + * {@code stackTrace} are {@code null} * * @since 1.4 */ @@ -761,8 +764,8 @@ public class Throwable implements Serializable { * package-protection for use by SharedSecrets. * * @param index index of the element to return. - * @throws IndexOutOfBoundsException if index < 0 || - * index >= getStackTraceDepth() + * @throws IndexOutOfBoundsException if {@code index < 0 || + * index >= getStackTraceDepth() } */ native StackTraceElement getStackTraceElement(int index); @@ -794,14 +797,27 @@ public class Throwable implements Serializable { * were suppressed, typically by the automatic resource management * statement, in order to deliver this exception. * + *

    Note that when one exception {@linkplain + * #initCause(Throwable) causes} another exception, the first + * exception is usually caught and then the second exception is + * thrown in response. In contrast, when one exception suppresses + * another, two exceptions are thrown in sibling code blocks, such + * as in a {@code try} block and in its {@code finally} block, and + * control flow can only continue with one exception so the second + * is recorded as a suppressed exception of the first. + * * @param exception the exception to be added to the list of * suppressed exceptions * @throws NullPointerException if {@code exception} is null + * @throws IllegalArgumentException if {@code exception} is this + * throwable; a throwable cannot suppress itself. * @since 1.7 */ public synchronized void addSuppressedException(Throwable exception) { if (exception == null) throw new NullPointerException(NULL_CAUSE_MESSAGE); + if (exception == this) + throw new IllegalArgumentException("Self-suppression not permitted"); if (suppressedExceptions.size() == 0) suppressedExceptions = new ArrayList(); diff --git a/jdk/src/share/classes/java/nio/Bits.java b/jdk/src/share/classes/java/nio/Bits.java index 4adf3e48066..fa11b6be785 100644 --- a/jdk/src/share/classes/java/nio/Bits.java +++ b/jdk/src/share/classes/java/nio/Bits.java @@ -596,6 +596,9 @@ class Bits { // package-private return pageSize; } + static int pageCount(long size) { + return (int)(size + (long)pageSize() - 1L) / pageSize(); + } private static boolean unaligned; private static boolean unalignedKnown = false; diff --git a/jdk/src/share/classes/java/nio/MappedByteBuffer.java b/jdk/src/share/classes/java/nio/MappedByteBuffer.java index 7e415c67bca..4811f41d2e1 100644 --- a/jdk/src/share/classes/java/nio/MappedByteBuffer.java +++ b/jdk/src/share/classes/java/nio/MappedByteBuffer.java @@ -25,6 +25,8 @@ package java.nio; +import sun.misc.Unsafe; + /** * A direct byte buffer whose content is a memory-mapped region of a file. @@ -93,6 +95,22 @@ public abstract class MappedByteBuffer throw new UnsupportedOperationException(); } + // Returns the distance (in bytes) of the buffer from the page aligned address + // of the mapping. Computed each time to avoid storing in every direct buffer. + private long mappingOffset() { + int ps = Bits.pageSize(); + long offset = address % ps; + return (offset >= 0) ? offset : (ps + offset); + } + + private long mappingAddress(long mappingOffset) { + return address - mappingOffset; + } + + private long mappingLength(long mappingOffset) { + return (long)capacity() + mappingOffset; + } + /** * Tells whether or not this buffer's content is resident in physical * memory. @@ -115,7 +133,9 @@ public abstract class MappedByteBuffer checkMapped(); if ((address == 0) || (capacity() == 0)) return true; - return isLoaded0(((DirectByteBuffer)this).address(), capacity()); + long offset = mappingOffset(); + long length = mappingLength(offset); + return isLoaded0(mappingAddress(offset), length, Bits.pageCount(length)); } /** @@ -132,7 +152,20 @@ public abstract class MappedByteBuffer checkMapped(); if ((address == 0) || (capacity() == 0)) return this; - load0(((DirectByteBuffer)this).address(), capacity(), Bits.pageSize()); + long offset = mappingOffset(); + long length = mappingLength(offset); + load0(mappingAddress(offset), length); + + // touch each page + Unsafe unsafe = Unsafe.getUnsafe(); + int ps = Bits.pageSize(); + int count = Bits.pageCount(length); + long a = mappingAddress(offset); + for (int i=0; i * signatureAlgorithm AlgorithmIdentifier

    diff --git a/jdk/src/share/classes/java/security/cert/X509Certificate.java b/jdk/src/share/classes/java/security/cert/X509Certificate.java index 8ca8c5d4d66..cb0e5482433 100644 --- a/jdk/src/share/classes/java/security/cert/X509Certificate.java +++ b/jdk/src/share/classes/java/security/cert/X509Certificate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -352,7 +352,7 @@ implements X509Extension { /** * Gets the signature algorithm name for the certificate - * signature algorithm. An example is the string "SHA-1/DSA". + * signature algorithm. An example is the string "SHA256withRSA". * The ASN.1 definition for this is: *

          * signatureAlgorithm   AlgorithmIdentifier

    diff --git a/jdk/src/share/classes/java/util/LinkedList.java b/jdk/src/share/classes/java/util/LinkedList.java index 34685d91ca7..9feb95e54ff 100644 --- a/jdk/src/share/classes/java/util/LinkedList.java +++ b/jdk/src/share/classes/java/util/LinkedList.java @@ -26,18 +26,9 @@ package java.util; /** - * Linked list implementation of the {@code List} interface. Implements all - * optional list operations, and permits all elements (including - * {@code null}). In addition to implementing the {@code List} interface, - * the {@code LinkedList} class provides uniformly named methods to - * {@code get}, {@code remove} and {@code insert} an element at the - * beginning and end of the list. These operations allow linked lists to be - * used as a stack, {@linkplain Queue queue}, or {@linkplain Deque - * double-ended queue}. - * - *

    The class implements the {@code Deque} interface, providing - * first-in-first-out queue operations for {@code add}, - * {@code poll}, along with other stack and deque operations. + * Linked list implementation of the {@link List} and {@link Deque} interfaces. + * Implements all optional operations, and permits all elements (including + * {@code null}). * *

    All of the operations perform as could be expected for a doubly-linked * list. Operations that index into the list will traverse the list from diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java index acd141c1c4a..f8c163d5d2d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicColorChooserUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -113,7 +113,6 @@ public class BasicColorChooserUI extends ColorChooserUI previewPanelHolder.setBorder(new TitledBorder(previewString)); } previewPanelHolder.setInheritsPopupMenu(true); - chooser.add(previewPanelHolder, BorderLayout.SOUTH); installPreviewPanel(); chooser.applyComponentOrientation(c.getComponentOrientation()); @@ -126,13 +125,9 @@ public class BasicColorChooserUI extends ColorChooserUI uninstallDefaultChoosers(); uninstallListeners(); + uninstallPreviewPanel(); uninstallDefaults(); - previewPanelHolder.remove(previewPanel); - if (previewPanel instanceof UIResource) { - chooser.setPreviewPanel(null); - } - previewPanelHolder = null; previewPanel = null; defaultChoosers = null; @@ -143,29 +138,37 @@ public class BasicColorChooserUI extends ColorChooserUI } protected void installPreviewPanel() { - if (previewPanel != null) { - previewPanelHolder.remove(previewPanel); - previewPanel.removeMouseListener(getHandler()); + JComponent previewPanel = this.chooser.getPreviewPanel(); + if (previewPanel == null) { + previewPanel = ColorChooserComponentFactory.getPreviewPanel(); } - - previewPanel = chooser.getPreviewPanel(); - Dimension layoutSize = new Dimension(); // fix for bug 4759306 - if (previewPanel != null) { - layoutSize = new BorderLayout().minimumLayoutSize(previewPanel); - if ((previewPanelHolder != null) && (chooser != null) && - (layoutSize.getWidth() + layoutSize.getHeight() == 0)) { - chooser.remove(previewPanelHolder); - return; + else { + Dimension size = new BorderLayout().minimumLayoutSize(previewPanel); + if ((size.width == 0) && (size.height == 0)) { + previewPanel = null; } } - if (previewPanel == null || previewPanel instanceof UIResource) { - previewPanel = ColorChooserComponentFactory.getPreviewPanel(); // get from table? - chooser.setPreviewPanel(previewPanel); + this.previewPanel = previewPanel; + if (previewPanel != null) { + chooser.add(previewPanelHolder, BorderLayout.SOUTH); + previewPanel.setForeground(chooser.getColor()); + previewPanelHolder.add(previewPanel); + previewPanel.addMouseListener(getHandler()); + previewPanel.setInheritsPopupMenu(true); } - previewPanel.setForeground(chooser.getColor()); - previewPanelHolder.add(previewPanel); - previewPanel.addMouseListener(getHandler()); - previewPanel.setInheritsPopupMenu(true); + } + + /** + * Removes installed preview panel from the UI delegate. + * + * @since 1.7 + */ + protected void uninstallPreviewPanel() { + if (this.previewPanel != null) { + this.previewPanel.removeMouseListener(getHandler()); + this.previewPanelHolder.remove(this.previewPanel); + } + this.chooser.remove(this.previewPanelHolder); } protected void installDefaults() { @@ -209,7 +212,6 @@ public class BasicColorChooserUI extends ColorChooserUI chooser.removePropertyChangeListener( propertyChangeListener ); chooser.getSelectionModel().removeChangeListener(previewListener); previewListener = null; - previewPanel.removeMouseListener(getHandler()); } private void selectionChanged(ColorSelectionModel model) { @@ -312,9 +314,8 @@ public class BasicColorChooserUI extends ColorChooserUI } } else if (prop == JColorChooser.PREVIEW_PANEL_PROPERTY) { - if (evt.getNewValue() != previewPanel) { - installPreviewPanel(); - } + uninstallPreviewPanel(); + installPreviewPanel(); } else if (prop == JColorChooser.SELECTION_MODEL_PROPERTY) { ColorSelectionModel oldModel = (ColorSelectionModel) evt.getOldValue(); @@ -352,5 +353,4 @@ public class BasicColorChooserUI extends ColorChooserUI super("color"); } } - } diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java index 077c15b9d4a..803e4d01bda 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java @@ -202,8 +202,8 @@ public class BasicComboPopup extends JPopupMenu implements ComboPopup { * Implementation of ComboPopup.show(). */ public void show() { + comboBox.firePopupMenuWillBecomeVisible(); setListSelection(comboBox.getSelectedIndex()); - Point location = getPopupLocation(); show( comboBox, location.x, location.y ); } @@ -344,7 +344,8 @@ public class BasicComboPopup extends JPopupMenu implements ComboPopup { protected void firePopupMenuWillBecomeVisible() { super.firePopupMenuWillBecomeVisible(); - comboBox.firePopupMenuWillBecomeVisible(); + // comboBox.firePopupMenuWillBecomeVisible() is called from BasicComboPopup.show() method + // to let the user change the popup menu from the PopupMenuListener.popupMenuWillBecomeVisible() } protected void firePopupMenuWillBecomeInvisible() { diff --git a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java index d6e47c5fdf9..75c3481678e 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java @@ -570,7 +570,9 @@ public class DefaultFormatter extends JFormattedTextField.AbstractFormatter direction = -1; } - if (getOverwriteMode() && rh.text != null) { + if (getOverwriteMode() && rh.text != null && + getFormattedTextField().getSelectedText() == null) + { rh.length = Math.min(Math.max(rh.length, rh.text.length()), rh.fb.getDocument().getLength() - rh.offset); } diff --git a/jdk/src/share/classes/javax/swing/text/InternationalFormatter.java b/jdk/src/share/classes/javax/swing/text/InternationalFormatter.java index c511b20e281..b49fed2e3ce 100644 --- a/jdk/src/share/classes/javax/swing/text/InternationalFormatter.java +++ b/jdk/src/share/classes/javax/swing/text/InternationalFormatter.java @@ -622,18 +622,8 @@ public class InternationalFormatter extends DefaultFormatter { /** * Overriden in an attempt to honor the literals. - *

    - * If we do - * not allow invalid values and are in overwrite mode, this does the - * following for each character in the replacement range: - *

      - *
    1. If the character is a literal, add it to the string to replace - * with. If there is text to insert and it doesn't match the - * literal, then insert the literal in the the middle of the insert - * text. This allows you to either paste in literals or not and - * get the same behavior. - *
    2. If there is no text to insert, replace it with ' '. - *
    + *

    If we do not allow invalid values and are in overwrite mode, this + * {@code rh.length} is corrected as to preserve trailing literals. * If not in overwrite mode, and there is text to insert it is * inserted at the next non literal index going forward. If there * is only text to remove, it is removed from the next non literal @@ -643,61 +633,27 @@ public class InternationalFormatter extends DefaultFormatter { if (!getAllowsInvalid()) { String text = rh.text; int tl = (text != null) ? text.length() : 0; + JTextComponent c = getFormattedTextField(); - if (tl == 0 && rh.length == 1 && getFormattedTextField(). - getSelectionStart() != rh.offset) { + if (tl == 0 && rh.length == 1 && c.getSelectionStart() != rh.offset) { // Backspace, adjust to actually delete next non-literal. rh.offset = getNextNonliteralIndex(rh.offset, -1); - } - if (getOverwriteMode()) { - StringBuffer replace = null; + } else if (getOverwriteMode()) { + int pos = rh.offset; + int textPos = pos; + boolean overflown = false; - for (int counter = 0, textIndex = 0, - max = Math.max(tl, rh.length); counter < max; - counter++) { - if (isLiteral(rh.offset + counter)) { - if (replace != null) { - replace.append(getLiteral(rh.offset + - counter)); - } - if (textIndex < tl && text.charAt(textIndex) == - getLiteral(rh.offset + counter)) { - textIndex++; - } - else if (textIndex == 0) { - rh.offset++; - rh.length--; - counter--; - max--; - } - else if (replace == null) { - replace = new StringBuffer(max); - replace.append(text.substring(0, textIndex)); - replace.append(getLiteral(rh.offset + - counter)); - } - } - else if (textIndex < tl) { - if (replace != null) { - replace.append(text.charAt(textIndex)); - } - textIndex++; - } - else { - // Nothing to replace it with, assume ' ' - if (replace == null) { - replace = new StringBuffer(max); - if (textIndex > 0) { - replace.append(text.substring(0, textIndex)); - } - } - if (replace != null) { - replace.append(' '); - } + for (int i = 0; i < rh.length; i++) { + while (isLiteral(pos)) pos++; + if (pos >= string.length()) { + pos = textPos; + overflown = true; + break; } + textPos = ++pos; } - if (replace != null) { - rh.text = replace.toString(); + if (overflown || c.getSelectedText() == null) { + rh.length = pos - rh.offset; } } else if (tl > 0) { diff --git a/jdk/src/share/classes/sun/applet/resources/MsgAppletViewer.java b/jdk/src/share/classes/sun/applet/resources/MsgAppletViewer.java index fcf66e64c18..6c24c7f2946 100644 --- a/jdk/src/share/classes/sun/applet/resources/MsgAppletViewer.java +++ b/jdk/src/share/classes/sun/applet/resources/MsgAppletViewer.java @@ -29,7 +29,7 @@ import java.util.ListResourceBundle; public class MsgAppletViewer extends ListResourceBundle { public Object[][] getContents() { - return new Object[][] { + Object[][] temp = new Object[][] { {"textframe.button.dismiss", "Dismiss"}, {"appletviewer.tool.title", "Applet Viewer: {0}"}, {"appletviewer.menu.applet", "Applet"}, @@ -197,5 +197,7 @@ public class MsgAppletViewer extends ListResourceBundle { {"appletsecurityexception.checkread.unknown", "unknown class loader type. unable to check for checking read {0}"}, {"appletsecurityexception.checkconnect.unknown", "unknown class loader type. unable to check for checking connect"}, }; + + return temp; } } diff --git a/jdk/src/share/classes/sun/net/dns/ResolverConfiguration.java b/jdk/src/share/classes/sun/net/dns/ResolverConfiguration.java index e97d7fe0fe8..4ab30b2935d 100644 --- a/jdk/src/share/classes/sun/net/dns/ResolverConfiguration.java +++ b/jdk/src/share/classes/sun/net/dns/ResolverConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -26,7 +26,6 @@ package sun.net.dns; import java.util.List; -import java.io.IOException; /** * The configuration of the client resolver. @@ -68,7 +67,7 @@ public abstract class ResolverConfiguration { * * @return list of domain names */ - public abstract List searchlist(); + public abstract List searchlist(); /** * Returns a list of name servers used for host name lookup. @@ -78,7 +77,7 @@ public abstract class ResolverConfiguration { * * @return list of the name servers */ - public abstract List nameservers(); + public abstract List nameservers(); /** diff --git a/jdk/src/share/classes/sun/net/spi/nameservice/dns/DNSNameService.java b/jdk/src/share/classes/sun/net/spi/nameservice/dns/DNSNameService.java index bdc82ad6da2..9142de0a3c0 100644 --- a/jdk/src/share/classes/sun/net/spi/nameservice/dns/DNSNameService.java +++ b/jdk/src/share/classes/sun/net/spi/nameservice/dns/DNSNameService.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -45,20 +45,21 @@ import sun.security.action.*; public final class DNSNameService implements NameService { // List of domains specified by property - private LinkedList domainList = null; + private LinkedList domainList = null; // JNDI-DNS URL for name servers specified via property private String nameProviderUrl = null; // Per-thread soft cache of the last temporary context - private static ThreadLocal contextRef = new ThreadLocal(); + private static ThreadLocal> contextRef = + new ThreadLocal<>(); // Simple class to encapsulate the temporary context private static class ThreadContext { private DirContext dirCtxt; - private List nsList; + private List nsList; - public ThreadContext(DirContext dirCtxt, List nsList) { + public ThreadContext(DirContext dirCtxt, List nsList) { this.dirCtxt = dirCtxt; this.nsList = nsList; } @@ -67,16 +68,16 @@ public final class DNSNameService implements NameService { return dirCtxt; } - public List nameservers() { + public List nameservers() { return nsList; } } // Returns a per-thread DirContext private DirContext getTemporaryContext() throws NamingException { - SoftReference ref = (SoftReference)contextRef.get(); + SoftReference ref = contextRef.get(); ThreadContext thrCtxt = null; - List nsList = null; + List nsList = null; // if no property specified we need to obtain the list of servers // @@ -87,7 +88,7 @@ public final class DNSNameService implements NameService { // specified then we need to check if the DNS configuration // has changed. // - if ((ref != null) && ((thrCtxt = (ThreadContext)ref.get()) != null)) { + if ((ref != null) && ((thrCtxt = ref.get()) != null)) { if (nameProviderUrl == null) { if (!thrCtxt.nameservers().equals(nsList)) { // DNS configuration has changed @@ -98,7 +99,7 @@ public final class DNSNameService implements NameService { // new thread context needs to be created if (thrCtxt == null) { - final Hashtable env = new Hashtable(); + final Hashtable env = new Hashtable<>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); @@ -119,10 +120,9 @@ public final class DNSNameService implements NameService { // DirContext dirCtxt; try { - dirCtxt = (DirContext) - java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { - public Object run() throws NamingException { + dirCtxt = java.security.AccessController.doPrivileged( + new java.security.PrivilegedExceptionAction() { + public DirContext run() throws NamingException { // Create the DNS context using NamingManager rather than using // the initial context constructor. This avoids having the initial // context constructor call itself. @@ -130,7 +130,7 @@ public final class DNSNameService implements NameService { if (!(ctx instanceof DirContext)) { return null; // cannot create a DNS context } - return ctx; + return (DirContext)ctx; } }); } catch (java.security.PrivilegedActionException pae) { @@ -161,18 +161,18 @@ public final class DNSNameService implements NameService { * * @throws UnknownHostException if lookup fails or other error. */ - private ArrayList resolve(final DirContext ctx, final String name, final String[] ids, - int depth) throws UnknownHostException + private ArrayList resolve(final DirContext ctx, final String name, + final String[] ids, int depth) + throws UnknownHostException { - ArrayList results = new ArrayList(); + ArrayList results = new ArrayList<>(); Attributes attrs; // do the query try { - attrs = (Attributes) - java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { - public Object run() throws NamingException { + attrs = java.security.AccessController.doPrivileged( + new java.security.PrivilegedExceptionAction() { + public Attributes run() throws NamingException { return ctx.getAttributes(name, ids); } }); @@ -181,7 +181,7 @@ public final class DNSNameService implements NameService { } // non-requested type returned so enumeration is empty - NamingEnumeration ne = attrs.getAll(); + NamingEnumeration ne = attrs.getAll(); if (!ne.hasMoreElements()) { throw new UnknownHostException("DNS record not found"); } @@ -190,7 +190,7 @@ public final class DNSNameService implements NameService { UnknownHostException uhe = null; try { while (ne.hasMoreElements()) { - Attribute attr = (Attribute)ne.next(); + Attribute attr = ne.next(); String attrID = attr.getID(); for (NamingEnumeration e = attr.getAll(); e.hasMoreElements();) { @@ -251,13 +251,12 @@ public final class DNSNameService implements NameService { // no property specified so check host DNS resolver configured // with at least one nameserver in dotted notation. // - List nsList = ResolverConfiguration.open().nameservers(); - if (nsList.size() == 0) + List nsList = ResolverConfiguration.open().nameservers(); + if (nsList.isEmpty()) { throw new RuntimeException("no nameservers provided"); + } boolean found = false; - Iterator i = nsList.iterator(); - while (i.hasNext()) { - String addr = (String)i.next(); + for (String addr: nsList) { if (IPAddressUtil.isIPv4LiteralAddress(addr) || IPAddressUtil.isIPv6LiteralAddress(addr)) { found = true; @@ -308,8 +307,8 @@ public final class DNSNameService implements NameService { // suffix if the list has one entry. if (results == null) { - List searchList = null; - Iterator i; + List searchList = null; + Iterator i; boolean usingSearchList = false; if (domainList != null) { @@ -324,7 +323,7 @@ public final class DNSNameService implements NameService { // iterator through each domain suffix while (i.hasNext()) { - String parentDomain = (String)i.next(); + String parentDomain = i.next(); int start = 0; while ((start = parentDomain.indexOf(".")) != -1 && start < parentDomain.length() -1) { @@ -407,7 +406,7 @@ public final class DNSNameService implements NameService { String literalip = ""; String[] ids = { "PTR" }; DirContext ctx; - ArrayList results = null; + ArrayList results = null; try { ctx = getTemporaryContext(); } catch (NamingException nx) { @@ -420,7 +419,7 @@ public final class DNSNameService implements NameService { literalip += "IN-ADDR.ARPA."; results = resolve(ctx, literalip, ids, 0); - host = (String)results.get(0); + host = results.get(0); } else if (addr.length == 16) { // IPv6 Address /** * Because RFC 3152 changed the root domain name for reverse @@ -437,7 +436,7 @@ public final class DNSNameService implements NameService { try { results = resolve(ctx, ip6lit, ids, 0); - host = (String)results.get(0); + host = results.get(0); } catch (UnknownHostException e) { host = null; } @@ -445,7 +444,7 @@ public final class DNSNameService implements NameService { // IP6.ARPA lookup failed, let's try the older IP6.INT ip6lit = literalip + "IP6.INT."; results = resolve(ctx, ip6lit, ids, 0); - host = (String)results.get(0); + host = results.get(0); } } } catch (Exception e) { @@ -478,11 +477,10 @@ public final class DNSNameService implements NameService { * @return String containing the JNDI-DNS provider URL * corresponding to the supplied List of nameservers. */ - private static String createProviderURL(List nsList) { - Iterator i = nsList.iterator(); + private static String createProviderURL(List nsList) { StringBuffer sb = new StringBuffer(); - while (i.hasNext()) { - appendIfLiteralAddress((String)i.next(), sb); + for (String s: nsList) { + appendIfLiteralAddress(s, sb); } return sb.toString(); } diff --git a/jdk/src/share/classes/sun/nio/ch/SocketAdaptor.java b/jdk/src/share/classes/sun/nio/ch/SocketAdaptor.java index 583835727e8..7ff9a3075f9 100644 --- a/jdk/src/share/classes/sun/nio/ch/SocketAdaptor.java +++ b/jdk/src/share/classes/sun/nio/ch/SocketAdaptor.java @@ -336,7 +336,12 @@ public class SocketAdaptor } public void sendUrgentData(int data) throws IOException { - throw new SocketException("Urgent data not supported"); + synchronized (sc.blockingLock()) { + if (!sc.isBlocking()) + throw new IllegalBlockingModeException(); + int n = sc.sendOutOfBandData((byte)data); + assert n == 1; + } } public void setOOBInline(boolean on) throws SocketException { diff --git a/jdk/src/share/classes/sun/nio/ch/SocketChannelImpl.java b/jdk/src/share/classes/sun/nio/ch/SocketChannelImpl.java index 2539007afd1..ee84a0e626c 100644 --- a/jdk/src/share/classes/sun/nio/ch/SocketChannelImpl.java +++ b/jdk/src/share/classes/sun/nio/ch/SocketChannelImpl.java @@ -498,6 +498,36 @@ class SocketChannelImpl return write0(Util.subsequence(srcs, offset, length)); } + // package-private + int sendOutOfBandData(byte b) throws IOException { + synchronized (writeLock) { + ensureWriteOpen(); + int n = 0; + try { + begin(); + synchronized (stateLock) { + if (!isOpen()) + return 0; + writerThread = NativeThread.current(); + } + for (;;) { + n = sendOutOfBandData(fd, b); + if ((n == IOStatus.INTERRUPTED) && isOpen()) + continue; + return IOStatus.normalize(n); + } + } finally { + writerCleanup(); + end((n > 0) || (n == IOStatus.UNAVAILABLE)); + synchronized (stateLock) { + if ((n <= 0) && (!isOutputOpen)) + throw new AsynchronousCloseException(); + } + assert IOStatus.check(n); + } + } + } + protected void implConfigureBlocking(boolean block) throws IOException { IOUtil.configureBlocking(fd, block); } @@ -957,6 +987,9 @@ class SocketChannelImpl boolean block, boolean ready) throws IOException; + private static native int sendOutOfBandData(FileDescriptor fd, byte data) + throws IOException; + static { Util.load(); nd = new SocketDispatcher(); diff --git a/jdk/src/share/classes/sun/security/krb5/Config.java b/jdk/src/share/classes/sun/security/krb5/Config.java index c885869ff65..21fb4cea7f5 100644 --- a/jdk/src/share/classes/sun/security/krb5/Config.java +++ b/jdk/src/share/classes/sun/security/krb5/Config.java @@ -42,6 +42,8 @@ import java.util.Enumeration; import java.util.StringTokenizer; import java.net.InetAddress; import java.net.UnknownHostException; +import java.util.List; +import sun.net.dns.ResolverConfiguration; import sun.security.krb5.internal.crypto.EType; import sun.security.krb5.internal.ktab.*; import sun.security.krb5.internal.Krb5; @@ -1180,6 +1182,33 @@ public class Config { } // get the domain realm mapping from the configuration String mapRealm = PrincipalName.mapHostToRealm(hostName); + if (mapRealm == null) { + // No match. Try search and/or domain in /etc/resolv.conf + List srchlist = ResolverConfiguration.open().searchlist(); + for (String domain: srchlist) { + realm = checkRealm(domain); + if (realm != null) { + break; + } + } + } else { + realm = checkRealm(mapRealm); + } + if (realm == null) { + throw new KrbException(Krb5.KRB_ERR_GENERIC, + "Unable to locate Kerberos realm"); + } + return realm; + } + + /** + * Check if the provided realm is the correct realm + * @return the realm if correct, or null otherwise + */ + private static String checkRealm(String mapRealm) { + if (DEBUG) { + System.out.println("getRealmFromDNS: trying " + mapRealm); + } String[] records = null; String newRealm = mapRealm; while ((records == null) && (newRealm != null)) { @@ -1188,23 +1217,14 @@ public class Config { newRealm = Realm.parseRealmComponent(newRealm); // if no DNS TXT records found, try again using sub-realm } - if (records == null) { - // no DNS TXT records - throw new KrbException(Krb5.KRB_ERR_GENERIC, - "Unable to locate Kerberos realm"); - } - boolean found = false; - for (int i = 0; i < records.length; i++) { - if (records[i].equals(mapRealm)) { - found = true; - realm = records[i]; + if (records != null) { + for (int i = 0; i < records.length; i++) { + if (records[i].equalsIgnoreCase(mapRealm)) { + return records[i]; + } } } - if (found == false) { - throw new KrbException(Krb5.KRB_ERR_GENERIC, - "Unable to locate Kerberos realm"); - } - return realm; + return null; } /** @@ -1218,10 +1238,16 @@ public class Config { String kdcs = null; String[] srvs = null; // locate DNS SRV record using UDP - srvs = KrbServiceLocator.getKerberosService(realm, "_udp."); + if (DEBUG) { + System.out.println("getKDCFromDNS using UDP"); + } + srvs = KrbServiceLocator.getKerberosService(realm, "_udp"); if (srvs == null) { // locate DNS SRV record using TCP - srvs = KrbServiceLocator.getKerberosService(realm, "_tcp."); + if (DEBUG) { + System.out.println("getKDCFromDNS using UDP"); + } + srvs = KrbServiceLocator.getKerberosService(realm, "_tcp"); } if (srvs == null) { // no DNS SRV records diff --git a/jdk/src/share/classes/sun/security/krb5/Credentials.java b/jdk/src/share/classes/sun/security/krb5/Credentials.java index b7ae4aaee65..6896aa18e95 100644 --- a/jdk/src/share/classes/sun/security/krb5/Credentials.java +++ b/jdk/src/share/classes/sun/security/krb5/Credentials.java @@ -36,6 +36,7 @@ import sun.security.krb5.internal.ccache.CredentialsCache; import sun.security.krb5.internal.crypto.EType; import java.io.IOException; import java.util.Date; +import java.util.Locale; import java.net.InetAddress; /** @@ -287,7 +288,7 @@ public class Credentials { // The default ticket cache on Windows is not a file. String os = java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction("os.name")); - if (os.toUpperCase().startsWith("WINDOWS")) { + if (os.toUpperCase(Locale.ENGLISH).startsWith("WINDOWS")) { Credentials creds = acquireDefaultCreds(); if (creds == null) { if (DEBUG) { diff --git a/jdk/src/share/classes/sun/security/pkcs/PKCS9Attribute.java b/jdk/src/share/classes/sun/security/pkcs/PKCS9Attribute.java index 05b61eb0c32..fb1862f6adb 100644 --- a/jdk/src/share/classes/sun/security/pkcs/PKCS9Attribute.java +++ b/jdk/src/share/classes/sun/security/pkcs/PKCS9Attribute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -28,6 +28,7 @@ package sun.security.pkcs; import java.io.IOException; import java.io.OutputStream; import java.security.cert.CertificateException; +import java.util.Locale; import java.util.Date; import java.util.Hashtable; import sun.security.x509.CertificateExtensions; @@ -742,7 +743,7 @@ public class PKCS9Attribute implements DerEncoder { * the name. */ public static ObjectIdentifier getOID(String name) { - return NAME_OID_TABLE.get(name.toLowerCase()); + return NAME_OID_TABLE.get(name.toLowerCase(Locale.ENGLISH)); } /** diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java b/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java index cd6731bae2c..1ea39e799d1 100644 --- a/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java +++ b/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java @@ -26,6 +26,7 @@ package sun.security.pkcs11; import java.nio.ByteBuffer; import java.util.Arrays; +import java.util.Locale; import java.security.*; import java.security.spec.*; @@ -201,7 +202,7 @@ final class P11Cipher extends CipherSpi { } private int parseMode(String mode) throws NoSuchAlgorithmException { - mode = mode.toUpperCase(); + mode = mode.toUpperCase(Locale.ENGLISH); int result; if (mode.equals("ECB")) { result = MODE_ECB; @@ -222,7 +223,7 @@ final class P11Cipher extends CipherSpi { throws NoSuchPaddingException { paddingObj = null; padBuffer = null; - padding = padding.toUpperCase(); + padding = padding.toUpperCase(Locale.ENGLISH); if (padding.equals("NOPADDING")) { paddingType = PAD_NONE; } else if (padding.equals("PKCS5PADDING")) { diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java b/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java index 7a092df10a1..18f3ab450ef 100644 --- a/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java +++ b/jdk/src/share/classes/sun/security/pkcs11/P11RSACipher.java @@ -29,6 +29,8 @@ import java.security.*; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.*; +import java.util.Locale; + import javax.crypto.*; import javax.crypto.spec.*; @@ -110,7 +112,7 @@ final class P11RSACipher extends CipherSpi { protected void engineSetPadding(String padding) throws NoSuchPaddingException { - String lowerPadding = padding.toLowerCase(); + String lowerPadding = padding.toLowerCase(Locale.ENGLISH); if (lowerPadding.equals("pkcs1Padding")) { // empty } else { diff --git a/jdk/src/share/classes/sun/security/provider/certpath/URICertStore.java b/jdk/src/share/classes/sun/security/provider/certpath/URICertStore.java index c0a36b4932a..a27cfa10505 100644 --- a/jdk/src/share/classes/sun/security/provider/certpath/URICertStore.java +++ b/jdk/src/share/classes/sun/security/provider/certpath/URICertStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -52,6 +52,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Locale; import sun.security.x509.AccessDescription; import sun.security.x509.GeneralNameInterface; import sun.security.x509.URIName; @@ -162,7 +163,7 @@ class URICertStore extends CertStoreSpi { } this.uri = ((URICertStoreParameters) params).uri; // if ldap URI, use an LDAPCertStore to fetch certs and CRLs - if (uri.getScheme().toLowerCase().equals("ldap")) { + if (uri.getScheme().toLowerCase(Locale.ENGLISH).equals("ldap")) { if (LDAP.helper() == null) throw new NoSuchAlgorithmException("LDAP not present"); ldap = true; diff --git a/jdk/src/share/classes/sun/security/util/Debug.java b/jdk/src/share/classes/sun/security/util/Debug.java index df5585096fc..5701a80cf9f 100644 --- a/jdk/src/share/classes/sun/security/util/Debug.java +++ b/jdk/src/share/classes/sun/security/util/Debug.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -28,6 +28,7 @@ package sun.security.util; import java.math.BigInteger; import java.util.regex.Pattern; import java.util.regex.Matcher; +import java.util.Locale; /** * A utility class for debuging. @@ -262,7 +263,7 @@ public class Debug { source = left; // convert the rest to lower-case characters - target.append(source.toString().toLowerCase()); + target.append(source.toString().toLowerCase(Locale.ENGLISH)); return target.toString(); } diff --git a/jdk/src/share/classes/sun/security/util/DerOutputStream.java b/jdk/src/share/classes/sun/security/util/DerOutputStream.java index f5400c634ec..c517df8a43e 100644 --- a/jdk/src/share/classes/sun/security/util/DerOutputStream.java +++ b/jdk/src/share/classes/sun/security/util/DerOutputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -25,17 +25,16 @@ package sun.security.util; -import java.io.FilterOutputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; -import java.util.Vector; import java.util.Comparator; import java.util.Arrays; import java.math.BigInteger; +import java.util.Locale; /** @@ -501,7 +500,7 @@ extends ByteArrayOutputStream implements DerEncoder { pattern = "yyyyMMddHHmmss'Z'"; } - SimpleDateFormat sdf = new SimpleDateFormat(pattern); + SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.US); sdf.setTimeZone(tz); byte[] time = (sdf.format(d)).getBytes("ISO-8859-1"); diff --git a/jdk/src/share/classes/sun/security/x509/AVA.java b/jdk/src/share/classes/sun/security/x509/AVA.java index ce0081523c8..e88947488cc 100644 --- a/jdk/src/share/classes/sun/security/x509/AVA.java +++ b/jdk/src/share/classes/sun/security/x509/AVA.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -1227,7 +1227,7 @@ class AVAKeyword { (String keyword, int standard, Map extraKeywordMap) throws IOException { - keyword = keyword.toUpperCase(); + keyword = keyword.toUpperCase(Locale.ENGLISH); if (standard == AVA.RFC2253) { if (keyword.startsWith(" ") || keyword.endsWith(" ")) { throw new IOException("Invalid leading or trailing space " + diff --git a/jdk/src/share/classes/sun/security/x509/AlgorithmId.java b/jdk/src/share/classes/sun/security/x509/AlgorithmId.java index f593304df29..e28c3445718 100644 --- a/jdk/src/share/classes/sun/security/x509/AlgorithmId.java +++ b/jdk/src/share/classes/sun/security/x509/AlgorithmId.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -553,9 +553,10 @@ public class AlgorithmId implements Serializable, DerEncoder { for (Enumeration enum_ = provs[i].keys(); enum_.hasMoreElements(); ) { String alias = (String)enum_.nextElement(); + String upperCaseAlias = alias.toUpperCase(Locale.ENGLISH); int index; - if (alias.toUpperCase().startsWith("ALG.ALIAS") && - (index=alias.toUpperCase().indexOf("OID.", 0)) != -1) { + if (upperCaseAlias.startsWith("ALG.ALIAS") && + (index=upperCaseAlias.indexOf("OID.", 0)) != -1) { index += "OID.".length(); if (index == alias.length()) { // invalid alias entry @@ -565,19 +566,26 @@ public class AlgorithmId implements Serializable, DerEncoder { oidTable = new HashMap(); } oidString = alias.substring(index); - String stdAlgName - = provs[i].getProperty(alias).toUpperCase(); - if (oidTable.get(stdAlgName) == null) { + String stdAlgName = provs[i].getProperty(alias); + if (stdAlgName != null) { + stdAlgName = stdAlgName.toUpperCase(Locale.ENGLISH); + } + if (stdAlgName != null && + oidTable.get(stdAlgName) == null) { oidTable.put(stdAlgName, new ObjectIdentifier(oidString)); } } } } + + if (oidTable == null) { + oidTable = new HashMap(1); + } initOidTable = true; } - return oidTable.get(name.toUpperCase()); + return oidTable.get(name.toUpperCase(Locale.ENGLISH)); } private static ObjectIdentifier oid(int ... values) { diff --git a/jdk/src/share/classes/sun/security/x509/DNSName.java b/jdk/src/share/classes/sun/security/x509/DNSName.java index f0dc6943cb9..398e93fe042 100644 --- a/jdk/src/share/classes/sun/security/x509/DNSName.java +++ b/jdk/src/share/classes/sun/security/x509/DNSName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2000, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -26,6 +26,7 @@ package sun.security.x509; import java.io.IOException; +import java.util.Locale; import sun.security.util.*; @@ -198,8 +199,9 @@ public class DNSName implements GeneralNameInterface { else if (inputName.getType() != NAME_DNS) constraintType = NAME_DIFF_TYPE; else { - String inName = (((DNSName)inputName).getName()).toLowerCase(); - String thisName = name.toLowerCase(); + String inName = + (((DNSName)inputName).getName()).toLowerCase(Locale.ENGLISH); + String thisName = name.toLowerCase(Locale.ENGLISH); if (inName.equals(thisName)) constraintType = NAME_MATCH; else if (thisName.endsWith(inName)) { diff --git a/jdk/src/share/classes/sun/security/x509/RFC822Name.java b/jdk/src/share/classes/sun/security/x509/RFC822Name.java index 81f6af982fe..8f56903469c 100644 --- a/jdk/src/share/classes/sun/security/x509/RFC822Name.java +++ b/jdk/src/share/classes/sun/security/x509/RFC822Name.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2000, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -26,6 +26,7 @@ package sun.security.x509; import java.io.IOException; +import java.util.Locale; import sun.security.util.*; @@ -187,8 +188,9 @@ public class RFC822Name implements GeneralNameInterface constraintType = NAME_DIFF_TYPE; } else { //RFC2459 specifies that case is not significant in RFC822Names - String inName = (((RFC822Name)inputName).getName()).toLowerCase(); - String thisName = name.toLowerCase(); + String inName = + (((RFC822Name)inputName).getName()).toLowerCase(Locale.ENGLISH); + String thisName = name.toLowerCase(Locale.ENGLISH); if (inName.equals(thisName)) { constraintType = NAME_MATCH; } else if (thisName.endsWith(inName)) { diff --git a/jdk/src/share/classes/sun/tools/jconsole/resources/JConsoleResources.java b/jdk/src/share/classes/sun/tools/jconsole/resources/JConsoleResources.java index bce3f2ad799..c9e8ac07c63 100644 --- a/jdk/src/share/classes/sun/tools/jconsole/resources/JConsoleResources.java +++ b/jdk/src/share/classes/sun/tools/jconsole/resources/JConsoleResources.java @@ -46,8 +46,6 @@ import static java.awt.event.KeyEvent.*; */ public class JConsoleResources extends ListResourceBundle { - private static final String cr = System.getProperty("line.separator"); - /** * Returns the contents of this ResourceBundle. * @@ -56,8 +54,8 @@ public class JConsoleResources extends ListResourceBundle { * @return the contents of this ResourceBundle. */ protected Object[][] getContents0() { - return new Object[][] { - // NOTE 1: The value strings in this file containing "{0}" are + Object[][] temp = new Object[][] { + // NOTE 1: The value strings in this file containing "{0}" are // processed by the java.text.MessageFormat class. Any // single quotes appearing in these strings need to be // doubled up. @@ -98,7 +96,7 @@ public class JConsoleResources extends ListResourceBundle { {"Attributes","Attributes"}, {"Blank", "Blank"}, {"BlockedCount WaitedCount", - "Total blocked: {0} Total waited: {1}" + cr}, + "Total blocked: {0} Total waited: {1}\n"}, {"Boot class path","Boot class path"}, {"BorderedComponent.moreOrLessButton.toolTip", "Toggle to show more or less information"}, {"CPU Usage","CPU Usage"}, @@ -271,21 +269,21 @@ public class JConsoleResources extends ListResourceBundle { {"Minimize All.mnemonic", 'M'}, {"Minus Version", "This is {0} version {1}"}, {"Monitor locked", - " - locked {0}" + cr}, + " - locked {0}\n"}, {"Motif","Motif"}, {"Name Build and Mode","{0} (build {1}, {2})"}, {"Name and Build","{0} (build {1})"}, {"Name","Name"}, {"Name: ","Name: "}, {"Name State", - "Name: {0}" + cr + - "State: {1}" + cr}, + "Name: {0}\n" + + "State: {1}\n"}, {"Name State LockName", - "Name: {0}" + cr + - "State: {1} on {2}" + cr}, + "Name: {0}\n" + + "State: {1} on {2}\n"}, {"Name State LockName LockOwner", - "Name: {0}" + cr + - "State: {1} on {2} owned by: {3}" + cr}, + "Name: {0}\n" + + "State: {1} on {2} owned by: {3}\n"}, {"New Connection...", "New Connection..."}, {"New Connection....mnemonic", 'N'}, {"New value applied","New value applied"}, @@ -351,7 +349,7 @@ public class JConsoleResources extends ListResourceBundle { {"Size Mb","{0} Mb"}, {"Source","Source"}, {"Stack trace", - cr + "Stack trace: " + cr}, + "\nStack trace: \n"}, {"Success:","Success:"}, // Note: SummaryTab.headerDateTimeFormat can be one the following: // 1. A combination of two styles for date and time, using the @@ -433,22 +431,27 @@ public class JConsoleResources extends ListResourceBundle { {"plot", "plot"}, {"visualize","visualize"}, {"zz usage text", - "Usage: {0} [ -interval=n ] [ -notile ] [ -pluginpath ] [ -version ] [ connection ... ]" + cr + - cr + - " -interval Set the update interval to n seconds (default is 4 seconds)" + cr + - " -notile Do not tile windows initially (for two or more connections)" + cr + - " -pluginpath Specify the path that jconsole uses to look up the plugins" + cr + - " -version Print program version" + cr + - cr + - " connection = pid || host:port || JMX URL (service:jmx:://...)" + cr + - " pid The process id of a target process" + cr + - " host A remote host name or IP address" + cr + - " port The port number for the remote connection" + cr + - cr + - " -J Specify the input arguments to the Java virtual machine" + cr + + "Usage: {0} [ -interval=n ] [ -notile ] [ -pluginpath ] [ -version ] [ connection ... ]\n\n" + + " -interval Set the update interval to n seconds (default is 4 seconds)\n" + + " -notile Do not tile windows initially (for two or more connections)\n" + + " -pluginpath Specify the path that jconsole uses to look up the plugins\n\n" + + " -version Print program version\n" + + " connection = pid || host:port || JMX URL (service:jmx:://...)\n" + + " pid The process id of a target process\n" + + " host A remote host name or IP address\n" + + " port The port number for the remote connection\n\n" + + " -J Specify the input arguments to the Java virtual machine\n" + " on which jconsole is running"}, // END OF MATERIAL TO LOCALIZE }; + + String ls = System.getProperty("line.separator"); + for(int i=0;i resolvconf(String keyword, + int maxperkeyword, + int maxkeywords) + { + LinkedList ll = new LinkedList<>(); try { BufferedReader in = @@ -99,8 +102,8 @@ public class ResolverConfigurationImpl return ll; } - private LinkedList searchlist; - private LinkedList nameservers; + private LinkedList searchlist; + private LinkedList nameservers; // Load DNS configuration from OS @@ -118,9 +121,9 @@ public class ResolverConfigurationImpl // get the name servers from /etc/resolv.conf nameservers = - (LinkedList)java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction>() { + public LinkedList run() { // typically MAXNS is 3 but we've picked 5 here // to allow for additional servers if required. return resolvconf("nameserver", 1, 5); @@ -137,15 +140,15 @@ public class ResolverConfigurationImpl // obtain search list or local domain - private LinkedList getSearchList() { + private LinkedList getSearchList() { - LinkedList sl; + LinkedList sl; // first try the search keyword in /etc/resolv.conf - sl = (LinkedList)java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { + sl = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction>() { + public LinkedList run() { LinkedList ll; // first try search keyword (max 6 domains) @@ -177,10 +180,10 @@ public class ResolverConfigurationImpl // try domain keyword in /etc/resolv.conf - sl = (LinkedList)java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - LinkedList ll; + sl = java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction>() { + public LinkedList run() { + LinkedList ll; ll = resolvconf("domain", 1, 1); if (ll.size() > 0) { @@ -197,7 +200,7 @@ public class ResolverConfigurationImpl // no local domain so try fallback (RPC) domain or // hostname - sl = new LinkedList(); + sl = new LinkedList<>(); String domain = fallbackDomain0(); if (domain != null && domain.length() > 0) { sl.add(domain); @@ -213,7 +216,7 @@ public class ResolverConfigurationImpl opts = new OptionsImpl(); } - public List searchlist() { + public List searchlist() { synchronized (lock) { loadConfig(); @@ -222,7 +225,7 @@ public class ResolverConfigurationImpl } } - public List nameservers() { + public List nameservers() { synchronized (lock) { loadConfig(); diff --git a/jdk/src/solaris/native/java/net/NetworkInterface.c b/jdk/src/solaris/native/java/net/NetworkInterface.c index 58675462b96..c166cc86dda 100644 --- a/jdk/src/solaris/native/java/net/NetworkInterface.c +++ b/jdk/src/solaris/native/java/net/NetworkInterface.c @@ -131,7 +131,7 @@ static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *name, s static short getSubnet(JNIEnv *env, int sock, const char *ifname); static int getIndex(int sock, const char *ifname); -static int getFlags(JNIEnv *env, int sock, const char *ifname); +static int getFlags(int sock, const char *ifname); static int getMacAddress(JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr, unsigned char *buf); static int getMTU(JNIEnv *env, int sock, const char *ifname); @@ -550,7 +550,7 @@ static int getFlags0(JNIEnv *env, jstring name) { name_utf = (*env)->GetStringUTFChars(env, name, &isCopy); - ret = getFlags(env, sock, name_utf); + ret = getFlags(sock, name_utf); close(sock); (*env)->ReleaseStringUTFChars(env, name, name_utf); @@ -753,19 +753,27 @@ static netif *enumInterfaces(JNIEnv *env) { * If IPv6 is available then enumerate IPv6 addresses. */ #ifdef AF_INET6 - sock = openSocket(env, AF_INET6); - if (sock < 0 && (*env)->ExceptionOccurred(env)) { - freeif(ifs); - return NULL; - } - ifs = enumIPv6Interfaces(env, sock, ifs); - close(sock); + /* User can disable ipv6 expicitly by -Djava.net.preferIPv4Stack=true, + * so we have to call ipv6_available() + */ + if (ipv6_available()) { - if ((*env)->ExceptionOccurred(env)) { - freeif(ifs); - return NULL; - } + sock = openSocket(env, AF_INET6); + if (sock < 0 && (*env)->ExceptionOccurred(env)) { + freeif(ifs); + return NULL; + } + + ifs = enumIPv6Interfaces(env, sock, ifs); + close(sock); + + if ((*env)->ExceptionOccurred(env)) { + freeif(ifs); + return NULL; + } + + } #endif return ifs; @@ -877,7 +885,7 @@ netif *addif(JNIEnv *env, int sock, const char * if_name, netif *ifs, struct soc * the 'parent' interface with the new records. */ *name_colonP = 0; - if (getFlags(env,sock,name) < 0) { + if (getFlags(sock, name) < 0) { // failed to access parent interface do not create parent. // We are a virtual interface with no parent. isVirtual = 1; @@ -1249,7 +1257,7 @@ static int getMTU(JNIEnv *env, int sock, const char *ifname) { return if2.ifr_mtu; } -static int getFlags(JNIEnv *env, int sock, const char *ifname) { +static int getFlags(int sock, const char *ifname) { struct ifreq if2; int ret = -1; @@ -1625,13 +1633,12 @@ static int getMTU(JNIEnv *env, int sock, const char *ifname) { } -static int getFlags(JNIEnv *env, int sock, const char *ifname) { +static int getFlags(int sock, const char *ifname) { struct lifreq lifr; memset((caddr_t)&lifr, 0, sizeof(lifr)); strcpy((caddr_t)&(lifr.lifr_name), ifname); if (ioctl(sock, SIOCGLIFFLAGS, (char *)&lifr) < 0) { - NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFFLAGS failed"); return -1; } diff --git a/jdk/src/solaris/native/java/nio/MappedByteBuffer.c b/jdk/src/solaris/native/java/nio/MappedByteBuffer.c index 4a278858677..15c4ec5f5de 100644 --- a/jdk/src/solaris/native/java/nio/MappedByteBuffer.c +++ b/jdk/src/solaris/native/java/nio/MappedByteBuffer.c @@ -32,14 +32,11 @@ #include #include - JNIEXPORT jboolean JNICALL -Java_java_nio_MappedByteBuffer_isLoaded0(JNIEnv *env, jobject obj, - jlong address, jlong len) +Java_java_nio_MappedByteBuffer_isLoaded0(JNIEnv *env, jobject obj, jlong address, + jlong len, jint numPages) { jboolean loaded = JNI_TRUE; - jint pageSize = sysconf(_SC_PAGESIZE); - jint numPages = (len + pageSize - 1) / pageSize; int result = 0; int i = 0; void *a = (void *) jlong_to_ptr(address); @@ -55,9 +52,9 @@ Java_java_nio_MappedByteBuffer_isLoaded0(JNIEnv *env, jobject obj, } result = mincore(a, (size_t)len, vec); - if (result != 0) { - free(vec); + if (result == -1) { JNU_ThrowIOExceptionWithLastError(env, "mincore failed"); + free(vec); return JNI_FALSE; } @@ -72,23 +69,15 @@ Java_java_nio_MappedByteBuffer_isLoaded0(JNIEnv *env, jobject obj, } -JNIEXPORT jint JNICALL +JNIEXPORT void JNICALL Java_java_nio_MappedByteBuffer_load0(JNIEnv *env, jobject obj, jlong address, - jlong len, jint pageSize) + jlong len) { - int pageIncrement = pageSize / sizeof(int); - int numPages = (len + pageSize - 1) / pageSize; - int *ptr = (int *)jlong_to_ptr(address); - int i = 0; - int j = 0; - int result = madvise((caddr_t)ptr, len, MADV_WILLNEED); - - /* touch every page */ - for (i=0; i stringToList(String str) { + LinkedList ll = new LinkedList<>(); // comma and space are valid delimites StringTokenizer st = new StringTokenizer(str, ", "); @@ -112,7 +111,7 @@ public class ResolverConfigurationImpl opts = new OptionsImpl(); } - public List searchlist() { + public List searchlist() { synchronized (lock) { loadConfig(); @@ -121,7 +120,7 @@ public class ResolverConfigurationImpl } } - public List nameservers() { + public List nameservers() { synchronized (lock) { loadConfig(); diff --git a/jdk/src/windows/native/java/nio/MappedByteBuffer.c b/jdk/src/windows/native/java/nio/MappedByteBuffer.c index 8cce64a26e2..5af3b99c73d 100644 --- a/jdk/src/windows/native/java/nio/MappedByteBuffer.c +++ b/jdk/src/windows/native/java/nio/MappedByteBuffer.c @@ -31,8 +31,8 @@ #include JNIEXPORT jboolean JNICALL -Java_java_nio_MappedByteBuffer_isLoaded0(JNIEnv *env, jobject obj, - jlong address, jlong len) +Java_java_nio_MappedByteBuffer_isLoaded0(JNIEnv *env, jobject obj, jlong address, + jlong len, jint numPages) { jboolean loaded = JNI_FALSE; /* Information not available? @@ -43,22 +43,11 @@ Java_java_nio_MappedByteBuffer_isLoaded0(JNIEnv *env, jobject obj, return loaded; } -JNIEXPORT jint JNICALL +JNIEXPORT void JNICALL Java_java_nio_MappedByteBuffer_load0(JNIEnv *env, jobject obj, jlong address, - jlong len, jint pageSize) + jlong len) { - int *ptr = (int *) jlong_to_ptr(address); - int pageIncrement = pageSize / sizeof(int); - jlong numPages = (len + pageSize - 1) / pageSize; - int i = 0; - int j = 0; - - /* touch every page */ - for (i=0; i JLClass; * Class to encapsulate the extraction of the java string contents * into a buffer and the cleanup of the buffer */ - class JavaStringBuffer +class JavaStringBuffer { protected: LPWSTR m_pStr; jsize m_dwSize; + LPWSTR getNonEmptyString() { + return (NULL==m_pStr) + ? L"" + : m_pStr; + } public: JavaStringBuffer(jsize cbTCharCount) { m_dwSize = cbTCharCount; - m_pStr = (LPWSTR)safe_Malloc( (m_dwSize+1)*sizeof(WCHAR) ); + m_pStr = (0 == m_dwSize) + ? NULL + : (LPWSTR)safe_Malloc( (m_dwSize+1)*sizeof(WCHAR) ); } JavaStringBuffer(JNIEnv *env, jstring text) { - if (NULL == text) { - m_pStr = L""; - m_dwSize = 0; + m_dwSize = (NULL == text) + ? 0 + : env->GetStringLength(text); + if (0 == m_dwSize) { + m_pStr = NULL; } else { - m_dwSize = env->GetStringLength(text); m_pStr = (LPWSTR)safe_Malloc( (m_dwSize+1)*sizeof(WCHAR) ); env->GetStringRegion(text, 0, m_dwSize, reinterpret_cast(m_pStr)); m_pStr[m_dwSize] = 0; @@ -341,12 +349,16 @@ public: void Resize(jsize cbTCharCount) { m_dwSize = cbTCharCount; + //It is ok to have non-null terminated string here. + //The function is used only for space reservation in staff buffer for + //followed data copying process. And that is the reason why we ignore + //the special case m_dwSize==0 here. m_pStr = (LPWSTR)safe_Realloc(m_pStr, (m_dwSize+1)*sizeof(WCHAR) ); } //we are in UNICODE now, so LPWSTR:=:LPTSTR - operator LPWSTR() { return m_pStr; } - operator LPARAM() { return (LPARAM)m_pStr; } - void *GetData() { return (void *)m_pStr; } + operator LPWSTR() { return getNonEmptyString(); } + operator LPARAM() { return (LPARAM)getNonEmptyString(); } + void *GetData() { return (void *)getNonEmptyString(); } jsize GetSize() { return m_dwSize; } }; diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index db5b356877c..ab70ed9deeb 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -366,139 +366,6 @@ javax/print/attribute/MediaMappingsTest.java generic-all # jdk_net -# Suspect many of these tests auffer from using fixed ports, no concrete -# evidence. - -# Times out on Windows X64 -sun/net/www/http/KeepAliveStream/KeepAliveStreamCloseWithWrongContentLength.java generic-all - -# Dies on Solaris 10 sparc and sparcv9, Linux -ea -esa with -# Interrupted or IO exception, maybe writing to non-unique named file? -com/sun/net/httpserver/bugs/B6373555.java generic-all - -# Fails on OpenSolaris, times out -java/net/MulticastSocket/SetOutgoingIf.java generic-all - -# Timed out on Solaris 10 X86. -com/sun/net/httpserver/Test3.java generic-all - -# Exception in test on windows -com/sun/net/httpserver/bugs/B6373555.java windows-all - -# One of these pollutes the samevm on Linux, too many open files, kills jtreg -com/sun/net/httpserver/bugs/B6339483.java generic-all -com/sun/net/httpserver/bugs/B6341616.java generic-all - -# Suspects in cascading samevm problem, solaris 11 i586 (needs othervm?) -# Suspect use of setHttps*()? -com/sun/net/httpserver/SelCacheTest.java generic-all -com/sun/net/httpserver/Test1.java generic-all -com/sun/net/httpserver/Test12.java generic-all -com/sun/net/httpserver/Test13.java generic-all -com/sun/net/httpserver/Test6a.java generic-all -com/sun/net/httpserver/Test7a.java generic-all -com/sun/net/httpserver/Test8a.java generic-all -com/sun/net/httpserver/Test9.java generic-all -com/sun/net/httpserver/Test9a.java generic-all - -# 10,000 connections, fails on Linux and makes tests&jtreg fail with samevm -com/sun/net/httpserver/bugs/B6361557.java generic-all - -# Address already in use with samevm? Always? Solaris sparc, probably ports -java/net/Authenticator/B4933582.sh generic-all -java/net/DatagramSocket/SendSize.java generic-all - -# Solaris 11: exception wrong address??? -java/net/Inet6Address/B6558853.java generic-all - -# Not closing stream on file i6a1, windows samevm problem -java/net/Inet6Address/serialize/Serialize.java generic-all - -# Linux x64 fails "network unreachable"? -java/net/ipv6tests/TcpTest.java generic-all - -# Linux i586, fails with unexpected output -java/net/MulticastSocket/NoLoopbackPackets.java linux-i586 - -# Address already in use -java/net/DatagramSocket/DatagramTimeout.java generic-all - -# Fails on windows, takes too long and fails -# Solaris 10 sparcv9, samevm, java.lang.Exception: Takes too long. Dead lock -java/net/Socket/DeadlockTest.java generic-all - -# Linux i586 address already in use or connection error, samevm issues -java/net/Socket/AccurateTimeout.java generic-all -java/net/Socket/asyncClose/BrokenPipe.java generic-all -java/net/Socket/CloseAvailable.java generic-all - -# Linux X64 address already in use, samevm issues -java/net/Socket/LingerTest.java generic-all -java/net/Socket/LinkLocal.java generic-all -java/net/Socket/NullHost.java generic-all -java/net/Socket/ProxyCons.java generic-all -java/net/Socket/ReadTimeout.java generic-all - -# Linux X64 address already in use, samevm issues -java/net/Socket/SetReceiveBufferSize.java generic-all - -# Linux i586 address already in use or connection error, samevm issues -java/net/Socket/setReuseAddress/Basic.java generic-all -java/net/Socket/setReuseAddress/Restart.java generic-all - -# Linux X64 address already in use, samevm issues -java/net/Socket/SetSoLinger.java generic-all - -# Address already in use, windows samevm -java/net/Socket/Timeout.java generic-all - -# Linux X64 address already in use, samevm issues -java/net/Socket/ShutdownBoth.java generic-all -java/net/Socket/SoTimeout.java generic-all -java/net/Socket/TestClose.java generic-all -java/net/Socket/UrgentDataTest.java generic-all -java/net/SocketInputStream/SocketClosedException.java generic-all -java/net/SocketInputStream/SocketTimeout.java generic-all - -# Linux i586, address already in use or timeout, samevm issues -java/net/URLConnection/DisconnectAfterEOF.java generic-all -java/net/URLConnection/HandleContentTypeWithAttrs.java generic-all -java/net/URLConnection/Responses.java generic-all -java/net/URLConnection/TimeoutTest.java generic-all -java/net/URLConnection/ZeroContentLength.java generic-all - -# Solaris 11 i586 fails with samevm, not sure why -java/net/ResponseCache/B6181108.java generic-all -java/net/ResponseCache/ResponseCacheTest.java generic-all -java/net/URL/GetContent.java generic-all -java/net/URLConnection/HttpContinueStackOverflow.java generic-all -java/net/URLConnection/Redirect307Test.java generic-all -java/net/URLConnection/RedirectLimit.java generic-all -java/net/URLConnection/ResendPostBody.java generic-all -java/net/URL/OpenStream.java generic-all -java/net/URLClassLoader/ClassLoad.java generic-all -java/net/URLConnection/SetIfModifiedSince.java generic-all -java/net/URLConnection/URLConnectionHeaders.java generic-all - -# Linux i586 Connection refused or address already in use, samevm issues -sun/net/ftp/B6427768.java generic-all -sun/net/ftp/FtpGetContent.java generic-all -sun/net/ftp/FtpURL.java generic-all - -# Failed on solaris 10 i586, Exception: should have gotten HttpRetryException? -sun/net/www/http/ChunkedOutputStream/Test.java generic-all - -# Trouble cleaning up threads in samevm mode on solaris 11 i586 -sun/net/www/http/HttpClient/ProxyTest.java generic-all -sun/net/www/http/ChunkedInputStream/ChunkedEncodingTest.java generic-all -sun/net/www/http/ChunkedInputStream/ChunkedEncodingWithProgressMonitorTest.java generic-all -sun/net/www/http/HttpClient/B6726695.java generic-all -sun/net/www/http/HttpClient/MultiThreadTest.java generic-all -sun/net/www/http/KeepAliveCache/KeepAliveTimerThread.java generic-all - -# Connection refused, windows samevm -sun/net/www/protocol/http/DigestTest.java generic-all - ############################################################################ # jdk_io diff --git a/jdk/test/com/sun/jdi/ShellScaffold.sh b/jdk/test/com/sun/jdi/ShellScaffold.sh index 99193a18ed6..d61acb51094 100644 --- a/jdk/test/com/sun/jdi/ShellScaffold.sh +++ b/jdk/test/com/sun/jdi/ShellScaffold.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright (c) 2002, 2009, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 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 @@ -141,7 +141,10 @@ topPid=$$ cleanup() { if [ -r "$failFile" ] ; then - cat $failFile >& 2 + ls -l "$failFile" >&2 + echo "" >&2 + cat "$failFile" >&2 + echo "" >&2 fi # Kill all processes that have our special @@ -337,6 +340,10 @@ EOF failFile=$tmpFileDir/testFailed debuggeepidFile=$tmpFileDir/debuggeepid rm -f $failFile $debuggeepidFile + if [ -f "$failFile" ]; then + echo "ERROR: unable to delete existing failFile:" >&2 + ls -l "$failFile" >&2 + fi if [ -z "$pkg" ] ; then pkgSlash= @@ -524,6 +531,10 @@ cmd() # See 6562090. Maybe there is a way that the exit # can cause jdb to not get the quit. sleep 5 + + # The exit code value here doesn't matter since this function + # is called as part of a pipeline and it is not the last command + # in the pipeline. exit 1 fi @@ -938,6 +949,10 @@ waitForFinish() done if [ -r "$failFile" ] ; then + ls -l "$failFile" >&2 + echo "" >&2 + cat "$failFile" >&2 + echo "" >&2 exit 1 fi } @@ -946,33 +961,45 @@ waitForFinish() # $3 is the number of lines to search (from the end) grepForString() { - # See bug 6220903. Sometimes the jdb '> ' prompt chars - # get inserted into the string we are searching for - # so ignore those chars. if [ -z "$3" ] ; then theCmd=cat else theCmd="tail -$3" fi + case "$2" in - *\>*) - # Target string contains a > so we better - # not ignore it + *\>*) + # Target string contains a '>' so we better not ignore it $theCmd $1 | $grep -s "$2" > $devnull 2>&1 - return $? + stat="$?" ;; + *) + # Target string does not contain a '>'. + # NOTE: if $1 does not end with a new line, piping it to sed + # doesn't include the chars on the last line. Detect this + # case, and add a new line. + theFile="$1" + if [ `tail -1 "$theFile" | wc -l | sed -e 's@ @@g'` = 0 ] ; then + # The target file doesn't end with a new line so we have + # add one to a copy of the target file so the sed command + # below can filter that last line. + cp "$theFile" "$theFile.tmp" + theFile="$theFile.tmp" + echo >> "$theFile" + fi + + # See bug 6220903. Sometimes the jdb prompt chars ('> ') can + # get interleaved in the target file which can keep us from + # matching the target string. + $theCmd "$theFile" | sed -e 's@> @@g' -e 's@>@@g' \ + | $grep -s "$2" > $devnull 2>&1 + stat=$? + if [ "$theFile" != "$1" ]; then + # remove the copy of the target file + rm -f "$theFile" + fi + unset theFile esac - # Target string does not contain a >. - # Ignore > and '> ' in the file. - # NOTE: if $1 does not end with a new line, piping it to sed doesn't include the - # chars on the last line. Detect this case, and add a new line. - cp $1 $1.tmp - if [ `tail -1 $1.tmp | wc -l | sed -e 's@ @@g'` = 0 ] ; then - echo >> $1.tmp - fi - $theCmd $1.tmp | sed -e 's@> @@g' -e 's@>@@g' | $grep -s "$2" > $devnull 2>&1 - stat=$? - rm -f $1.tmp return $stat } @@ -1037,6 +1064,11 @@ pass() echo echo "--Done: test passed" exit 0 + else + ls -l "$failFile" >&2 + echo "" >&2 + cat "$failFile" >&2 + echo "" >&2 fi } diff --git a/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/ContextWithNullProperties.java b/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/ContextWithNullProperties.java new file mode 100644 index 00000000000..f8706df0caf --- /dev/null +++ b/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/ContextWithNullProperties.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 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. + */ + +/* + * @test + * @bug 6676075 + * @summary RegistryContext (com.sun.jndi.url.rmi.rmiURLContext) coding problem + */ + +import java.rmi.RemoteException; +import java.rmi.registry.LocateRegistry; + +import com.sun.jndi.rmi.registry.*; + +public class ContextWithNullProperties { + + public static void main(String[] args) throws Exception { + + // Create registry on port 1099 if one is not already running. + try { + LocateRegistry.createRegistry(1099); + } catch (RemoteException e) { + } + + System.out.println("Connecting to the default Registry..."); + // Connect to the default Registry. + // Pass null as the JNDI environment properties (see final argument) + RegistryContext ctx = new RegistryContext(null, -1, null); + } +} diff --git a/jdk/test/com/sun/net/httpserver/Test1.java b/jdk/test/com/sun/net/httpserver/Test1.java index 786b94eda4d..e58900e0f7d 100644 --- a/jdk/test/com/sun/net/httpserver/Test1.java +++ b/jdk/test/com/sun/net/httpserver/Test1.java @@ -24,17 +24,15 @@ /** * @test * @bug 6270015 + * @run main/othervm Test1 * @summary Light weight HTTP server */ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import java.security.cert.*; import javax.net.ssl.*; /* basic http/s connectivity test diff --git a/jdk/test/com/sun/net/httpserver/Test11.java b/jdk/test/com/sun/net/httpserver/Test11.java index d3db077416f..f683a16e834 100644 --- a/jdk/test/com/sun/net/httpserver/Test11.java +++ b/jdk/test/com/sun/net/httpserver/Test11.java @@ -28,7 +28,6 @@ */ import java.net.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import com.sun.net.httpserver.*; @@ -52,22 +51,25 @@ public class Test11 { public static void main (String[] args) throws Exception { System.out.print ("Test 11: "); - HttpServer server = HttpServer.create (new InetSocketAddress(0), 0); - HttpContext ctx = server.createContext ( - "/foo/bar/", new Handler () - ); - ExecutorService s = Executors.newCachedThreadPool(); - server.setExecutor (s); - server.start (); - URL url = new URL ("http://localhost:" + server.getAddress().getPort()+ - "/Foo/bar/test.html"); - HttpURLConnection urlc = (HttpURLConnection)url.openConnection(); - int r = urlc.getResponseCode(); - System.out.println ("OK"); - s.shutdown(); - server.stop(5); - if (r == 200) { - throw new RuntimeException ("wrong response received"); + HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); + ExecutorService s = Executors.newCachedThreadPool(); + try { + HttpContext ctx = server.createContext ( + "/foo/bar/", new Handler () + ); + s = Executors.newCachedThreadPool(); + server.start (); + URL url = new URL ("http://localhost:" + server.getAddress().getPort()+ + "/Foo/bar/test.html"); + HttpURLConnection urlc = (HttpURLConnection)url.openConnection(); + int r = urlc.getResponseCode(); + if (r == 200) { + throw new RuntimeException ("wrong response received"); + } + System.out.println ("OK"); + } finally { + s.shutdown(); + server.stop(2); } } } diff --git a/jdk/test/com/sun/net/httpserver/Test12.java b/jdk/test/com/sun/net/httpserver/Test12.java index d7dd0d931f5..6d9049697a7 100644 --- a/jdk/test/com/sun/net/httpserver/Test12.java +++ b/jdk/test/com/sun/net/httpserver/Test12.java @@ -24,17 +24,15 @@ /** * @test * @bug 6270015 + * @run main/othervm Test12 * @summary Light weight HTTP server */ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import java.security.cert.*; import javax.net.ssl.*; /* basic http/s connectivity test diff --git a/jdk/test/com/sun/net/httpserver/Test13.java b/jdk/test/com/sun/net/httpserver/Test13.java index f990885f294..a4299322038 100644 --- a/jdk/test/com/sun/net/httpserver/Test13.java +++ b/jdk/test/com/sun/net/httpserver/Test13.java @@ -24,17 +24,16 @@ /** * @test * @bug 6270015 + * @run main/othervm Test13 * @summary Light weight HTTP server */ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import java.security.cert.*; + import javax.net.ssl.*; /* basic http/s connectivity test diff --git a/jdk/test/com/sun/net/httpserver/Test6a.java b/jdk/test/com/sun/net/httpserver/Test6a.java index d22db274f3a..0367fa76da6 100644 --- a/jdk/test/com/sun/net/httpserver/Test6a.java +++ b/jdk/test/com/sun/net/httpserver/Test6a.java @@ -24,17 +24,15 @@ /** * @test * @bug 6270015 + * @run main/othervm Test6a * @summary Light weight HTTP server */ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.security.auth.callback.*; import javax.net.ssl.*; /** diff --git a/jdk/test/com/sun/net/httpserver/Test7a.java b/jdk/test/com/sun/net/httpserver/Test7a.java index 3080b807334..67039f81da0 100644 --- a/jdk/test/com/sun/net/httpserver/Test7a.java +++ b/jdk/test/com/sun/net/httpserver/Test7a.java @@ -24,18 +24,15 @@ /** * @test * @bug 6270015 + * @run main/othervm Test7a * @summary Light weight HTTP server */ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; -import java.util.logging.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.security.auth.callback.*; import javax.net.ssl.*; /** diff --git a/jdk/test/com/sun/net/httpserver/Test8a.java b/jdk/test/com/sun/net/httpserver/Test8a.java index ed64d1a4621..9e8f96a9728 100644 --- a/jdk/test/com/sun/net/httpserver/Test8a.java +++ b/jdk/test/com/sun/net/httpserver/Test8a.java @@ -24,18 +24,15 @@ /** * @test * @bug 6270015 + * @run main/othervm Test8a * @summary Light weight HTTP server */ import com.sun.net.httpserver.*; -import java.util.*; import java.util.concurrent.*; -import java.util.logging.*; import java.io.*; import java.net.*; -import java.security.*; -import javax.security.auth.callback.*; import javax.net.ssl.*; /** @@ -50,46 +47,50 @@ public class Test8a extends Test { //h.setLevel (Level.INFO); //log.addHandler (h); //log.setLevel (Level.INFO); - Handler handler = new Handler(); - InetSocketAddress addr = new InetSocketAddress (0); - 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(); - server.setHttpsConfigurator(new HttpsConfigurator (ssl)); - server.setExecutor (executor); - server.start (); + HttpsServer server = null; + ExecutorService executor = null; + try { + Handler handler = new Handler(); + InetSocketAddress addr = new InetSocketAddress (0); + server = HttpsServer.create (addr, 0); + HttpContext ctx = server.createContext ("/test", handler); + executor = Executors.newCachedThreadPool(); + SSLContext ssl = new SimpleSSLContext(System.getProperty("test.src")).get(); + server.setHttpsConfigurator(new HttpsConfigurator (ssl)); + server.setExecutor (executor); + server.start (); - URL url = new URL ("https://localhost:"+server.getAddress().getPort()+"/test/foo.html"); - System.out.print ("Test8a: " ); - HttpsURLConnection urlc = (HttpsURLConnection)url.openConnection (); - urlc.setDoOutput (true); - urlc.setRequestMethod ("POST"); - urlc.setHostnameVerifier (new DummyVerifier()); - urlc.setSSLSocketFactory (ssl.getSocketFactory()); - OutputStream os = new BufferedOutputStream (urlc.getOutputStream(), 8000); - for (int i=0; i selkeys = selector.selectedKeys(); for (SelectionKey key : selkeys) { if (key.isReadable()) { SocketChannel chan = (SocketChannel)key.channel(); - buf.clear(); + ByteBuffer buf = (ByteBuffer)key.attachment(); try { - int x = chan.read (buf); - if (x == -1) { + int x = chan.read(buf); + if (x == -1 || responseComplete(buf)) { + key.attach(null); chan.close(); + responses++; } } catch (IOException e) {} } } - if (i< NUM) { - SocketChannel schan = SocketChannel.open (destaddr); - String cmd = "GET /test/foo.html HTTP/1.1\r\nContent-length: 0\r\n\r\n"; - buf.rewind (); - buf.put (cmd.getBytes()); - buf.flip(); + if (requests < NUM) { + SocketChannel schan = SocketChannel.open(destaddr); + requestBuf.rewind(); int c = 0; - while (buf.remaining() > 0) { - c += schan.write (buf); + while (requestBuf.remaining() > 0) { + c += schan.write(requestBuf); } - schan.configureBlocking (false); - schan.register (selector, SelectionKey.OP_READ, null); - } else { + schan.configureBlocking(false); + schan.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(100)); + requests++; + } + if (responses == NUM) { System.out.println ("Finished clients"); - server.stop (1); - executor.shutdown (); - return; + break; } } + server.stop (1); + selector.close(); + executor.shutdown (); + + } + + /* Look for CR LF CR LF */ + static boolean responseComplete(ByteBuffer buf) { + int pos = buf.position(); + buf.flip(); + byte[] lookingFor = new byte[] {'\r', '\n', '\r', '\n' }; + int lookingForCount = 0; + while (buf.hasRemaining()) { + byte b = buf.get(); + if (b == lookingFor[lookingForCount]) { + lookingForCount++; + if (lookingForCount == 4) { + return true; + } + } else { + lookingForCount = 0; + } + } + buf.position(pos); + buf.limit(buf.capacity()); + return false; } } diff --git a/jdk/test/com/sun/net/httpserver/bugs/B6373555.java b/jdk/test/com/sun/net/httpserver/bugs/B6373555.java index 8660d3190d4..bdb37cd484c 100644 --- a/jdk/test/com/sun/net/httpserver/bugs/B6373555.java +++ b/jdk/test/com/sun/net/httpserver/bugs/B6373555.java @@ -46,7 +46,7 @@ public class B6373555 { private static Object lock; static HttpServer httpServer; static ExecutorService pool, execs; - static int NUM = 4000; + static int NUM = 1000; public static void main(String[] args) throws Exception { try { @@ -125,7 +125,7 @@ public class B6373555 { } } catch(Exception e) { - //e.printStackTrace(); + e.printStackTrace(); System.out.print ("."); error = true; } diff --git a/jdk/test/java/beans/XMLEncoder/Test4631471.java b/jdk/test/java/beans/XMLEncoder/Test4631471.java index 9c67e60e3d9..0b3b107f7c6 100644 --- a/jdk/test/java/beans/XMLEncoder/Test4631471.java +++ b/jdk/test/java/beans/XMLEncoder/Test4631471.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -23,7 +23,7 @@ /* * @test - * @bug 4631471 + * @bug 4631471 6972468 * @summary Tests DefaultTreeModel encoding * @author Sergey Malenkov, Mark Davidson */ @@ -37,6 +37,12 @@ import javax.swing.tree.TreeNode; public abstract class Test4631471 extends AbstractTest { public static void main(String[] args) throws Exception { + main(); + System.setSecurityManager(new SecurityManager()); + main(); + } + + private static void main() throws Exception { // the DefaultMutableTreeNode will archive correctly new Test4631471() { protected Object getObject() { diff --git a/jdk/test/java/beans/XMLEncoder/Test4903007.java b/jdk/test/java/beans/XMLEncoder/Test4903007.java index 82583720934..02ba9a6a939 100644 --- a/jdk/test/java/beans/XMLEncoder/Test4903007.java +++ b/jdk/test/java/beans/XMLEncoder/Test4903007.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -23,7 +23,7 @@ /* * @test - * @bug 4903007 + * @bug 4903007 6972468 * @summary Tests encoding of container with boxes and BoxLayout * @author Sergey Malenkov, Mark Davidson */ @@ -36,7 +36,7 @@ import javax.swing.JPanel; public class Test4903007 extends AbstractTest { public static void main(String[] args) throws Exception { - new Test4903007().test(false); // TODO: could not encode with security manager + new Test4903007().test(true); } protected JPanel getObject() { diff --git a/jdk/test/java/beans/XMLEncoder/javax_swing_JLayeredPane.java b/jdk/test/java/beans/XMLEncoder/javax_swing_JLayeredPane.java index 05c90ba15dc..1e41bc41e7b 100644 --- a/jdk/test/java/beans/XMLEncoder/javax_swing_JLayeredPane.java +++ b/jdk/test/java/beans/XMLEncoder/javax_swing_JLayeredPane.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -23,7 +23,7 @@ /* * @test - * @bug 5023552 + * @bug 5023552 6972468 * @summary Tests JLayeredPane encoding * @author Sergey Malenkov */ @@ -35,7 +35,7 @@ import javax.swing.JPanel; public final class javax_swing_JLayeredPane extends AbstractTest { public static void main(String[] args) { - new javax_swing_JLayeredPane().test(false); // TODO: could not encode with security manager + new javax_swing_JLayeredPane().test(true); } private static void init(JLayeredPane pane, int layer, int x, int y, int w, int h, Color color) { diff --git a/jdk/test/java/lang/Throwable/SuppressedExceptions.java b/jdk/test/java/lang/Throwable/SuppressedExceptions.java index 89f974c0f4f..0993cd6333f 100644 --- a/jdk/test/java/lang/Throwable/SuppressedExceptions.java +++ b/jdk/test/java/lang/Throwable/SuppressedExceptions.java @@ -26,7 +26,7 @@ import java.util.*; /* * @test - * @bug 6911258 6962571 + * @bug 6911258 6962571 6963622 * @summary Basic tests of suppressed exceptions * @author Joseph D. Darcy */ @@ -35,11 +35,22 @@ public class SuppressedExceptions { private static String message = "Bad suppressed exception information"; public static void main(String... args) throws Exception { + noSelfSuppression(); basicSupressionTest(); serializationTest(); selfReference(); } + private static void noSelfSuppression() { + Throwable throwable = new Throwable(); + try { + throwable.addSuppressedException(throwable); + throw new RuntimeException("IllegalArgumentException for self-suppresion not thrown."); + } catch (IllegalArgumentException iae) { + ; // Expected + } + } + private static void basicSupressionTest() { Throwable throwable = new Throwable(); RuntimeException suppressed = new RuntimeException("A suppressed exception."); @@ -156,9 +167,8 @@ public class SuppressedExceptions { throwable1.printStackTrace(); - - throwable1.addSuppressedException(throwable1); throwable1.addSuppressedException(throwable2); + throwable2.addSuppressedException(throwable1); throwable1.printStackTrace(); } diff --git a/jdk/test/java/net/DatagramSocket/DatagramTimeout.java b/jdk/test/java/net/DatagramSocket/DatagramTimeout.java index 0aa08752e3d..85bcbbdf6b5 100644 --- a/jdk/test/java/net/DatagramSocket/DatagramTimeout.java +++ b/jdk/test/java/net/DatagramSocket/DatagramTimeout.java @@ -27,25 +27,25 @@ * @summary test to see if timeout hangs * @run main/timeout=15 DatagramTimeout */ -import java.net.*; -import java.io.*; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.SocketTimeoutException; public class DatagramTimeout { - - public static ServerSocket sock; - public static void main(String[] args) throws Exception { boolean success = false; + DatagramSocket sock = new DatagramSocket(); + try { - DatagramSocket sock; DatagramPacket p; byte[] buffer = new byte[50]; p = new DatagramPacket(buffer, buffer.length); - sock = new DatagramSocket(2333); sock.setSoTimeout(2); sock.receive(p); } catch (SocketTimeoutException e) { success = true; + } finally { + sock.close(); } if (!success) throw new RuntimeException("Socket timeout failure."); diff --git a/jdk/test/java/net/DatagramSocket/SendSize.java b/jdk/test/java/net/DatagramSocket/SendSize.java index e9dc5ed17d7..7ce69a72e77 100644 --- a/jdk/test/java/net/DatagramSocket/SendSize.java +++ b/jdk/test/java/net/DatagramSocket/SendSize.java @@ -32,35 +32,26 @@ * @author Benjamin Renaud */ -import java.io.*; -import java.net.*; -import java.util.*; +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; public class SendSize { - - static final int clientPort = 8989; - static final int serverPort = 9999; static final int bufferLength = 512; static final int packetLength = 256; public static void main(String[] args) throws Exception { - new ServerThread().start(); - new ClientThread().start(); + DatagramSocket serverSocket = new DatagramSocket(); + new ServerThread(serverSocket).start(); + new ClientThread(serverSocket.getLocalPort()).start(); } - static class ServerThread extends Thread { - - int port; DatagramSocket server; - ServerThread(int port) throws IOException { - this.port = port; - this.server = new DatagramSocket(port); - } - - ServerThread() throws IOException { - this(SendSize.serverPort); + ServerThread(DatagramSocket server) { + this.server = server; } public void run() { @@ -85,33 +76,22 @@ public class SendSize { } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("caugth: " + e); + } finally { + if (server != null) { server.close(); } } } } static class ClientThread extends Thread { - int port; int serverPort; - int bufferLength; - int packetLength; - DatagramSocket client; InetAddress host; - ClientThread(int port, int serverPort, - int bufferLength, int packetLength) throws IOException { - this.port = port; + ClientThread(int serverPort)throws IOException { this.serverPort = serverPort; this.host = InetAddress.getLocalHost(); - this.bufferLength = bufferLength; - this.packetLength = packetLength; - this.client = new DatagramSocket(port, host); - } - - ClientThread() throws IOException { - this(SendSize.clientPort, SendSize.serverPort, - SendSize.bufferLength, SendSize.packetLength); + this.client = new DatagramSocket(); } public void run() { @@ -129,6 +109,8 @@ public class SendSize { } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("caught: " + e); + } finally { + if (client != null) { client.close(); } } } } diff --git a/jdk/test/java/net/Inet6Address/B6558853.java b/jdk/test/java/net/Inet6Address/B6558853.java index 04b17615457..cf4adff93dd 100644 --- a/jdk/test/java/net/Inet6Address/B6558853.java +++ b/jdk/test/java/net/Inet6Address/B6558853.java @@ -43,6 +43,9 @@ public class B6558853 implements Runnable { InetAddress dest = null; while (l.hasMoreElements() && dest == null) { NetworkInterface nif = l.nextElement(); + if (!nif.isUp()) + continue; + for (InterfaceAddress a : nif.getInterfaceAddresses()) { if (a.getAddress() instanceof Inet6Address) { Inet6Address a6 = (Inet6Address) a.getAddress(); @@ -53,6 +56,7 @@ public class B6558853 implements Runnable { } } } + System.out.println("Using " + dest); if (dest != null) { B6558853 test = new B6558853(dest, port); Thread thread = new Thread(test); diff --git a/jdk/test/java/net/Inet6Address/serialize/Serialize.java b/jdk/test/java/net/Inet6Address/serialize/Serialize.java index 9dfdd112c13..5fcf774727b 100644 --- a/jdk/test/java/net/Inet6Address/serialize/Serialize.java +++ b/jdk/test/java/net/Inet6Address/serialize/Serialize.java @@ -72,6 +72,7 @@ public class Serialize { File file = new File (System.getProperty("test.src"), "serial1.4.2.ser"); ois = new ObjectInputStream(new FileInputStream(file)); nobj = (Inet6Address) ois.readObject(); + ois.close(); if (!nobj.equals (InetAddress.getByName ("::1"))) { throw new RuntimeException ("old ::1 not deserialized right"); } @@ -90,6 +91,8 @@ public class Serialize { nobj = (Inet6Address) ois.readObject(); } catch (NullPointerException e) { throw new RuntimeException("6656849 Not fixed: NullPointer when deserializing"); + } finally { + ois.close(); } System.out.println(nobj); System.out.println("All tests passed"); @@ -102,6 +105,7 @@ public class Serialize { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("i6a1.ser")); Inet6Address nobj = (Inet6Address) ois.readObject(); + ois.close(); if (nobj.equals(obj)) { return true; diff --git a/jdk/test/java/net/InetAddress/CheckJNI.java b/jdk/test/java/net/InetAddress/CheckJNI.java index fb1e7c25705..2d8efdd4660 100644 --- a/jdk/test/java/net/InetAddress/CheckJNI.java +++ b/jdk/test/java/net/InetAddress/CheckJNI.java @@ -56,6 +56,8 @@ public class CheckJNI { while (ifs.hasMoreElements()) { NetworkInterface nif = (NetworkInterface)ifs.nextElement(); + if (!nif.isUp()) + continue; Enumeration addrs = nif.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr = (InetAddress) addrs.nextElement(); diff --git a/jdk/test/java/net/MulticastSocket/SetOutgoingIf.java b/jdk/test/java/net/MulticastSocket/SetOutgoingIf.java index dd2e3d62706..173b79d1a1b 100644 --- a/jdk/test/java/net/MulticastSocket/SetOutgoingIf.java +++ b/jdk/test/java/net/MulticastSocket/SetOutgoingIf.java @@ -76,6 +76,10 @@ public class SetOutgoingIf { // now determine what (if any) type of addresses are assigned to this interface for (InetAddress addr : Collections.list(nic.getInetAddresses())) { + if (addr.isAnyLocalAddress()) + continue; + + System.out.println(" addr " + addr); if (addr instanceof Inet4Address) { netIf.ipv4Address(true); } else if (addr instanceof Inet6Address) { diff --git a/jdk/test/java/net/NetworkInterface/IPv4Only.java b/jdk/test/java/net/NetworkInterface/IPv4Only.java new file mode 100644 index 00000000000..4d0bc3d404c --- /dev/null +++ b/jdk/test/java/net/NetworkInterface/IPv4Only.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 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. + */ + +/* @test + * @bug 6964714 + * @run main/othervm IPv4Only + * @summary Test the networkinterface listing with java.net.preferIPv4Stack=true. + */ + + +import java.net.*; +import java.util.*; + + +public class IPv4Only { + public static void main(String[] args) throws Exception { + System.setProperty("java.net.preferIPv4Stack","true"); + + Enumeration nifs = NetworkInterface.getNetworkInterfaces(); + while (nifs.hasMoreElements()) { + NetworkInterface nif = nifs.nextElement(); + Enumeration addrs = nif.getInetAddresses(); + while (addrs.hasMoreElements()) { + InetAddress hostAddr = addrs.nextElement(); + if ( hostAddr instanceof Inet6Address ){ + throw new RuntimeException( "NetworkInterfaceV6List failed - found v6 address " + hostAddr.getHostAddress() ); + } + } + } + } +} diff --git a/jdk/test/java/net/ResponseCache/B6181108.java b/jdk/test/java/net/ResponseCache/B6181108.java index 045ba9ac494..8b10d99bd6e 100644 --- a/jdk/test/java/net/ResponseCache/B6181108.java +++ b/jdk/test/java/net/ResponseCache/B6181108.java @@ -67,9 +67,10 @@ public class B6181108 implements Runnable { out.flush(); s.close(); - ss.close(); } catch (Exception e) { e.printStackTrace(); + } finally { + try { ss.close(); } catch (IOException unused) {} } } @@ -100,6 +101,7 @@ public class B6181108 implements Runnable { URLConnection urlc = url.openConnection(); int i = ((HttpURLConnection)(urlc)).getResponseCode(); System.out.println ("response code = " + i); + ResponseCache.setDefault(null); } public static void main(String args[]) throws Exception { diff --git a/jdk/test/java/net/ResponseCache/ResponseCacheTest.java b/jdk/test/java/net/ResponseCache/ResponseCacheTest.java index 7d768d8060e..1e94dcd802e 100644 --- a/jdk/test/java/net/ResponseCache/ResponseCacheTest.java +++ b/jdk/test/java/net/ResponseCache/ResponseCacheTest.java @@ -30,7 +30,6 @@ import java.net.*; import java.util.*; import java.io.*; -import java.nio.*; import sun.net.www.ParseUtil; import javax.net.ssl.*; @@ -43,11 +42,16 @@ public class ResponseCacheTest implements Runnable { static URL url1; static URL url2; static String FNPrefix, OutFNPrefix; + static List streams = new ArrayList<>(); + static List files = new ArrayList<>(); + /* * Our "http" server to return a 404 */ public void run() { + Socket s = null; + FileInputStream fis = null; try { - Socket s = ss.accept(); + s = ss.accept(); InputStream is = s.getInputStream (); BufferedReader r = new BufferedReader(new InputStreamReader(is)); @@ -68,7 +72,7 @@ public class ResponseCacheTest implements Runnable { out.print("Content-Length: "+file2.length()+"\r\n"); out.print("Connection: close\r\n"); out.print("\r\n"); - FileInputStream fis = new FileInputStream(file2); + fis = new FileInputStream(file2); byte[] buf = new byte[(int)file2.length()]; int len; while ((len = fis.read(buf)) != -1) { @@ -81,6 +85,10 @@ public class ResponseCacheTest implements Runnable { ss.close(); } catch (Exception e) { e.printStackTrace(); + } finally { + try { ss.close(); } catch (IOException unused) {} + try { s.close(); } catch (IOException unused) {} + try { fis.close(); } catch (IOException unused) {} } } static class NameVerifier implements HostnameVerifier { @@ -144,11 +152,14 @@ static class NameVerifier implements HostnameVerifier { // assert (headers1 == headers2 && file1 == file2.2) File file1 = new File(OutFNPrefix+"file1"); File file2 = new File(OutFNPrefix+"file2.2"); + files.add(file1); + files.add(file2); System.out.println("headers1"+headers1+"\nheaders2="+headers2); if (!headers1.equals(headers2) || file1.length() != file2.length()) { throw new RuntimeException("test failed"); } } + public static void main(String args[]) throws Exception { try { ResponseCache.setDefault(new MyResponseCache()); @@ -157,6 +168,12 @@ static class NameVerifier implements HostnameVerifier { new ResponseCacheTest(); } finally{ ResponseCache.setDefault(null); + for (Closeable c: streams) { + try { c.close(); } catch (IOException unused) {} + } + for (File f: files) { + f.delete(); + } } } @@ -184,6 +201,7 @@ static class NameVerifier implements HostnameVerifier { public MyCacheResponse(String filename) { try { fis = new FileInputStream(new File(filename)); + streams.add(fis); ObjectInputStream ois = new ObjectInputStream(fis); headers = (Map>)ois.readObject(); } catch (Exception ex) { @@ -206,6 +224,8 @@ static class NameVerifier implements HostnameVerifier { try { File file = new File(filename); fos = new FileOutputStream(file); + streams.add(fos); + files.add(file); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(rspHeaders); } catch (Exception ex) { diff --git a/jdk/test/java/net/ResponseCache/getResponseCode.java b/jdk/test/java/net/ResponseCache/getResponseCode.java index 02f0f565d28..b5a4d0c2e04 100644 --- a/jdk/test/java/net/ResponseCache/getResponseCode.java +++ b/jdk/test/java/net/ResponseCache/getResponseCode.java @@ -39,6 +39,7 @@ import java.io.*; public class getResponseCode { static URL url; static String FNPrefix; + static List resources = new ArrayList<>(); getResponseCode() throws Exception { url = new URL("http://localhost/file1.cache"); @@ -57,6 +58,9 @@ public class getResponseCode { new getResponseCode(); } finally{ ResponseCache.setDefault(null); + for (Closeable c : resources) { + try { c.close(); } catch (IOException unused) {} + } } } @@ -77,6 +81,7 @@ public class getResponseCode { public MyResponse(String filename) { try { fis = new FileInputStream(new File(filename)); + resources.add(fis); headers = (Map>)new ObjectInputStream(fis).readObject(); } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); diff --git a/jdk/test/java/net/Socket/AccurateTimeout.java b/jdk/test/java/net/Socket/AccurateTimeout.java deleted file mode 100644 index 81a664d31b3..00000000000 --- a/jdk/test/java/net/Socket/AccurateTimeout.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2002, 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 - * @bug 4512028 - * @summary Check the tolerance on read timeouts. - */ -import java.net.*; -import java.io.*; - -public class AccurateTimeout { - - static final int TOLERANCE = 100; - - static boolean skipTest() { - String os = System.getProperty("os.name"); - if (os.equals("Windows 95") || - os.equals("Windows 98") || - os.equals("Windows Me")) { - - System.out.println("Due to an OS bug timeout tolerance cannot be tested on this OS"); - return true; - } - return false; - } - - public static void main(String args[]) throws Exception { - - if (skipTest()) { - return; - } - - int failures = 0; - int timeout; - - System.out.println(""); - System.out.println("Testing Socket.getInputStream().read() ..."); - System.out.println(""); - - ServerSocket ss = new ServerSocket(0); - Socket s1 = new Socket(InetAddress.getLocalHost(), ss.getLocalPort()); - Socket s2 = ss.accept(); - - InputStream in = s1.getInputStream(); - - timeout = 100; - while (timeout < 2500) { - s1.setSoTimeout(timeout); - - long startTime = System.currentTimeMillis(); - try { - in.read(); - } catch (SocketTimeoutException e) { - } - long actual = System.currentTimeMillis() - startTime; - - System.out.print("excepted: " + timeout + " actual: " + actual); - - if (Math.abs(actual-timeout) > TOLERANCE) { - System.out.print(" *** FAIL: outside tolerance"); - failures++; - } else { - System.out.print(" PASS."); - } - - System.out.println(""); - timeout += 200; - } - - s1.close(); - s2.close(); - ss.close(); - - - // ---------- - - - System.out.println(""); - System.out.println("Testing DatagramSocket.receive ..."); - System.out.println(""); - - byte b[] = new byte[8]; - DatagramPacket p = new DatagramPacket(b, b.length); - - DatagramSocket ds = new DatagramSocket(); - - timeout = 100; - while (timeout < 2500) { - ds.setSoTimeout(timeout); - - long startTime = System.currentTimeMillis(); - try { - ds.receive(p); - } catch (SocketTimeoutException e) { - } - long actual = System.currentTimeMillis() - startTime; - - System.out.print("excepted: " + timeout + " actual: " + actual); - - if (Math.abs(actual-timeout) > TOLERANCE) { - System.out.print(" *** FAIL: outside tolerance"); - failures++; - } else { - System.out.print(" PASS."); - } - - System.out.println(""); - timeout += 200; - } - - ds.close(); - - System.out.println(""); - - // --------- - - if (failures > 0) { - throw new Exception("Test failed: " + failures + - " test(s) outside tolerance"); - } - - } - -} diff --git a/jdk/test/java/net/Socket/CloseAvailable.java b/jdk/test/java/net/Socket/CloseAvailable.java index d7f20828098..5e9fd5c97b3 100644 --- a/jdk/test/java/net/Socket/CloseAvailable.java +++ b/jdk/test/java/net/Socket/CloseAvailable.java @@ -47,6 +47,7 @@ public class CloseAvailable implements Runnable { t.start(); Socket soc = ss.accept(); + ss.close(); DataInputStream is = new DataInputStream(soc.getInputStream()); is.close(); @@ -64,7 +65,7 @@ public class CloseAvailable implements Runnable { public void run() { try { Socket s = new Socket(addr, port); - + s.close(); } catch (Exception e) { e.printStackTrace(); } diff --git a/jdk/test/java/net/Socket/DeadlockTest.java b/jdk/test/java/net/Socket/DeadlockTest.java index ff601c71936..a5d7751f5fd 100644 --- a/jdk/test/java/net/Socket/DeadlockTest.java +++ b/jdk/test/java/net/Socket/DeadlockTest.java @@ -33,29 +33,32 @@ import java.io.*; public class DeadlockTest { public static void main(String [] argv) throws Exception { + ServerSocket ss = new ServerSocket(0); + Socket clientSocket = new Socket(); - // Start the server thread - Thread s1 = new Thread(new ServerThread()); - s1.start(); + try { + // Start the server thread + Thread s1 = new Thread(new ServerThread(ss)); + s1.start(); - // Sleep to make sure s1 has created a server socket - Thread.sleep(1000); + // Start the client thread + ClientThread ct = new ClientThread(clientSocket, ss.getLocalPort()); + Thread c1 = new Thread(ct); + c1.start(); - // Start the client thread - ClientThread ct = new ClientThread(); - Thread c1 = new Thread(ct); - c1.start(); + // Wait for the client thread to finish + c1.join(20000); - // Wait for the client thread to finish - c1.join(40000); - - // If timeout, we assume there is a deadlock - if (c1.isAlive() == true) { - // Close the socket to force the server thread - // terminate too - s1.stop(); - ct.getSock().close(); - throw new Exception("Takes too long. Dead lock"); + // If timeout, we assume there is a deadlock + if (c1.isAlive() == true) { + // Close the socket to force the server thread + // terminate too + s1.stop(); + throw new Exception("Takes too long. Dead lock"); + } + } finally { + ss.close(); + clientSocket.close(); } } } @@ -71,8 +74,8 @@ class ServerThread implements Runnable { Socket sock; - public ServerThread() throws Exception { - + public ServerThread(ServerSocket serverSocket) throws Exception { + this.server = serverSocket; } public void ping(int cnt) { @@ -85,7 +88,6 @@ class ServerThread implements Runnable { try { if (Thread.currentThread().getName().startsWith("child") == false) { - server = new ServerSocket(4711); sock = server.accept(); new Thread(this, "child").start(); @@ -107,6 +109,7 @@ class ServerThread implements Runnable { } } catch (Throwable e) { + System.out.println(e); // If anything goes wrong, just quit. } @@ -141,10 +144,11 @@ class ClientThread implements Runnable { Socket sock; - public ClientThread() throws Exception { + public ClientThread(Socket sock, int serverPort) throws Exception { try { - System.out.println("About to create a socket"); - sock = new Socket(InetAddress.getLocalHost().getHostName(), 4711); + System.out.println("About to connect the client socket"); + this.sock = sock; + this.sock.connect(new InetSocketAddress("localhost", serverPort)); System.out.println("connected"); out = new ObjectOutputStream(sock.getOutputStream()); @@ -156,10 +160,6 @@ class ClientThread implements Runnable { } } - public Socket getSock() { - return sock; - } - private int cnt = 1; public void run() { @@ -213,6 +213,7 @@ class Message implements java.io.Serializable { System.out.println("write message done " + cnt++); } catch (IOException ioe) { // Ignore the exception + System.out.println(ioe); } } } diff --git a/jdk/test/java/net/Socket/LingerTest.java b/jdk/test/java/net/Socket/LingerTest.java index 600dbd7db40..c84e153116b 100644 --- a/jdk/test/java/net/Socket/LingerTest.java +++ b/jdk/test/java/net/Socket/LingerTest.java @@ -81,7 +81,7 @@ public class LingerTest { public void run() { System.out.println ("Another starts"); try { - Thread.currentThread().sleep(delay); + Thread.sleep(delay); Socket s = new Socket("localhost", port); synchronized (this) { connected = true; @@ -105,7 +105,6 @@ public class LingerTest { Socket s1 = new Socket("localhost", ss.getLocalPort()); Socket s2 = ss.accept(); - // setup conditions for untransmitted data and lengthy // linger interval s1.setSendBufferSize(128*1024); @@ -122,14 +121,15 @@ public class LingerTest { thr.start(); // give sender time to queue the data - Thread.currentThread().sleep(1000); + Thread.sleep(1000); // close the socket asynchronously (new Thread(new Closer(s1))).start(); // give another time to run - Thread.currentThread().sleep(10000); + Thread.sleep(10000); + ss.close(); // check that another is done if (!another.connected()) { throw new RuntimeException("Another thread is blocked"); diff --git a/jdk/test/java/net/Socket/LinkLocal.java b/jdk/test/java/net/Socket/LinkLocal.java index 1d3288bdcf1..8a0aea287b0 100644 --- a/jdk/test/java/net/Socket/LinkLocal.java +++ b/jdk/test/java/net/Socket/LinkLocal.java @@ -58,11 +58,10 @@ public class LinkLocal { } catch (SocketException e) { failed++; System.out.println("Test failed: " + e); + } finally { + s.close(); + ss.close(); } - - // clean up - s.close(); - ss.close(); } static void UdpTest(InetAddress ia, boolean connected) throws Exception { @@ -93,16 +92,16 @@ public class LinkLocal { ds1.send(p); System.out.println("Packet has been sent."); - ds2.setSoTimeout(1000); + ds2.setSoTimeout(5000); ds2.receive(p); System.out.println("Test passed - packet received."); } catch (SocketException e) { failed++; System.out.println("Test failed: " + e); + } finally { + ds1.close(); + ds2.close(); } - - ds1.close(); - ds2.close(); } static void TestAddress(InetAddress ia) throws Exception { @@ -138,6 +137,9 @@ public class LinkLocal { Enumeration nifs = NetworkInterface.getNetworkInterfaces(); while (nifs.hasMoreElements()) { NetworkInterface ni = (NetworkInterface)nifs.nextElement(); + if (!ni.isUp()) + continue; + Enumeration addrs = ni.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr = (InetAddress)addrs.nextElement(); diff --git a/jdk/test/java/net/Socket/ProxyCons.java b/jdk/test/java/net/Socket/ProxyCons.java index 901638ec280..da80337070d 100644 --- a/jdk/test/java/net/Socket/ProxyCons.java +++ b/jdk/test/java/net/Socket/ProxyCons.java @@ -39,6 +39,7 @@ public class ProxyCons { public void run () { try { Socket s = server.accept (); + s.close(); while (!finished ()) { Thread.sleep (500); } @@ -58,10 +59,9 @@ public class ProxyCons { public ProxyCons() { } - void test() { + void test() throws Exception { + ServerSocket ss = new ServerSocket(0); try { - ServerSocket ss = new ServerSocket(); - ss.bind(new InetSocketAddress(0)); Server s = new Server(ss); s.start(); Socket sock = new Socket(Proxy.NO_PROXY); @@ -70,10 +70,12 @@ public class ProxyCons { sock.close(); } catch (java.io.IOException e) { throw new RuntimeException(e); + } finally { + ss.close(); } } - public static void main(String[] args) { + public static void main(String[] args) throws Exception { ProxyCons c = new ProxyCons(); c.test(); } diff --git a/jdk/test/java/net/Socket/ReadTimeout.java b/jdk/test/java/net/Socket/ReadTimeout.java index 26097827efb..89fe4150466 100644 --- a/jdk/test/java/net/Socket/ReadTimeout.java +++ b/jdk/test/java/net/Socket/ReadTimeout.java @@ -44,7 +44,7 @@ public class ReadTimeout { sin = InetAddress.getLocalHost(); srv = new ServerSocket(port); port = srv.getLocalPort(); - soc = new Socket(sin, port, true); + soc = new Socket(sin, port); soc1 = srv.accept(); soc.setSoTimeout(tout); @@ -53,10 +53,10 @@ public class ReadTimeout { os = soc1.getOutputStream(); is.read(); } catch(InterruptedIOException e) { + } finally { + soc.close(); + soc1.close(); + srv.close(); } - - soc.close(); - soc1.close(); - srv.close(); } } diff --git a/jdk/test/java/net/Socket/SetReceiveBufferSize.java b/jdk/test/java/net/Socket/SetReceiveBufferSize.java index 562010d48ef..fa5302a4882 100644 --- a/jdk/test/java/net/Socket/SetReceiveBufferSize.java +++ b/jdk/test/java/net/Socket/SetReceiveBufferSize.java @@ -32,29 +32,14 @@ import java.net.Socket; import java.net.ServerSocket; public class SetReceiveBufferSize { - class Server extends Thread { - private ServerSocket ss; - public Server(ServerSocket ss) { - this.ss = ss; - } - - public void run() { - try { - ss.accept(); - } catch (Exception e) { - } - } - } - public static void main(String[] args) throws Exception { SetReceiveBufferSize s = new SetReceiveBufferSize(); } public SetReceiveBufferSize() throws Exception { ServerSocket ss = new ServerSocket(0); - Server serv = new Server(ss); - serv.start(); Socket s = new Socket("localhost", ss.getLocalPort()); + Socket accepted = ss.accept(); try { s.setReceiveBufferSize(0); } catch (IllegalArgumentException e) { @@ -62,6 +47,8 @@ public class SetReceiveBufferSize { } catch (Exception ex) { } finally { ss.close(); + s.close(); + accepted.close(); } throw new RuntimeException("IllegalArgumentException not thrown!"); } diff --git a/jdk/test/java/net/Socket/SetSoLinger.java b/jdk/test/java/net/Socket/SetSoLinger.java index 97351f35212..f2eaff43823 100644 --- a/jdk/test/java/net/Socket/SetSoLinger.java +++ b/jdk/test/java/net/Socket/SetSoLinger.java @@ -30,36 +30,24 @@ import java.net.*; -public class SetSoLinger implements Runnable { - static ServerSocket ss; - static InetAddress addr; - static int port; +public class SetSoLinger { + static final int LINGER = 65546; public static void main(String args[]) throws Exception { - boolean error = true; - int linger = 65546; - int value = 0; - addr = InetAddress.getLocalHost(); - ss = new ServerSocket(0); - port = ss.getLocalPort(); + int value; + InetAddress addr = InetAddress.getLocalHost(); + ServerSocket ss = new ServerSocket(0); + int port = ss.getLocalPort(); - Thread t = new Thread(new SetSoLinger()); - t.start(); + Socket s = new Socket(addr, port); Socket soc = ss.accept(); - soc.setSoLinger(true, linger); + soc.setSoLinger(true, LINGER); value = soc.getSoLinger(); soc.close(); + s.close(); + ss.close(); if(value != 65535) throw new RuntimeException("Failed. Value not properly reduced."); } - - public void run() { - try { - Socket s = new Socket(addr, port); - } catch (Exception e) { - e.printStackTrace(); - } - } - } diff --git a/jdk/test/java/net/Socket/ShutdownBoth.java b/jdk/test/java/net/Socket/ShutdownBoth.java index bf19924e051..99281c76e1a 100644 --- a/jdk/test/java/net/Socket/ShutdownBoth.java +++ b/jdk/test/java/net/Socket/ShutdownBoth.java @@ -36,12 +36,14 @@ public class ShutdownBoth { Socket s1 = new Socket(ss.getInetAddress(), ss.getLocalPort()); Socket s2 = ss.accept(); - s1.shutdownInput(); - s1.shutdownOutput(); // failed b55 - - s1.close(); - s2.close(); - ss.close(); + try { + s1.shutdownInput(); + s1.shutdownOutput(); // failed b55 + } finally { + s1.close(); + s2.close(); + ss.close(); + } } } diff --git a/jdk/test/java/net/Socket/SoTimeout.java b/jdk/test/java/net/Socket/SoTimeout.java index 1273d968c12..0b1e448523d 100644 --- a/jdk/test/java/net/Socket/SoTimeout.java +++ b/jdk/test/java/net/Socket/SoTimeout.java @@ -52,9 +52,10 @@ public class SoTimeout implements Runnable { t.start(); Socket s = serverSocket.accept(); + serverSocket.close(); - // set a 1 second timeout on the socket - s.setSoTimeout(1000); + // set a 5 second timeout on the socket + s.setSoTimeout(5000); s.getInputStream().read(b, 0, b.length); s.close(); @@ -64,7 +65,7 @@ public class SoTimeout implements Runnable { // this sequence should complete fairly quickly and if it // takes something resembling the the SoTimeout value then // we are probably incorrectly blocking and not waking up - if (waited > 500) { + if (waited > 2000) { throw new Exception("shouldn't take " + waited + " to complete"); } } diff --git a/jdk/test/java/net/Socket/Timeout.java b/jdk/test/java/net/Socket/Timeout.java index 653db8f726a..31471acfc1a 100644 --- a/jdk/test/java/net/Socket/Timeout.java +++ b/jdk/test/java/net/Socket/Timeout.java @@ -31,18 +31,16 @@ import java.net.*; import java.io.*; public class Timeout { - - public static ServerSocket sock; - public static void main(String[] args) throws Exception { boolean success = false; + ServerSocket sock = new ServerSocket(0); try { - ServerSocket sock; - sock = new ServerSocket(2333); sock.setSoTimeout(2); sock.accept(); } catch (InterruptedIOException e) { success = true; + } finally { + sock.close(); } if (!success) throw new RuntimeException("Socket timeout failure."); diff --git a/jdk/test/java/net/Socket/UrgentDataTest.java b/jdk/test/java/net/Socket/UrgentDataTest.java index 7b6a8dca187..d63bc5cb805 100644 --- a/jdk/test/java/net/Socket/UrgentDataTest.java +++ b/jdk/test/java/net/Socket/UrgentDataTest.java @@ -90,63 +90,64 @@ public class UrgentDataTest { } public void run () throws Exception { - if (isClient) { - client = new Socket (clHost, clPort); - clis = client.getInputStream(); - clos = client.getOutputStream(); - client.setOOBInline (true); - if (client.getOOBInline() != true) { - throw new RuntimeException ("Setting OOBINLINE failed"); - } - } - if (isServer) { - server = listener.accept (); - sis = server.getInputStream(); - sos = server.getOutputStream(); - } - if (isClient) { - clos.write ("Hello".getBytes ()); - client.sendUrgentData (100); - clos.write ("world".getBytes ()); - } - // read Hello world from server (during which oob byte must have been dropped) - String s = "Helloworld"; - if (isServer) { - for (int y=0; y= 0) { throw ioe; } + } finally { + server.close(); } - server.close(); } } diff --git a/jdk/test/java/net/Socket/setReuseAddress/Restart.java b/jdk/test/java/net/Socket/setReuseAddress/Restart.java index 90c2a1810d2..08bb5af2f62 100644 --- a/jdk/test/java/net/Socket/setReuseAddress/Restart.java +++ b/jdk/test/java/net/Socket/setReuseAddress/Restart.java @@ -39,27 +39,28 @@ public class Restart { */ public static void main(String args[]) throws Exception { + ServerSocket ss = new ServerSocket(0); + Socket s1 = null, s2 = null; + try { + int port = ss.getLocalPort(); - InetSocketAddress isa = new InetSocketAddress(0); - ServerSocket ss = new ServerSocket(); - ss.bind(isa); + s1 = new Socket(InetAddress.getLocalHost(), port); + s2 = ss.accept(); - int port = ss.getLocalPort(); + // close server socket and the accepted connection + ss.close(); + s2.close(); - Socket s1 = new Socket(InetAddress.getLocalHost(), port); - Socket s2 = ss.accept(); + ss = new ServerSocket(); + ss.bind( new InetSocketAddress(port) ); + ss.close(); - // close server socket and the accepted connection - ss.close(); - s2.close(); - - boolean failed = false; - - ss = new ServerSocket(); - ss.bind( new InetSocketAddress(port) ); - ss.close(); - - // close the client socket - s1.close(); + // close the client socket + s1.close(); + } finally { + if (ss != null) ss.close(); + if (s1 != null) s1.close(); + if (s2 != null) s2.close(); + } } } diff --git a/jdk/test/java/net/SocketInputStream/SocketClosedException.java b/jdk/test/java/net/SocketInputStream/SocketClosedException.java index b116cd21d0b..cf141863a53 100644 --- a/jdk/test/java/net/SocketInputStream/SocketClosedException.java +++ b/jdk/test/java/net/SocketInputStream/SocketClosedException.java @@ -32,68 +32,37 @@ import java.io.*; import java.net.*; public class SocketClosedException { - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ static void doServerSide() throws Exception { - ServerSocket serverSocket = new ServerSocket(serverPort); - serverPort = serverSocket.getLocalPort(); + try { + Socket socket = serverSocket.accept(); - /* - * Signal Client, we're ready for a connect. - */ - serverReady = true; + OutputStream os = socket.getOutputStream(); - Socket socket = serverSocket.accept(); - - InputStream is = socket.getInputStream(); - OutputStream os = socket.getOutputStream(); - - os.write(85); - os.flush(); - socket.close(); - } - - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - static void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(5000); + os.write(85); + os.flush(); + socket.close(); + } finally { + serverSocket.close(); } - - Socket socket = new Socket("localhost", serverPort); - InputStream is = socket.getInputStream(); - OutputStream os = socket.getOutputStream(); - - int read = is.read(); - socket.close(); - read = is.read(); } - static int serverPort = 0; + static void doClientSide(int port) throws Exception { + Socket socket = new Socket("localhost", port); + InputStream is = socket.getInputStream(); + + is.read(); + socket.close(); + is.read(); + } + + static ServerSocket serverSocket; static Exception serverException = null; public static void main(String[] args) throws Exception { + serverSocket = new ServerSocket(0); startServer(); try { - doClientSide(); + doClientSide(serverSocket.getLocalPort()); } catch (SocketException e) { if (!e.getMessage().equalsIgnoreCase("Socket closed")) { throw new Exception("Received a wrong exception message: " + @@ -108,21 +77,14 @@ public class SocketClosedException { } static void startServer() { - Thread serverThread = new Thread() { + (new Thread() { public void run() { try { doServerSide(); } catch (Exception e) { - /* - * server thread just died. - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; + e.printStackTrace(); } } - }; - serverThread.start(); + }).start(); } } diff --git a/jdk/test/java/net/SocketInputStream/SocketTimeout.java b/jdk/test/java/net/SocketInputStream/SocketTimeout.java index 37d84162fa7..ad4c70acbbf 100644 --- a/jdk/test/java/net/SocketInputStream/SocketTimeout.java +++ b/jdk/test/java/net/SocketInputStream/SocketTimeout.java @@ -31,26 +31,24 @@ import java.net.*; import java.io.*; public class SocketTimeout { + static final int TIMEOUT = 1000; + public static void main(String args[]) throws Exception { - InetAddress sin = null; + InetAddress sin = InetAddress.getLocalHost(); Socket soc = null,soc1 = null; InputStream is = null; - OutputStream os = null; ServerSocket srv = null; int port = 0; - int tout = 1000; - sin = InetAddress.getLocalHost(); - srv = new ServerSocket(port); + srv = new ServerSocket(0); port = srv.getLocalPort(); soc = new Socket(sin, port); soc1 = srv.accept(); - soc.setSoTimeout(tout); - srv.setSoTimeout(tout); + soc.setSoTimeout(TIMEOUT); + srv.setSoTimeout(TIMEOUT); try { is = soc.getInputStream(); - os = soc1.getOutputStream(); is.read(); } catch(InterruptedIOException e) { try { @@ -59,6 +57,9 @@ public class SocketTimeout { } catch(NoClassDefFoundError e1) { throw new Exception ("SocketTimeoutException: not found"); } + } finally { + soc.close(); + soc1.close(); } // now check accept @@ -72,12 +73,14 @@ public class SocketTimeout { } catch(NoClassDefFoundError e1) { throw new Exception ("SocketTimeoutException: not found"); } + } finally { + srv.close(); } // Now check DatagramSocket.receive() DatagramSocket dg = new DatagramSocket (); - dg.setSoTimeout (tout); + dg.setSoTimeout (TIMEOUT); try { dg.receive (new DatagramPacket (new byte [64], 64)); @@ -88,11 +91,8 @@ public class SocketTimeout { } catch(NoClassDefFoundError e1) { throw new Exception ("SocketTimeoutException: not found"); } + } finally { + dg.close(); } - - soc.close(); - soc1.close(); - srv.close(); - dg.close(); } } diff --git a/jdk/test/java/net/URL/GetContent.java b/jdk/test/java/net/URL/GetContent.java index b913cfe0779..aa32da29bd3 100644 --- a/jdk/test/java/net/URL/GetContent.java +++ b/jdk/test/java/net/URL/GetContent.java @@ -53,11 +53,13 @@ public class GetContent implements Runnable { // wait for client to read response - otherwise http // client get error and re-establish connection - Thread.currentThread().sleep(2000); + Thread.sleep(2000); s.close(); } catch (Exception e) { e.printStackTrace(); + } finally { + try { ss.close(); } catch (IOException unused) {} } } @@ -81,8 +83,6 @@ public class GetContent implements Runnable { error = false; } - ss.close(); - if (error) throw new RuntimeException("No IOException generated."); } diff --git a/jdk/test/java/net/URLClassLoader/ClassLoad.java b/jdk/test/java/net/URLClassLoader/ClassLoad.java index b9aa687b4cc..c23073f93bf 100644 --- a/jdk/test/java/net/URLClassLoader/ClassLoad.java +++ b/jdk/test/java/net/URLClassLoader/ClassLoad.java @@ -27,20 +27,45 @@ * @summary Test for FileNotFoundException when loading bogus class */ -import java.net.*; -import java.io.*; +import java.io.InputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URL; +import java.net.URLClassLoader; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; public class ClassLoad { public static void main(String[] args) throws Exception { boolean error = true; + + // Start a dummy server to return 404 + HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); + HttpHandler handler = new HttpHandler() { + public void handle(HttpExchange t) throws IOException { + InputStream is = t.getRequestBody(); + while (is.read() != -1); + t.sendResponseHeaders (404, -1); + t.close(); + } + }; + server.createContext("/", handler); + server.start(); + + // Client request try { - URL url = new URL(args.length >= 1 ? args[0] : "http://jini.east/"); + URL url = new URL("http://localhost:" + server.getAddress().getPort()); String name = args.length >= 2 ? args[1] : "foo.bar.Baz"; ClassLoader loader = new URLClassLoader(new URL[] { url }); + System.out.println(url); Class c = loader.loadClass(name); System.out.println("Loaded class \"" + c.getName() + "\"."); } catch (ClassNotFoundException ex) { + System.out.println(ex); error = false; + } finally { + server.stop(0); } if (error) throw new RuntimeException("No ClassNotFoundException generated"); diff --git a/jdk/test/java/net/URLConnection/DisconnectAfterEOF.java b/jdk/test/java/net/URLConnection/DisconnectAfterEOF.java index 927fedfd91d..0a3814794b7 100644 --- a/jdk/test/java/net/URLConnection/DisconnectAfterEOF.java +++ b/jdk/test/java/net/URLConnection/DisconnectAfterEOF.java @@ -56,7 +56,6 @@ public class DisconnectAfterEOF { int cl = -1; int remaining = -1; StringBuffer sb = new StringBuffer(); - Random r = new Random(); boolean close = false; boolean inBody = false; @@ -239,8 +238,6 @@ public class DisconnectAfterEOF { } public static void main(String args[]) throws Exception { - Random r = new Random(); - // start server ServerSocket ss = new ServerSocket(0); Server svr = new Server(ss); @@ -273,7 +270,7 @@ public class DisconnectAfterEOF { URLConnection uc1 = doRequest(uri); doResponse(uc1); - Thread.currentThread().sleep(2000); + Thread.sleep(2000); URLConnection uc2 = doRequest(uri); diff --git a/jdk/test/java/net/URLConnection/HandleContentTypeWithAttrs.java b/jdk/test/java/net/URLConnection/HandleContentTypeWithAttrs.java index 3cad25dbe0c..50fcd388f16 100644 --- a/jdk/test/java/net/URLConnection/HandleContentTypeWithAttrs.java +++ b/jdk/test/java/net/URLConnection/HandleContentTypeWithAttrs.java @@ -111,9 +111,8 @@ class myHttpServer implements Runnable, Cloneable { } catch(Exception e) { System.out.print("Server failure\n"); e.printStackTrace(); - try { - serverSocket.close(); - } catch(IOException e2) {} + } finally { + try { serverSocket.close(); } catch(IOException unused) {} } } else { try { @@ -127,10 +126,9 @@ class myHttpServer implements Runnable, Cloneable { } catch(Exception e) { // System.out.print("Service handler failure\n"); // e.printStackTrace(); + } finally { + try { close(); } catch(IOException unused) {} } - try { - close(); - } catch(IOException e2) {} } } diff --git a/jdk/test/java/net/URLConnection/HttpContinueStackOverflow.java b/jdk/test/java/net/URLConnection/HttpContinueStackOverflow.java index 8d9aab013ff..502adf9fae4 100644 --- a/jdk/test/java/net/URLConnection/HttpContinueStackOverflow.java +++ b/jdk/test/java/net/URLConnection/HttpContinueStackOverflow.java @@ -30,7 +30,7 @@ */ import java.io.BufferedReader; import java.io.InputStreamReader; -import java.io.OutputStreamWriter; +import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; @@ -41,61 +41,56 @@ public class HttpContinueStackOverflow { static class Server implements Runnable { int port; + ServerSocket serverSock ; - Server(int port) { - this.port = port; + Server() throws IOException { + serverSock = new ServerSocket(0); + } + + int getLocalPort() { + return serverSock.getLocalPort(); } public void run() { + Socket sock = null; try { - /* bind to port and wait for connection */ - ServerSocket serverSock = new ServerSocket( port ); serverSock.setSoTimeout(10000); - Socket sock = serverSock.accept(); + sock = serverSock.accept(); /* setup streams and read http request */ BufferedReader in = new BufferedReader( new InputStreamReader(sock.getInputStream())); PrintStream out = new PrintStream( sock.getOutputStream() ); - String request = in.readLine(); + in.readLine(); /* send continue followed by invalid response */ out.println("HTTP/1.1 100 Continue\r"); out.println("\r"); out.println("junk junk junk"); out.flush(); - - sock.close(); } catch (Exception e) { e.printStackTrace(); + } finally { + try { serverSock.close(); } catch (IOException unused) {} + try { sock.close(); } catch (IOException unused) {} } } } - HttpContinueStackOverflow(int port) throws Exception { + HttpContinueStackOverflow() throws Exception { /* create the server */ - Server s = new Server(port); - Thread thr = new Thread(s); - thr.start(); - - /* wait for server to bind to port */ - try { - Thread.currentThread().sleep(2000); - } catch (Exception e) { } + Server s = new Server(); + (new Thread(s)).start(); /* connect to server, connect to server and get response code */ - URL url = new URL("http", "localhost", port, "anything.html"); + URL url = new URL("http", "localhost", s.getLocalPort(), "anything.html"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); - int respCode = conn.getResponseCode(); + conn.getResponseCode(); System.out.println("TEST PASSED"); } public static void main(String args[]) throws Exception { - int port = 4090; - if (args.length > 0) { - port = Integer.parseInt(args[0]); - } System.out.println("Testing 100-Continue"); - new HttpContinueStackOverflow(port); + new HttpContinueStackOverflow(); } } diff --git a/jdk/test/java/net/URLConnection/Redirect307Test.java b/jdk/test/java/net/URLConnection/Redirect307Test.java index b0a85e14df5..37f044edac1 100644 --- a/jdk/test/java/net/URLConnection/Redirect307Test.java +++ b/jdk/test/java/net/URLConnection/Redirect307Test.java @@ -37,11 +37,11 @@ class RedirServer extends Thread { OutputStream os; int port; - String reply1 = "HTTP/1.1 307 Temporary Redirect\r\n" + + String reply1Part1 = "HTTP/1.1 307 Temporary Redirect\r\n" + "Date: Mon, 15 Jan 2001 12:18:21 GMT\r\n" + "Server: Apache/1.3.14 (Unix)\r\n" + "Location: http://localhost:"; - String reply2 = "/redirected.html\r\n" + + String reply1Part2 = "/redirected.html\r\n" + "Connection: close\r\n" + "Content-Type: text/html; charset=iso-8859-1\r\n\r\n" + "Hello"; @@ -49,9 +49,10 @@ class RedirServer extends Thread { RedirServer (ServerSocket y) { s = y; port = s.getLocalPort(); + System.out.println("Server created listening on " + port); } - String reply3 = "HTTP/1.1 200 Ok\r\n" + + String reply2 = "HTTP/1.1 200 Ok\r\n" + "Date: Mon, 15 Jan 2001 12:18:21 GMT\r\n" + "Server: Apache/1.3.14 (Unix)\r\n" + "Connection: close\r\n" + @@ -64,16 +65,24 @@ class RedirServer extends Thread { is = s1.getInputStream (); os = s1.getOutputStream (); is.read (); - String reply = reply1 + port + reply2; + String reply = reply1Part1 + port + reply1Part2; os.write (reply.getBytes()); + os.close(); /* wait for redirected connection */ s.setSoTimeout (5000); s1 = s.accept (); + is = s1.getInputStream (); os = s1.getOutputStream (); - os.write (reply3.getBytes()); + is.read(); + os.write (reply2.getBytes()); + os.close(); } catch (Exception e) { /* Just need thread to terminate */ + System.out.println("Server: caught " + e); + e.printStackTrace(); + } finally { + try { s.close(); } catch (IOException unused) {} } } }; @@ -84,10 +93,7 @@ public class Redirect307Test { public static final int DELAY = 10; public static void main(String[] args) throws Exception { - int nLoops = 1; - int nSize = 10; - int port, n =0; - byte b[] = new byte[nSize]; + int port; RedirServer server; ServerSocket sock; @@ -119,7 +125,8 @@ public class Redirect307Test { } } catch(IOException e) { - throw new RuntimeException ("Exception caught"); + e.printStackTrace(); + throw new RuntimeException ("Exception caught + " + e); } } } diff --git a/jdk/test/java/net/URLConnection/RedirectLimit.java b/jdk/test/java/net/URLConnection/RedirectLimit.java index 979a938b99c..b0ef22b94d9 100644 --- a/jdk/test/java/net/URLConnection/RedirectLimit.java +++ b/jdk/test/java/net/URLConnection/RedirectLimit.java @@ -76,15 +76,19 @@ class RedirLimitServer extends Thread { is.read (); String reply = reply1 + port + "/redirect" + i + reply2; os.write (reply.getBytes()); + os.close(); } s1 = s.accept (); is = s1.getInputStream (); os = s1.getOutputStream (); is.read (); os.write (reply3.getBytes()); + os.close(); } catch (Exception e) { /* Just need thread to terminate */ + } finally { + try { s.close(); } catch (IOException unused) {} } } }; diff --git a/jdk/test/java/net/URLConnection/ResendPostBody.java b/jdk/test/java/net/URLConnection/ResendPostBody.java index 8bdd5fa09a9..99331584bb5 100644 --- a/jdk/test/java/net/URLConnection/ResendPostBody.java +++ b/jdk/test/java/net/URLConnection/ResendPostBody.java @@ -109,8 +109,11 @@ public class ResendPostBody { while (!finished()) { Thread.sleep (1000); } + out.close(); } catch (Exception e) { System.err.println ("Server Exception: " + e); + } finally { + try { server.close(); } catch (IOException unused) {} } } } @@ -134,7 +137,7 @@ public class ResendPostBody { public void execute () throws Exception { - byte b[] = "X=ABCDEFGHZZZ".getBytes(); + byte b[] = "X=ABCDEFGHZZZ".getBytes(); ss = new ServerSocket (0); server = new Server (ss); @@ -163,8 +166,9 @@ public class ResendPostBody { /* Read the response */ int resp = conURL.getResponseCode (); + server.setFinished (true); + if (resp != 200) throw new RuntimeException ("Response code was not 200: " + resp); - server.setFinished (true); } } diff --git a/jdk/test/java/net/URLConnection/SetIfModifiedSince.java b/jdk/test/java/net/URLConnection/SetIfModifiedSince.java index e5681fc564f..f66d9385c1e 100644 --- a/jdk/test/java/net/URLConnection/SetIfModifiedSince.java +++ b/jdk/test/java/net/URLConnection/SetIfModifiedSince.java @@ -23,7 +23,7 @@ /* @test * @bug 4397096 - * @run main SetIfModifiedSince + * @run main/othervm SetIfModifiedSince * @summary setIfModifiedSince() of HttpURLConnection sets invalid date of default locale */ diff --git a/jdk/test/java/net/URLConnection/TimeoutTest.java b/jdk/test/java/net/URLConnection/TimeoutTest.java index c5c4f58d7a3..e8c32982c8f 100644 --- a/jdk/test/java/net/URLConnection/TimeoutTest.java +++ b/jdk/test/java/net/URLConnection/TimeoutTest.java @@ -43,8 +43,9 @@ public class TimeoutTest { try { Socket s = server.accept (); while (!finished ()) { - Thread.sleep (2000); + Thread.sleep (1000); } + s.close(); } catch (Exception e) { } } @@ -70,9 +71,12 @@ public class TimeoutTest { URL url = new URL ("http://127.0.0.1:"+ss.getLocalPort()); URLConnection urlc = url.openConnection (); InputStream is = urlc.getInputStream (); + throw new RuntimeException("Should have received timeout"); } catch (SocketTimeoutException e) { - s.done (); return; + } finally { + s.done(); + ss.close(); } } } diff --git a/jdk/test/java/net/URLConnection/URLConnectionHeaders.java b/jdk/test/java/net/URLConnection/URLConnectionHeaders.java index 3c162f0e0a2..4896e7a0b58 100644 --- a/jdk/test/java/net/URLConnection/URLConnectionHeaders.java +++ b/jdk/test/java/net/URLConnection/URLConnectionHeaders.java @@ -70,8 +70,10 @@ public class URLConnectionHeaders { w.newLine(); w.flush(); s.close (); - srv.close (); // or else the HTTPURLConnection will retry - } catch (IOException e) { e.printStackTrace();} + } catch (IOException e) { e.printStackTrace(); + } finally { + try { srv.close(); } catch (IOException unused) {} + } } } diff --git a/jdk/test/java/net/URLConnection/ZeroContentLength.java b/jdk/test/java/net/URLConnection/ZeroContentLength.java index 237520ae1b3..3da6ac1aba0 100644 --- a/jdk/test/java/net/URLConnection/ZeroContentLength.java +++ b/jdk/test/java/net/URLConnection/ZeroContentLength.java @@ -58,6 +58,14 @@ public class ZeroContentLength { contentLength = cl; } + static synchronized String getResponse() { + return response; + } + + static synchronized int getContentLength() { + return contentLength; + } + /* * Worker thread to service single connection - can service * multiple http requests on same connection. @@ -71,25 +79,44 @@ public class ZeroContentLength { this.id = id; } + final int CR = '\r'; + final int LF = '\n'; + public void run() { try { s.setSoTimeout(2000); - int max = 100; + int max = 20; // there should only be 20 connections + InputStream in = new BufferedInputStream(s.getInputStream()); for (;;) { - - // read entire request from client - byte b[] = new byte[100]; - InputStream in = s.getInputStream(); - int n, total=0; + // read entire request from client, until CR LF CR LF + int c, total=0; try { - do { - n = in.read(b); - if (n > 0) total += n; - } while (n > 0); - } catch (SocketTimeoutException e) { } + while ((c = in.read()) > 0) { + total++; + if (c == CR) { + if ((c = in.read()) > 0) { + total++; + if (c == LF) { + if ((c = in.read()) > 0) { + total++; + if (c == CR) { + if ((c = in.read()) > 0) { + total++; + if (c == LF) { + break; + } + } + } + } + } + } + } + + } + } catch (SocketTimeoutException e) {} debug("worker " + id + ": Read request from client " + @@ -105,19 +132,20 @@ public class ZeroContentLength { new BufferedOutputStream( s.getOutputStream() )); - out.print("HTTP/1.1 " + response + "\r\n"); - if (contentLength >= 0) { - out.print("Content-Length: " + contentLength + + out.print("HTTP/1.1 " + getResponse() + "\r\n"); + int clen = getContentLength(); + if (clen >= 0) { + out.print("Content-Length: " + clen + "\r\n"); } out.print("\r\n"); - for (int i=0; i upper || got < lower) { throw new RuntimeException ("checkTime failed: got " + got + " expected " + expected); } diff --git a/jdk/test/java/nio/MappedByteBuffer/Basic.java b/jdk/test/java/nio/MappedByteBuffer/Basic.java index 5b56918c563..3b068b76983 100644 --- a/jdk/test/java/nio/MappedByteBuffer/Basic.java +++ b/jdk/test/java/nio/MappedByteBuffer/Basic.java @@ -22,7 +22,7 @@ */ /* @test - * @bug 4462336 + * @bug 4462336 6799037 * @summary Simple MappedByteBuffer tests * @run main/othervm Basic */ @@ -52,6 +52,12 @@ public class Basic { mbb.force(); if (!mbb.isReadOnly()) throw new RuntimeException("Incorrect isReadOnly"); + + // repeat with unaligned position in file + mbb = fc.map(FileChannel.MapMode.READ_ONLY, 1, 10); + mbb.load(); + mbb.isLoaded(); + mbb.force(); fc.close(); fis.close(); diff --git a/jdk/test/java/nio/MappedByteBuffer/Truncate.java b/jdk/test/java/nio/MappedByteBuffer/Truncate.java new file mode 100644 index 00000000000..09dee07e60c --- /dev/null +++ b/jdk/test/java/nio/MappedByteBuffer/Truncate.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 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. + */ + +/* @test + * @bug 6934977 + * @summary Test MappedByteBuffer operations after mapped bye buffer becomes + * inaccessible + * @run main/othervm Truncate + */ + +import java.io.*; +import java.nio.*; +import java.nio.channels.*; +import java.util.concurrent.Callable; + +public class Truncate { + + static final long INITIAL_FILE_SIZE = 32000L; + static final long TRUNCATED_FILE_SIZE = 512L; + + public static void main(String[] args) throws Exception { + File blah = File.createTempFile("blah", null); + blah.deleteOnExit(); + + final FileChannel fc = new RandomAccessFile(blah, "rw").getChannel(); + fc.position(INITIAL_FILE_SIZE).write(ByteBuffer.wrap("THE END".getBytes())); + final MappedByteBuffer mbb = + fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size()); + boolean truncated; + try { + fc.truncate(TRUNCATED_FILE_SIZE); + truncated = true; + } catch (IOException ioe) { + // probably on Windows where a file cannot be truncated when + // there is a file mapping. + truncated = false; + } + if (truncated) { + // Test 1: access region that is no longer accessible + execute(new Callable() { + public Void call() { + mbb.get((int)TRUNCATED_FILE_SIZE + 1); + mbb.put((int)TRUNCATED_FILE_SIZE + 2, (byte)123); + return null; + } + }); + // Test 2: load buffer into memory + execute(new Callable() { + public Void call() throws IOException { + mbb.load(); + return null; + } + }); + } + fc.close(); + } + + // Runs the given task in its own thread. If operating correcting the + // the thread will terminate with an InternalError as the mapped buffer + // is inaccessible. + static void execute(final Callable c) { + Runnable r = new Runnable() { + public void run() { + try { + Object ignore = c.call(); + } catch (Exception ignore) { + } + } + }; + Thread t = new Thread(r); + t.start(); + try { t.join(); } catch (InterruptedException ignore) { } + } +} diff --git a/jdk/test/java/nio/channels/SocketChannel/OutOfBand.java b/jdk/test/java/nio/channels/SocketChannel/OutOfBand.java new file mode 100644 index 00000000000..83b32667730 --- /dev/null +++ b/jdk/test/java/nio/channels/SocketChannel/OutOfBand.java @@ -0,0 +1,191 @@ +/* + * Copyright (c) 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. + */ + +/* @test + * @summary Test socket adapter sendUrgentData method + * @bug 6963907 + */ + +import java.net.*; +import java.nio.ByteBuffer; +import java.nio.channels.*; +import java.io.IOException; +import java.util.Random; + +public class OutOfBand { + + private static final Random rand = new Random(); + + public static void main(String[] args) throws Exception { + ServerSocketChannel ssc = null; + SocketChannel sc1 = null; + SocketChannel sc2 = null; + + try { + + // establish loopback connection + ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0)); + InetAddress lh = InetAddress.getLocalHost(); + SocketAddress remote = + new InetSocketAddress(lh, ssc.socket().getLocalPort()); + sc1 = SocketChannel.open(remote); + sc2 = ssc.accept(); + + // enable SO_OOBLINE on server side + sc2.socket().setOOBInline(true); + + // run tests + test1(sc1, sc2); + test2(sc1, sc2); + test3(sc1, sc2); + test4(sc1); + + } finally { + if (sc1 != null) sc1.close(); + if (sc2 != null) sc2.close(); + if (ssc != null) ssc.close(); + } + } + + /** + * Basic test to check that OOB/TCP urgent byte is received. + */ + static void test1(SocketChannel client, SocketChannel server) + throws Exception + { + assert server.socket().getOOBInline(); + ByteBuffer bb = ByteBuffer.allocate(100); + for (int i=0; i<1000; i++) { + int b1 = -127 + rand.nextInt(384); + client.socket().sendUrgentData(b1); + + bb.clear(); + if (server.read(bb) != 1) + throw new RuntimeException("One byte expected"); + bb.flip(); + byte b2 = bb.get(); + if ((byte)b1 != b2) + throw new RuntimeException("Unexpected byte"); + } + } + + /** + * Basic test to check that OOB/TCP urgent byte is received, maybe with + * OOB mark changing. + */ + static void test2(final SocketChannel client, SocketChannel server) + throws Exception + { + assert server.socket().getOOBInline(); + Runnable sender = new Runnable() { + public void run() { + try { + for (int i=0; i<256; i++) + client.socket().sendUrgentData(i); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + }; + Thread thr = new Thread(sender); + thr.start(); + + ByteBuffer bb = ByteBuffer.allocate(256); + while (bb.hasRemaining()) { + if (server.read(bb) < 0) + throw new RuntimeException("Unexpected EOF"); + } + bb.flip(); + byte expect = 0; + while (bb.hasRemaining()) { + if (bb.get() != expect) + throw new RuntimeException("Unexpected byte"); + expect++; + } + + thr.join(); + } + + /** + * Test that is close to some real world examples where an urgent byte is + * used to "cancel" a long running query or transaction on the server. + */ + static void test3(SocketChannel client, final SocketChannel server) + throws Exception + { + final int STOP = rand.nextInt(256); + + assert server.socket().getOOBInline(); + Runnable reader = new Runnable() { + public void run() { + ByteBuffer bb = ByteBuffer.allocate(100); + try { + int n = server.read(bb); + if (n != 1) { + String msg = (n < 0) ? "Unexpected EOF" : + "One byte expected"; + throw new RuntimeException(msg); + } + bb.flip(); + if (bb.get() != (byte)STOP) + throw new RuntimeException("Unexpected byte"); + bb.flip(); + server.write(bb); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + + } + }; + + Thread thr = new Thread(reader); + thr.start(); + + // "stop" server + client.socket().sendUrgentData(STOP); + + // wait for server reply + ByteBuffer bb = ByteBuffer.allocate(100); + int n = client.read(bb); + if (n != 1) + throw new RuntimeException("Unexpected number of bytes"); + bb.flip(); + if (bb.get() != (byte)STOP) + throw new RuntimeException("Unexpected reply"); + + thr.join(); + } + + static void test4(SocketChannel sc) throws IOException { + boolean blocking = sc.isBlocking(); + sc.configureBlocking(false); + try { + sc.socket().sendUrgentData(0); + throw new RuntimeException("IllegalBlockingModeException expected"); + } catch (IllegalBlockingModeException x) { + // expected + } finally { + sc.configureBlocking(blocking); + } + } +} diff --git a/jdk/test/java/util/logging/AnonLoggerWeakRefLeak.java b/jdk/test/java/util/logging/AnonLoggerWeakRefLeak.java index 6b651013fbc..ed72e7f4110 100644 --- a/jdk/test/java/util/logging/AnonLoggerWeakRefLeak.java +++ b/jdk/test/java/util/logging/AnonLoggerWeakRefLeak.java @@ -23,24 +23,32 @@ import java.util.logging.*; -public class AnonLoggerWeakRefLeak { - public static int DEFAULT_LOOP_TIME = 60; // time is in seconds +public class AnonLoggerWeakRefLeak extends SimpleApplication { + // The test driver script will allow this program to run until we + // reach DEFAULT_LOOP_TIME or a decrease in instance counts is + // observed. For this particular WeakReference leak, the count + // was always observed to be increasing so if we get a decreasing + // count, then the leak is fixed in the bits being tested. + // Two minutes has been enough time to observe a decrease in + // fixed bits on overloaded systems, but the test will likely + // finish more quickly. + public static int DEFAULT_LOOP_TIME = 120; // time is in seconds - public static void main(String[] args) { + // execute the AnonLoggerWeakRefLeak app work + public void doMyAppWork(String[] args) throws Exception { int loop_time = 0; int max_loop_time = DEFAULT_LOOP_TIME; - if (args.length == 0) { + // args[0] is the port-file + if (args.length < 2) { System.out.println("INFO: using default time of " + max_loop_time + " seconds."); } else { try { - max_loop_time = Integer.parseInt(args[0]); + max_loop_time = Integer.parseInt(args[1]); } catch (NumberFormatException nfe) { - System.err.println("Error: '" + args[0] + throw new RuntimeException("Error: '" + args[1] + "': is not a valid seconds value."); - System.err.println("Usage: AnonLoggerWeakRefLeak [seconds]"); - System.exit(1); } } @@ -73,4 +81,12 @@ public class AnonLoggerWeakRefLeak { System.out.println("INFO: final loop count = " + count); } + + public static void main(String[] args) throws Exception { + AnonLoggerWeakRefLeak myApp = new AnonLoggerWeakRefLeak(); + + SimpleApplication.setMyApp(myApp); + + SimpleApplication.main(args); + } } diff --git a/jdk/test/java/util/logging/AnonLoggerWeakRefLeak.sh b/jdk/test/java/util/logging/AnonLoggerWeakRefLeak.sh index ddbb6efcfcf..eef8641c7b6 100644 --- a/jdk/test/java/util/logging/AnonLoggerWeakRefLeak.sh +++ b/jdk/test/java/util/logging/AnonLoggerWeakRefLeak.sh @@ -1,3 +1,5 @@ +#!/bin/sh + # # Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. @@ -23,76 +25,24 @@ # @test # @bug 6942989 -# @ignore until 6964018 is fixed # @summary Check for WeakReference leak in anonymous Logger objects # @author Daniel D. Daugherty # -# @run build AnonLoggerWeakRefLeak -# @run shell/timeout=180 AnonLoggerWeakRefLeak.sh +# @library ../../../sun/tools/common +# @build SimpleApplication ShutdownSimpleApplication +# @build AnonLoggerWeakRefLeak +# @run shell/timeout=240 AnonLoggerWeakRefLeak.sh -# The timeout is: 2 minutes for infrastructure and 1 minute for the test +# The timeout is: 2 minutes for infrastructure and 2 minutes for the test # -if [ "${TESTJAVA}" = "" ] -then - echo "TESTJAVA not set. Test cannot execute. Failed." - exit 1 -fi +. ${TESTSRC}/../../../sun/tools/common/CommonSetup.sh +. ${TESTSRC}/../../../sun/tools/common/ApplicationSetup.sh -if [ "${TESTSRC}" = "" ] -then - echo "TESTSRC not set. Test cannot execute. Failed." - exit 1 -fi - -if [ "${TESTCLASSES}" = "" ] -then - echo "TESTCLASSES not set. Test cannot execute. Failed." - exit 1 -fi - -JAVA="${TESTJAVA}"/bin/java -JMAP="${TESTJAVA}"/bin/jmap -JPS="${TESTJAVA}"/bin/jps - -set -eu TEST_NAME="AnonLoggerWeakRefLeak" TARGET_CLASS="java\.lang\.ref\.WeakReference" -is_cygwin=false -is_mks=false -is_windows=false - -case `uname -s` in -CYGWIN*) - is_cygwin=true - is_windows=true - ;; -Windows_*) - is_mks=true - is_windows=true - ;; -*) - ;; -esac - - -# wrapper for grep -# -grep_cmd() { - set +e - if $is_windows; then - # need dos2unix to get rid of CTRL-M chars from java output - dos2unix | grep "$@" - status="$?" - else - grep "$@" - status="$?" - fi - set -e -} - # MAIN begins here # @@ -105,62 +55,64 @@ fi # see if this version of jmap supports the '-histo:live' option jmap_option="-histo:live" set +e -"${JMAP}" "$jmap_option" 0 > "$TEST_NAME.jmap" 2>&1 -grep '^Usage: ' "$TEST_NAME.jmap" > /dev/null 2>&1 +"${JMAP}" 2>&1 | grep ':live' > /dev/null 2>&1 status="$?" set -e -if [ "$status" = 0 ]; then - echo "INFO: switching jmap option from '$jmap_option'\c" - jmap_option="-histo" - echo " to '$jmap_option'." -fi +if [ "$status" != 0 ]; then + # usage message doesn't show ':live' option -"${JAVA}" ${TESTVMOPTS} -classpath "${TESTCLASSES}" \ - "$TEST_NAME" $seconds > "$TEST_NAME.log" 2>&1 & -test_pid="$!" -echo "INFO: starting $TEST_NAME as pid = $test_pid" - -# wait for test program to get going -count=0 -while [ "$count" -lt 30 ]; do - sleep 2 - grep_cmd '^INFO: call count = 0$' < "$TEST_NAME.log" > /dev/null 2>&1 - if [ "$status" = 0 ]; then - break + if $isWindows; then + # If SA isn't present, then jmap gives a different usage message + # that doesn't show the ':live' option. However, that's a bug that + # is covered by 6971851 so we try using the option just to be sure. + # For some reason, this problem has only been seen on OpenJDK6 on + # Windows. Not sure why. + set +e + # Note: Don't copy this code to try probing process 0 on Linux; it + # will kill the process group in strange ways. + "${JMAP}" "$jmap_option" 0 2>&1 | grep 'Usage' > /dev/null 2>&1 + status="$?" + set -e + if [ "$status" = 0 ]; then + # Usage message generated so flag the problem. + status=1 + else + # No usage message so clear the flag. + status=0 + fi fi - count=`expr $count + 1` -done -if [ "$count" -ge 30 ]; then - echo "ERROR: $TEST_NAME failed to get going." >&2 - echo "INFO: killing $test_pid" - kill "$test_pid" - exit 1 -elif [ "$count" -gt 1 ]; then - echo "INFO: $TEST_NAME took $count loops to start." -fi - -if $is_cygwin; then - # We need the Windows pid for jmap and not the Cygwin pid. - # Note: '\t' works on Cygwin, but doesn't seem to work on Solaris. - jmap_pid=`"${JPS}"| grep_cmd "[ \t]$TEST_NAME$" | sed 's/[ \t].*//'` - if [ -z "$jmap_pid" ]; then - echo "FAIL: jps could not map Cygwin pid to Windows pid." >&2 - echo "INFO: killing $test_pid" - kill "$test_pid" + if [ "$status" != 0 ]; then + echo "ERROR: 'jmap $jmap_option' is not supported so this test" + echo "ERROR: cannot work reliably. Aborting!" exit 2 fi - echo "INFO: pid = $test_pid maps to Windows pid = $jmap_pid" -else - jmap_pid="$test_pid" fi +# Start application and use TEST_NAME.port for coordination +startApplication "$TEST_NAME" "$TEST_NAME.port" $seconds + +finished_early=false + decreasing_cnt=0 increasing_cnt=0 loop_cnt=0 prev_instance_cnt=0 +MAX_JMAP_TRY_CNT=10 +jmap_retry_cnt=0 +loop_cnt_on_retry=0 + while true; do + # see if the target process has finished its run and bail if it has + set +e + grep "^INFO: final loop count = " "$appOutput" > /dev/null 2>&1 + status="$?" + set -e + if [ "$status" = 0 ]; then + break + fi + # Output format for 'jmap -histo' in JDK1.5.0: # # <#bytes> <#instances> @@ -170,38 +122,70 @@ while true; do # : <#instances> <#bytes> # set +e - "${JMAP}" "$jmap_option" "$jmap_pid" > "$TEST_NAME.jmap" 2>&1 + "${JMAP}" "$jmap_option" "$appJavaPid" > "$TEST_NAME.jmap" 2>&1 status="$?" set -e if [ "$status" != 0 ]; then echo "INFO: jmap exited with exit code = $status" - if [ "$loop_cnt" = 0 ]; then - echo "INFO: on the first iteration so no samples were taken." - echo "INFO: start of jmap output:" - cat "$TEST_NAME.jmap" - echo "INFO: end of jmap output." + + # There are intermittent jmap failures; see 6498448. + # + # So far the following have been observed in a jmap call + # that was not in a race with target process termination: + # + # (Solaris specific, 2nd sample) + # : Unable to open door: target process not responding or HotSpot VM not loaded + # The -F option can be used when the target process is not responding + # + # (on Solaris so far) + # java.io.IOException + # + # (on Solaris so far, 1st sample) + # : Permission denied + # + sed 's/^/INFO: /' "$TEST_NAME.jmap" + + if [ "$loop_cnt" = "$loop_cnt_on_retry" ]; then + # loop count hasn't changed + jmap_retry_cnt=`expr $jmap_retry_cnt + 1` + else + # loop count has changed so remember it + jmap_retry_cnt=1 + loop_cnt_on_retry="$loop_cnt" + fi + + # This is '-ge' because we have the original attempt plus + # MAX_JMAP_TRY_CNT - 1 retries. + if [ "$jmap_retry_cnt" -ge "$MAX_JMAP_TRY_CNT" ]; then + echo "INFO: jmap failed $MAX_JMAP_TRY_CNT times in a row" \ + "without making any progress." echo "FAIL: jmap is unable to take any samples." >&2 - echo "INFO: killing $test_pid" - kill "$test_pid" + killApplication exit 2 fi - echo "INFO: The likely reason is that $TEST_NAME has finished running." - break + + # short delay and try again + # Note: sleep 1 didn't help with ": Permission denied" + sleep 2 + echo "INFO: retrying jmap (retry=$jmap_retry_cnt, loop=$loop_cnt)." + continue fi - instance_cnt=`grep_cmd "[ ]$TARGET_CLASS$" \ - < "$TEST_NAME.jmap" \ + set +e + instance_cnt=`grep "${PATTERN_WS}${TARGET_CLASS}${PATTERN_EOL}" \ + "$TEST_NAME.jmap" \ | sed ' # strip leading whitespace; does nothing in JDK1.5.0 - s/^[ ][ ]*// + s/^'"${PATTERN_WS}${PATTERN_WS}"'*// # strip <#bytes> in JDK1.5.0; does nothing otherwise - s/^[1-9][0-9]*[ ][ ]*// + s/^[1-9][0-9]*'"${PATTERN_WS}${PATTERN_WS}"'*// # strip : field; does nothing in JDK1.5.0 - s/^[1-9][0-9]*:[ ][ ]*// + s/^[1-9][0-9]*:'"${PATTERN_WS}${PATTERN_WS}"'*// # strip field - s/[ ].*// + s/'"${PATTERN_WS}"'.*// '` + set -e if [ -z "$instance_cnt" ]; then echo "INFO: instance count is unexpectedly empty" if [ "$loop_cnt" = 0 ]; then @@ -211,8 +195,7 @@ while true; do cat "$TEST_NAME.jmap" echo "INFO: end of jmap output." echo "FAIL: cannot find the instance count value." >&2 - echo "INFO: killing $test_pid" - kill "$test_pid" + killApplication exit 2 fi else @@ -221,7 +204,17 @@ while true; do if [ "$instance_cnt" -gt "$prev_instance_cnt" ]; then increasing_cnt=`expr $increasing_cnt + 1` else + # actually decreasing or the same decreasing_cnt=`expr $decreasing_cnt + 1` + + # For this particular WeakReference leak, the count was + # always observed to be increasing so if we get a decreasing + # or the same count, then the leak is fixed in the bits + # being tested. + echo "INFO: finishing early due to non-increasing instance count." + finished_early=true + killApplication + break fi prev_instance_cnt="$instance_cnt" fi @@ -232,8 +225,22 @@ while true; do loop_cnt=`expr $loop_cnt + 1` done +if [ $finished_early = false ]; then + stopApplication "$TEST_NAME.port" + waitForApplication +fi + +echo "INFO: $TEST_NAME has finished running." echo "INFO: increasing_cnt = $increasing_cnt" echo "INFO: decreasing_cnt = $decreasing_cnt" +if [ "$jmap_retry_cnt" -gt 0 ]; then + echo "INFO: jmap_retry_cnt = $jmap_retry_cnt (in $loop_cnt iterations)" +fi + +if [ "$loop_cnt" = 0 ]; then + echo "FAIL: jmap is unable to take any samples." >&2 + exit 2 +fi echo "INFO: The instance count of" `eval echo $TARGET_CLASS` "objects" if [ "$decreasing_cnt" = 0 ]; then @@ -242,6 +249,6 @@ if [ "$decreasing_cnt" = 0 ]; then exit 2 fi -echo "INFO: is both increasing and decreasing." +echo "INFO: is not always increasing." echo "PASS: This indicates that there is not a memory leak." exit 0 diff --git a/jdk/test/java/util/logging/LoggerWeakRefLeak.java b/jdk/test/java/util/logging/LoggerWeakRefLeak.java index c66d3752100..f93c7be6163 100644 --- a/jdk/test/java/util/logging/LoggerWeakRefLeak.java +++ b/jdk/test/java/util/logging/LoggerWeakRefLeak.java @@ -23,27 +23,32 @@ import java.util.logging.*; -public class LoggerWeakRefLeak { - // AnonLoggerWeakRefLeak checks for one weak reference leak. - // LoggerWeakRefLeak checks for two weak reference leaks so - // this test runs twice as long, by default. +public class LoggerWeakRefLeak extends SimpleApplication { + // The test driver script will allow this program to run until we + // reach DEFAULT_LOOP_TIME or a decrease in instance counts is + // observed. For these particular WeakReference leaks, the count + // was always observed to be increasing so if we get a decreasing + // count, then the leaks are fixed in the bits being tested. + // Two minutes has been enough time to observe a decrease in + // fixed bits on overloaded systems, but the test will likely + // finish more quickly. public static int DEFAULT_LOOP_TIME = 120; // time is in seconds - public static void main(String[] args) { + // execute the LoggerWeakRefLeak app work + public void doMyAppWork(String[] args) throws Exception { int loop_time = 0; int max_loop_time = DEFAULT_LOOP_TIME; - if (args.length == 0) { + // args[0] is the port-file + if (args.length < 2) { System.out.println("INFO: using default time of " + max_loop_time + " seconds."); } else { try { - max_loop_time = Integer.parseInt(args[0]); + max_loop_time = Integer.parseInt(args[1]); } catch (NumberFormatException nfe) { - System.err.println("Error: '" + args[0] + throw new RuntimeException("Error: '" + args[1] + "': is not a valid seconds value."); - System.err.println("Usage: LoggerWeakRefLeak [seconds]"); - System.exit(1); } } @@ -86,4 +91,12 @@ public class LoggerWeakRefLeak { System.out.println("INFO: final loop count = " + count); } + + public static void main(String[] args) throws Exception { + AnonLoggerWeakRefLeak myApp = new AnonLoggerWeakRefLeak(); + + SimpleApplication.setMyApp(myApp); + + SimpleApplication.main(args); + } } diff --git a/jdk/test/java/util/logging/LoggerWeakRefLeak.sh b/jdk/test/java/util/logging/LoggerWeakRefLeak.sh index 95c33c39e82..ea3dc1f8f1d 100644 --- a/jdk/test/java/util/logging/LoggerWeakRefLeak.sh +++ b/jdk/test/java/util/logging/LoggerWeakRefLeak.sh @@ -1,3 +1,5 @@ +#!/bin/sh + # # Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. @@ -23,76 +25,24 @@ # @test # @bug 6942989 -# @ignore until 6964018 is fixed # @summary Check for WeakReference leak in Logger objects # @author Daniel D. Daugherty # -# @run build LoggerWeakRefLeak +# @library ../../../sun/tools/common +# @build SimpleApplication ShutdownSimpleApplication +# @build LoggerWeakRefLeak # @run shell/timeout=240 LoggerWeakRefLeak.sh -# The timeout is: 2 minutes for infrastructure and 1 minute for the test +# The timeout is: 2 minutes for infrastructure and 2 minutes for the test # -if [ "${TESTJAVA}" = "" ] -then - echo "TESTJAVA not set. Test cannot execute. Failed." - exit 1 -fi +. ${TESTSRC}/../../../sun/tools/common/CommonSetup.sh +. ${TESTSRC}/../../../sun/tools/common/ApplicationSetup.sh -if [ "${TESTSRC}" = "" ] -then - echo "TESTSRC not set. Test cannot execute. Failed." - exit 1 -fi - -if [ "${TESTCLASSES}" = "" ] -then - echo "TESTCLASSES not set. Test cannot execute. Failed." - exit 1 -fi - -JAVA="${TESTJAVA}"/bin/java -JMAP="${TESTJAVA}"/bin/jmap -JPS="${TESTJAVA}"/bin/jps - -set -eu TEST_NAME="LoggerWeakRefLeak" TARGET_CLASS="java\.lang\.ref\.WeakReference" -is_cygwin=false -is_mks=false -is_windows=false - -case `uname -s` in -CYGWIN*) - is_cygwin=true - is_windows=true - ;; -Windows_*) - is_mks=true - is_windows=true - ;; -*) - ;; -esac - - -# wrapper for grep -# -grep_cmd() { - set +e - if $is_windows; then - # need dos2unix to get rid of CTRL-M chars from java output - dos2unix | grep "$@" - status="$?" - else - grep "$@" - status="$?" - fi - set -e -} - # MAIN begins here # @@ -105,62 +55,64 @@ fi # see if this version of jmap supports the '-histo:live' option jmap_option="-histo:live" set +e -"${JMAP}" "$jmap_option" 0 > "$TEST_NAME.jmap" 2>&1 -grep '^Usage: ' "$TEST_NAME.jmap" > /dev/null 2>&1 +"${JMAP}" 2>&1 | grep ':live' > /dev/null 2>&1 status="$?" set -e -if [ "$status" = 0 ]; then - echo "INFO: switching jmap option from '$jmap_option'\c" - jmap_option="-histo" - echo " to '$jmap_option'." -fi +if [ "$status" != 0 ]; then + # usage message doesn't show ':live' option -"${JAVA}" ${TESTVMOPTS} -classpath "${TESTCLASSES}" \ - "$TEST_NAME" $seconds > "$TEST_NAME.log" 2>&1 & -test_pid="$!" -echo "INFO: starting $TEST_NAME as pid = $test_pid" - -# wait for test program to get going -count=0 -while [ "$count" -lt 30 ]; do - sleep 2 - grep_cmd '^INFO: call count = 0$' < "$TEST_NAME.log" > /dev/null 2>&1 - if [ "$status" = 0 ]; then - break + if $isWindows; then + # If SA isn't present, then jmap gives a different usage message + # that doesn't show the ':live' option. However, that's a bug that + # is covered by 6971851 so we try using the option just to be sure. + # For some reason, this problem has only been seen on OpenJDK6 on + # Windows. Not sure why. + set +e + # Note: Don't copy this code to try probing process 0 on Linux; it + # will kill the process group in strange ways. + "${JMAP}" "$jmap_option" 0 2>&1 | grep 'Usage' > /dev/null 2>&1 + status="$?" + set -e + if [ "$status" = 0 ]; then + # Usage message generated so flag the problem. + status=1 + else + # No usage message so clear the flag. + status=0 + fi fi - count=`expr $count + 1` -done -if [ "$count" -ge 30 ]; then - echo "ERROR: $TEST_NAME failed to get going." >&2 - echo "INFO: killing $test_pid" - kill "$test_pid" - exit 1 -elif [ "$count" -gt 1 ]; then - echo "INFO: $TEST_NAME took $count loops to start." -fi - -if $is_cygwin; then - # We need the Windows pid for jmap and not the Cygwin pid. - # Note: '\t' works on Cygwin, but doesn't seem to work on Solaris. - jmap_pid=`"${JPS}"| grep_cmd "[ \t]$TEST_NAME$" | sed 's/[ \t].*//'` - if [ -z "$jmap_pid" ]; then - echo "FAIL: jps could not map Cygwin pid to Windows pid." >&2 - echo "INFO: killing $test_pid" - kill "$test_pid" + if [ "$status" != 0 ]; then + echo "ERROR: 'jmap $jmap_option' is not supported so this test" + echo "ERROR: cannot work reliably. Aborting!" exit 2 fi - echo "INFO: pid = $test_pid maps to Windows pid = $jmap_pid" -else - jmap_pid="$test_pid" fi +# Start application and use TEST_NAME.port for coordination +startApplication "$TEST_NAME" "$TEST_NAME.port" $seconds + +finished_early=false + decreasing_cnt=0 increasing_cnt=0 loop_cnt=0 prev_instance_cnt=0 +MAX_JMAP_TRY_CNT=10 +jmap_retry_cnt=0 +loop_cnt_on_retry=0 + while true; do + # see if the target process has finished its run and bail if it has + set +e + grep "^INFO: final loop count = " "$appOutput" > /dev/null 2>&1 + status="$?" + set -e + if [ "$status" = 0 ]; then + break + fi + # Output format for 'jmap -histo' in JDK1.5.0: # # <#bytes> <#instances> @@ -170,38 +122,70 @@ while true; do # : <#instances> <#bytes> # set +e - "${JMAP}" "$jmap_option" "$jmap_pid" > "$TEST_NAME.jmap" 2>&1 + "${JMAP}" "$jmap_option" "$appJavaPid" > "$TEST_NAME.jmap" 2>&1 status="$?" set -e if [ "$status" != 0 ]; then echo "INFO: jmap exited with exit code = $status" - if [ "$loop_cnt" = 0 ]; then - echo "INFO: on the first iteration so no samples were taken." - echo "INFO: start of jmap output:" - cat "$TEST_NAME.jmap" - echo "INFO: end of jmap output." + + # There are intermittent jmap failures; see 6498448. + # + # So far the following have been observed in a jmap call + # that was not in a race with target process termination: + # + # (Solaris specific, 2nd sample) + # : Unable to open door: target process not responding or HotSpot VM not loaded + # The -F option can be used when the target process is not responding + # + # (on Solaris so far) + # java.io.IOException + # + # (on Solaris so far, 1st sample) + # : Permission denied + # + sed 's/^/INFO: /' "$TEST_NAME.jmap" + + if [ "$loop_cnt" = "$loop_cnt_on_retry" ]; then + # loop count hasn't changed + jmap_retry_cnt=`expr $jmap_retry_cnt + 1` + else + # loop count has changed so remember it + jmap_retry_cnt=1 + loop_cnt_on_retry="$loop_cnt" + fi + + # This is '-ge' because we have the original attempt plus + # MAX_JMAP_TRY_CNT - 1 retries. + if [ "$jmap_retry_cnt" -ge "$MAX_JMAP_TRY_CNT" ]; then + echo "INFO: jmap failed $MAX_JMAP_TRY_CNT times in a row" \ + "without making any progress." echo "FAIL: jmap is unable to take any samples." >&2 - echo "INFO: killing $test_pid" - kill "$test_pid" + killApplication exit 2 fi - echo "INFO: The likely reason is that $TEST_NAME has finished running." - break + + # short delay and try again + # Note: sleep 1 didn't help with ": Permission denied" + sleep 2 + echo "INFO: retrying jmap (retry=$jmap_retry_cnt, loop=$loop_cnt)." + continue fi - instance_cnt=`grep_cmd "[ ]$TARGET_CLASS$" \ - < "$TEST_NAME.jmap" \ + set +e + instance_cnt=`grep "${PATTERN_WS}${TARGET_CLASS}${PATTERN_EOL}" \ + "$TEST_NAME.jmap" \ | sed ' # strip leading whitespace; does nothing in JDK1.5.0 - s/^[ ][ ]*// + s/^'"${PATTERN_WS}${PATTERN_WS}"'*// # strip <#bytes> in JDK1.5.0; does nothing otherwise - s/^[1-9][0-9]*[ ][ ]*// + s/^[1-9][0-9]*'"${PATTERN_WS}${PATTERN_WS}"'*// # strip : field; does nothing in JDK1.5.0 - s/^[1-9][0-9]*:[ ][ ]*// + s/^[1-9][0-9]*:'"${PATTERN_WS}${PATTERN_WS}"'*// # strip field - s/[ ].*// + s/'"${PATTERN_WS}"'.*// '` + set -e if [ -z "$instance_cnt" ]; then echo "INFO: instance count is unexpectedly empty" if [ "$loop_cnt" = 0 ]; then @@ -211,8 +195,7 @@ while true; do cat "$TEST_NAME.jmap" echo "INFO: end of jmap output." echo "FAIL: cannot find the instance count value." >&2 - echo "INFO: killing $test_pid" - kill "$test_pid" + killApplication exit 2 fi else @@ -221,7 +204,17 @@ while true; do if [ "$instance_cnt" -gt "$prev_instance_cnt" ]; then increasing_cnt=`expr $increasing_cnt + 1` else + # actually decreasing or the same decreasing_cnt=`expr $decreasing_cnt + 1` + + # For these particular WeakReference leaks, the count was + # always observed to be increasing so if we get a decreasing + # or the same count, then the leaks are fixed in the bits + # being tested. + echo "INFO: finishing early due to non-increasing instance count." + finished_early=true + killApplication + break fi prev_instance_cnt="$instance_cnt" fi @@ -232,8 +225,22 @@ while true; do loop_cnt=`expr $loop_cnt + 1` done +if [ $finished_early = false ]; then + stopApplication "$TEST_NAME.port" + waitForApplication +fi + +echo "INFO: $TEST_NAME has finished running." echo "INFO: increasing_cnt = $increasing_cnt" echo "INFO: decreasing_cnt = $decreasing_cnt" +if [ "$jmap_retry_cnt" -gt 0 ]; then + echo "INFO: jmap_retry_cnt = $jmap_retry_cnt (in $loop_cnt iterations)" +fi + +if [ "$loop_cnt" = 0 ]; then + echo "FAIL: jmap is unable to take any samples." >&2 + exit 2 +fi echo "INFO: The instance count of" `eval echo $TARGET_CLASS` "objects" if [ "$decreasing_cnt" = 0 ]; then @@ -242,6 +249,6 @@ if [ "$decreasing_cnt" = 0 ]; then exit 2 fi -echo "INFO: is both increasing and decreasing." +echo "INFO: is not always increasing." echo "PASS: This indicates that there is not a memory leak." exit 0 diff --git a/jdk/test/javax/swing/JColorChooser/Test6199676.java b/jdk/test/javax/swing/JColorChooser/Test6199676.java new file mode 100644 index 00000000000..19bb68b4900 --- /dev/null +++ b/jdk/test/javax/swing/JColorChooser/Test6199676.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 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. + */ + +/* + * @test + * @bug 6199676 + * @summary Tests preview panel after L&F changing + * @author Sergey Malenkov + */ + +import java.awt.Component; +import java.awt.Container; +import javax.swing.JColorChooser; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UIManager.LookAndFeelInfo; + +public class Test6199676 implements Runnable { + public static void main(String[] args) { + SwingUtilities.invokeLater(new Test6199676()); + } + + private static void exit(String error) { + if (error != null) { + System.err.println(error); + System.exit(1); + } + else { + System.exit(0); + } + } + + private static Component getPreview(Container container) { + String name = "ColorChooser.previewPanelHolder"; + for (Component component : container.getComponents()) { + if (!name.equals(component.getName())) { + component = (component instanceof Container) + ? getPreview((Container) component) + : null; + } + if (component instanceof Container) { + container = (Container) component; + return 1 == container.getComponentCount() + ? container.getComponent(0) + : null; + } + } + return null; + } + + private static boolean isShowing(Component component) { + return (component != null) && component.isShowing(); + } + + private int index; + private boolean updated; + private JColorChooser chooser; + + public synchronized void run() { + if (this.chooser == null) { + this.chooser = new JColorChooser(); + + JFrame frame = new JFrame(getClass().getName()); + frame.add(this.chooser); + frame.setVisible(true); + } + else if (this.updated) { + if (isShowing(this.chooser.getPreviewPanel())) { + exit("custom preview panel is showing"); + } + exit(null); + } + else { + Component component = this.chooser.getPreviewPanel(); + if (component == null) { + component = getPreview(this.chooser); + } + if (!isShowing(component)) { + exit("default preview panel is not showing"); + } + this.updated = true; + this.chooser.setPreviewPanel(new JPanel()); + } + LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels(); + LookAndFeelInfo info = infos[++this.index % infos.length]; + try { + UIManager.setLookAndFeel(info.getClassName()); + } + catch (Exception exception) { + exit("could not change L&F"); + } + SwingUtilities.updateComponentTreeUI(this.chooser); + SwingUtilities.invokeLater(this); + } +} diff --git a/jdk/test/javax/swing/JComboBox/4743225/bug4743225.java b/jdk/test/javax/swing/JComboBox/4743225/bug4743225.java new file mode 100644 index 00000000000..2a41b3075ac --- /dev/null +++ b/jdk/test/javax/swing/JComboBox/4743225/bug4743225.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 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. + */ + +/* @test + * @bug 4743225 + * @summary Size of JComboBox list is wrong when list is populated via PopupMenuListener + * @author Alexander Potochkin + */ + +import sun.awt.SunToolkit; + +import javax.accessibility.AccessibleContext; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; +import javax.swing.plaf.basic.BasicComboPopup; +import java.awt.FlowLayout; +import java.awt.Point; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.event.InputEvent; + +public class bug4743225 extends JFrame { + + private static JComboBox cb; + private static volatile boolean flag; + + public bug4743225() { + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setLayout(new FlowLayout()); + cb = new JComboBox(new Object[] {"one", "two", "three"}); + cb.addPopupMenuListener(new PopupMenuListener() { + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + cb.addItem("Test"); + } + + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + } + + public void popupMenuCanceled(PopupMenuEvent e) { + } + }); + add(cb); + pack(); + } + + public static BasicComboPopup getPopup() { + AccessibleContext c = cb.getAccessibleContext(); + for(int i = 0; i < c.getAccessibleChildrenCount(); i ++) { + if (c.getAccessibleChild(i) instanceof BasicComboPopup) { + return (BasicComboPopup) c.getAccessibleChild(i); + } + } + throw new AssertionError("No BasicComboPopup found"); + } + + public static void main(String... args) throws Exception { + + Robot robot = new Robot(); + robot.setAutoDelay(20); + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + new bug4743225().setVisible(true); + } + }); + toolkit.realSync(); + + // calling this method from main thread is ok + Point point = cb.getLocationOnScreen(); + robot.mouseMove(point.x + 10, point.y + 10); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + toolkit.realSync(); + + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + if(getPopup().getList().getLastVisibleIndex() == 3) { + flag = true; + } + } + }); + + if (!flag) { + throw new RuntimeException("The ComboBox popup wasn't correctly updated"); + } + } +} diff --git a/jdk/test/javax/swing/JFormattedTextField/Test6462562.java b/jdk/test/javax/swing/JFormattedTextField/Test6462562.java new file mode 100644 index 00000000000..0696a016fba --- /dev/null +++ b/jdk/test/javax/swing/JFormattedTextField/Test6462562.java @@ -0,0 +1,360 @@ +/* + * Copyright (c) 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + @bug 6462562 + @summary Tests text input into JFormattedTextField + with an InternationalFormatter + @author Peter Zhelezniakov + @run main Test6462562 +*/ + +import java.awt.event.ActionEvent; +import java.text.DateFormat; +import java.text.NumberFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import javax.swing.Action; +import javax.swing.JFormattedTextField; +import javax.swing.SwingUtilities; +import javax.swing.text.Caret; +import javax.swing.text.DateFormatter; +import javax.swing.text.DefaultEditorKit; +import javax.swing.text.InternationalFormatter; +import javax.swing.text.NumberFormatter; + + +public class Test6462562 +{ + static final String BACKSPACE = new String("backspace"); + static final String DELETE = new String("delete"); + + boolean failed = false; + + void test() { + testPercentFormat(); + testCurrencyFormat(); + testIntegerFormat(); + testDateFormat(); + + if (failed) { + throw new RuntimeException("Some testcases failed, see output above"); + } + System.err.println("(-; All testcases passed ;-)"); + } + + TestFormattedTextField create(NumberFormat format) { + format.setMaximumFractionDigits(0); + NumberFormatter fmt = new NumberFormatter(format); + return new TestFormattedTextField(fmt); + } + + TestFormattedTextField create(DateFormat format) { + DateFormatter fmt = new DateFormatter(format); + return new TestFormattedTextField(fmt); + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + new Test6462562().test(); + } + }); + } + + class TestFormattedTextField extends JFormattedTextField + { + final Action backspace; + final Action delete; + final Action insert; + + final ActionEvent dummyEvent; + + public TestFormattedTextField(InternationalFormatter fmt) { + super(fmt); + fmt.setAllowsInvalid(false); + fmt.setOverwriteMode(true); + + backspace = getActionMap().get(DefaultEditorKit.deletePrevCharAction); + delete = getActionMap().get(DefaultEditorKit.deleteNextCharAction); + insert = getActionMap().get(DefaultEditorKit.insertContentAction); + dummyEvent = new ActionEvent(this, 0, null); + } + + public boolean test(int pos, int selectionLength, String todo, Object expectedResult) { + Object v0 = getValue(); + + Caret caret = getCaret(); + caret.setDot(pos); + if (selectionLength > 0) { + caret.moveDot(pos + selectionLength); + } + + String desc = todo; + if (todo == BACKSPACE) { + backspace.actionPerformed(dummyEvent); + } else if (todo == DELETE) { + delete.actionPerformed(dummyEvent); + } else { + desc = "insert('" + todo + "')"; + insert.actionPerformed(new ActionEvent(this, 0, todo)); + } + + try { + commitEdit(); + } catch (ParseException e) { + e.printStackTrace(); + failed = true; + return false; + } + + Object v1 = getValue(); + if (! v1.equals(expectedResult)) { + System.err.printf("Failure: value='%s', mark=%d, dot=%d, action=%s\n", + v0, pos, pos + selectionLength, desc); + System.err.printf(" Result: '%s', expected: '%s'\n", v1, expectedResult); + failed = true; + return false; + } + return true; + } + } + + void testPercentFormat() { + NumberFormat format = NumberFormat.getPercentInstance(Locale.US); + TestFormattedTextField ftf = create(format); + ftf.setValue(.34); + + System.err.println("Testing NumberFormat.getPercentInstance(Locale.US)"); + + // test inserting individual characters + ftf.test(0, 0, "1", .14); + ftf.test(2, 0, "2", 1.42); + ftf.test(1, 0, "0", 1.02); + + // test inserting several characters at once - e.g. from clipboard + ftf.test(0, 0, "1024", 10.24); + ftf.test(3, 0, "333", 103.33); + ftf.test(6, 0, "77", 10333.77); + ftf.test(4, 0, "99", 10399.77); + ftf.test(6, 0, "00", 10390.07); + + // test inserting strings that contain some formatting + ftf.test(0, 0, "2,2", 2290.07); + ftf.test(2, 0, "2,2", 222.27); + ftf.test(4, 0, "2,2", 222.22); + ftf.test(6, 0, "33,33", 2222233.33); + + // test delete + ftf.test(0, 0, DELETE, 222233.33); + ftf.test(10, 0, DELETE, 222233.33); + ftf.test(5, 0, DELETE, 22223.33); + ftf.test(6, 0, DELETE, 2222.33); + + // test backspace + ftf.test(0, 0, BACKSPACE, 2222.33); + ftf.test(7, 0, BACKSPACE, 222.23); + ftf.test(4, 0, BACKSPACE, 22.23); + ftf.test(2, 0, BACKSPACE, 2.23); + + // test replacing selection + ftf.test(0, 1, "555", 555.23); + ftf.test(4, 2, "555", 5555.55); + ftf.test(2, 3, "1", 551.55); + ftf.test(3, 2, "6", 55.65); + ftf.test(4, 2, "12", 556.12); + ftf.test(3, 4, "0", 5.5); + ftf.test(0, 3, "111222333444555", 1112223334445.55); + + // test deleting selection + ftf.test(0, 2, DELETE, 12223334445.55); + ftf.test(0, 3, BACKSPACE, 223334445.55); + ftf.test(12, 2, DELETE, 2233344.45); + ftf.test(9, 2, BACKSPACE, 22333.44); + ftf.test(4, 3, DELETE, 223.44); + ftf.test(1, 2, BACKSPACE, 23.44); + ftf.test(3, 3, DELETE, .23); + ftf.test(1, 2, BACKSPACE, .02); + } + + void testCurrencyFormat() { + NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US); + TestFormattedTextField ftf = create(format); + ftf.setValue(56L); + + System.err.println("Testing NumberFormat.getCurrencyInstance(Locale.US)"); + + // test inserting individual characters + ftf.test(1, 0, "1", 16L); + ftf.test(3, 0, "2", 162L); + ftf.test(2, 0, "0", 102L); + + // test inserting several characters at once - e.g. from clipboard + ftf.test(1, 0, "1024", 1024L); + ftf.test(4, 0, "333", 10333L); + ftf.test(7, 0, "77", 1033377L); + ftf.test(5, 0, "99", 1039977L); + ftf.test(7, 0, "00", 1039007L); + + // test inserting strings that contain some formatting + ftf.test(1, 0, "2,2", 229007L); + ftf.test(3, 0, "2,2", 22227L); + ftf.test(4, 0, "2,2", 2222L); + ftf.test(6, 0, "33,33", 22223333L); + + // test delete + ftf.test(1, 0, DELETE, 2223333L); + ftf.test(10, 0, DELETE, 2223333L); + ftf.test(5, 0, DELETE, 222333L); + ftf.test(5, 0, DELETE, 22233L); + + // test backspace + ftf.test(1, 0, BACKSPACE, 22233L); + ftf.test(7, 0, BACKSPACE, 2223L); + ftf.test(4, 0, BACKSPACE, 223L); + ftf.test(2, 0, BACKSPACE, 23L); + + // test replacing selection + ftf.test(1, 1, "555", 5553L); + ftf.test(4, 2, "555", 55555L); + ftf.test(2, 3, "1", 5155L); + ftf.test(3, 2, "6", 565L); + ftf.test(1, 3, "111222333444555", 111222333444555L); + + // test deleting selection + ftf.test(1, 2, DELETE, 1222333444555L); + ftf.test(1, 3, BACKSPACE, 22333444555L); + ftf.test(13, 2, DELETE, 223334445L); + ftf.test(10, 2, BACKSPACE, 2233344L); + ftf.test(4, 4, DELETE, 2244L); + ftf.test(1, 4, BACKSPACE, 4L); + } + + void testIntegerFormat() { + NumberFormat format = NumberFormat.getIntegerInstance(Locale.US); + TestFormattedTextField ftf = create(format); + ftf.setValue(56L); + + System.err.println("Testing NumberFormat.getIntegerInstance(Locale.US)"); + + // test inserting individual characters + ftf.test(0, 0, "1", 16L); + ftf.test(2, 0, "2", 162L); + ftf.test(1, 0, "0", 102L); + + // test inserting several characters at once - e.g. from clipboard + ftf.test(0, 0, "1024", 1024L); + ftf.test(3, 0, "333", 10333L); + ftf.test(6, 0, "77", 1033377L); + ftf.test(4, 0, "99", 1039977L); + ftf.test(6, 0, "00", 1039007L); + + // test inserting strings that contain some formatting + ftf.test(0, 0, "2,2", 229007L); + ftf.test(2, 0, "2,2", 22227L); + ftf.test(3, 0, "2,2", 2222L); + ftf.test(5, 0, "33,33", 22223333L); + + // test delete + ftf.test(0, 0, DELETE, 2223333L); + ftf.test(9, 0, DELETE, 2223333L); + ftf.test(4, 0, DELETE, 222333L); + ftf.test(4, 0, DELETE, 22233L); + + // test backspace + ftf.test(0, 0, BACKSPACE, 22233L); + ftf.test(6, 0, BACKSPACE, 2223L); + ftf.test(2, 0, BACKSPACE, 223L); + ftf.test(2, 0, BACKSPACE, 23L); + + // test replacing selection + ftf.test(0, 1, "555", 5553L); + ftf.test(3, 2, "555", 55555L); + ftf.test(1, 3, "1", 5155L); + ftf.test(2, 2, "6", 565L); + ftf.test(0, 3, "111222333444555", 111222333444555L); + + // test deleting selection + ftf.test(0, 2, DELETE, 1222333444555L); + ftf.test(0, 3, BACKSPACE, 22333444555L); + ftf.test(12, 2, DELETE, 223334445L); + ftf.test(9, 2, BACKSPACE, 2233344L); + ftf.test(3, 4, DELETE, 2244L); + ftf.test(0, 4, BACKSPACE, 4L); + } + + Date date(DateFormat format, String spec) { + try { + return format.parse(spec); + } catch (ParseException e) { + throw new Error("Error in test"); + } + } + + void testDateFormat() { + DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.US); + TestFormattedTextField ftf = create(format); + ftf.setValue(date(format, "12/05/2005")); + + System.err.println("Testing SimpleDateFormat(\"MM/dd/yyyy\", Locale.US)"); + + // test inserting individual characters + ftf.test(0, 0, "0", date(format, "02/05/2005")); + ftf.test(4, 0, "4", date(format, "02/04/2005")); + ftf.test(6, 0, "1", date(format, "02/04/1005")); + ftf.test(9, 0, "9", date(format, "02/04/1009")); + + // test inserting several characters at once - e.g. from clipboard + ftf.test(0, 0, "11", date(format, "11/04/1009")); + ftf.test(3, 0, "23", date(format, "11/23/1009")); + ftf.test(6, 0, "191", date(format, "11/23/1919")); + + // test delete + ftf.test(0, 0, DELETE, date(format, "01/23/1919")); + ftf.test(3, 0, DELETE, date(format, "01/03/1919")); + ftf.test(10, 0, DELETE, date(format, "01/03/1919")); + ftf.test(1, 0, DELETE, date(format, "12/03/1918")); + ftf.test(4, 0, DELETE, date(format, "11/30/1918")); + + // test backspace + ftf.test(0, 0, BACKSPACE, date(format, "11/30/1918")); + ftf.test(1, 0, BACKSPACE, date(format, "01/30/1918")); + ftf.test(4, 0, BACKSPACE, date(format, "12/31/1917")); + ftf.test(10, 0, BACKSPACE, date(format, "12/31/0191")); + ftf.test(3, 0, BACKSPACE, date(format, "01/31/0191")); + ftf.test(5, 0, BACKSPACE, date(format, "01/03/0191")); + + // test replacing selection + ftf.test(0, 1, "1", date(format, "11/03/0191")); + ftf.test(3, 1, "2", date(format, "11/23/0191")); + ftf.test(6, 2, "20", date(format, "11/23/2091")); + + // test deleting selection + ftf.test(0, 1, BACKSPACE, date(format, "01/23/2091")); + ftf.test(3, 1, DELETE, date(format, "01/03/2091")); + ftf.test(6, 2, BACKSPACE, date(format, "01/03/0091")); + ftf.test(8, 1, DELETE, date(format, "01/03/0001")); + } +} diff --git a/jdk/test/sun/net/ftp/FtpGetContent.java b/jdk/test/sun/net/ftp/FtpGetContent.java index 46428dd3f14..c736fd43752 100644 --- a/jdk/test/sun/net/ftp/FtpGetContent.java +++ b/jdk/test/sun/net/ftp/FtpGetContent.java @@ -391,6 +391,10 @@ public class FtpGetContent { done = true; } + synchronized boolean done() { + return done; + } + synchronized public void setPortEnabled(boolean ok) { portEnabled = ok; } @@ -431,12 +435,13 @@ public class FtpGetContent { public void run() { try { Socket client; - while (!done) { + while (!done()) { client = server.accept(); (new FtpServerHandler(client)).start(); } - server.close(); } catch(Exception e) { + } finally { + try { server.close(); } catch (IOException unused) {} } } } @@ -463,18 +468,13 @@ public class FtpGetContent { bytesRead = stream.read(buffer); } stream.close(); - server.terminate(); - server.interrupt(); if (totalBytes != filesize) throw new RuntimeException("wrong file size!"); } catch (IOException e) { - try { - server.terminate(); - server.interrupt(); - } catch (Exception e2) { - } throw new RuntimeException(e.getMessage()); + } finally { + server.terminate(); + server.server.close(); } } - } diff --git a/jdk/test/sun/net/ftp/FtpURL.java b/jdk/test/sun/net/ftp/FtpURL.java index c642fb38b32..1d50e49ba20 100644 --- a/jdk/test/sun/net/ftp/FtpURL.java +++ b/jdk/test/sun/net/ftp/FtpURL.java @@ -438,8 +438,9 @@ public class FtpURL { client = server.accept(); (new FtpServerHandler(client)).run(); } - server.close(); } catch(Exception e) { + } finally { + try { server.close(); } catch (IOException unused) {} } } } @@ -448,10 +449,9 @@ public class FtpURL { } public FtpURL() throws Exception { - FtpServer server = null; + FtpServer server = new FtpServer(0); BufferedReader in = null; try { - server = new FtpServer(0); server.start(); int port = server.getPort(); @@ -497,17 +497,14 @@ public class FtpURL { throw new RuntimeException("Incorrect filename received"); if (! "/usr".equals(server.pwd())) throw new RuntimeException("Incorrect pwd received"); - in.close(); // We're done! } catch (Exception e) { - try { - in.close(); - server.terminate(); - server.interrupt(); - } catch(Exception ex) { - } throw new RuntimeException("FTP support error: " + e.getMessage()); + } finally { + try { in.close(); } catch (IOException unused) {} + server.terminate(); + server.server.close(); } } } diff --git a/jdk/test/sun/net/www/http/ChunkedInputStream/ChunkedEncodingWithProgressMonitorTest.java b/jdk/test/sun/net/www/http/ChunkedInputStream/ChunkedEncodingWithProgressMonitorTest.java index 1fc3767cd8e..b2cdf6ec042 100644 --- a/jdk/test/sun/net/www/http/ChunkedInputStream/ChunkedEncodingWithProgressMonitorTest.java +++ b/jdk/test/sun/net/www/http/ChunkedInputStream/ChunkedEncodingWithProgressMonitorTest.java @@ -30,9 +30,7 @@ * @summary ChunkedEncoding unit test; MeteredStream/ProgressData problem */ -import java.io.*; import java.net.*; -import java.security.*; import java.util.BitSet; import sun.net.ProgressMeteringPolicy; import sun.net.ProgressMonitor; @@ -42,8 +40,10 @@ import sun.net.ProgressEvent; public class ChunkedEncodingWithProgressMonitorTest { public static void main (String[] args) throws Exception { ProgressMonitor.setMeteringPolicy(new MyProgressMeteringPolicy()); - ProgressMonitor.getDefault().addProgressListener(new MyProgressListener()); + ProgressListener listener = new MyProgressListener(); + ProgressMonitor.getDefault().addProgressListener(listener); ChunkedEncodingTest.test(); + ProgressMonitor.getDefault().removeProgressListener(listener); if (flag.cardinality() != 3) { throw new RuntimeException("All three methods in ProgressListener"+ diff --git a/jdk/test/sun/net/www/http/ChunkedOutputStream/Test.java b/jdk/test/sun/net/www/http/ChunkedOutputStream/Test.java index 10026cf9412..48d365a7c38 100644 --- a/jdk/test/sun/net/www/http/ChunkedOutputStream/Test.java +++ b/jdk/test/sun/net/www/http/ChunkedOutputStream/Test.java @@ -34,7 +34,7 @@ import com.sun.net.httpserver.*; public class Test implements HttpHandler { - static int count = 0; + static volatile int count = 0; static final String str1 = "Helloworld1234567890abcdefghijklmnopqrstuvwxyz"+ "1234567890abcdefkjsdlkjflkjsldkfjlsdkjflkj"+ @@ -46,9 +46,9 @@ public class Test implements HttpHandler { public void handle(HttpExchange exchange) { String reqbody; try { - switch (count) { - case 0: /* test1 -- keeps conn alive */ - case 1: /* test2 -- closes conn */ + switch (exchange.getRequestURI().toString()) { + case "/test/test1": /* test1 -- keeps conn alive */ + case "/test/test2": /* test2 -- closes conn */ printRequestURI(exchange); reqbody = read(exchange.getRequestBody()); if (!reqbody.equals(str1)) { @@ -72,7 +72,7 @@ public class Test implements HttpHandler { resHeaders.set("Connection", "close"); } break; - case 2: /* test 3 */ + case "/test/test3": /* test 3 */ printRequestURI(exchange); reqbody = read(exchange.getRequestBody()); @@ -93,19 +93,19 @@ public class Test implements HttpHandler { exchange.sendResponseHeaders(200, reqbody.length()); write(exchange.getResponseBody(), reqbody); break; - case 3: /* test 4 */ - case 4: /* test 5 */ + case "/test/test4": /* test 4 */ + case "/test/test5": /* test 5 */ printRequestURI(exchange); break; - case 5: /* test 6 */ + case "/test/test6": /* test 6 */ printRequestURI(exchange); resHeaders = exchange.getResponseHeaders() ; resHeaders.set("Location", "http://foo.bar/"); resHeaders.set("Connection", "close"); exchange.sendResponseHeaders(307, 0); break; - case 6: /* test 7 */ - case 7: /* test 8 */ + case "/test/test7": /* test 7 */ + case "/test/test8": /* test 8 */ printRequestURI(exchange); reqbody = read(exchange.getRequestBody()); if (reqbody != null && !"".equals(reqbody)) { @@ -116,7 +116,7 @@ public class Test implements HttpHandler { resHeaders.set("Connection", "close"); exchange.sendResponseHeaders(200, 0); break; - case 8: /* test 9 */ + case "/test/test9": /* test 9 */ printRequestURI(exchange); reqbody = read(exchange.getRequestBody()); if (!reqbody.equals(str1)) { @@ -134,7 +134,7 @@ public class Test implements HttpHandler { exchange.sendResponseHeaders(200, reqbody.length()); write(exchange.getResponseBody(), reqbody); break; - case 9: /* test10 */ + case "/test/test10": /* test10 */ printRequestURI(exchange); InputStream is = exchange.getRequestBody(); String s = read (is, str1.length()); @@ -158,7 +158,7 @@ public class Test implements HttpHandler { exchange.sendResponseHeaders(200, 0); } break; - case 10: /* test11 */ + case "/test/test11": /* test11 */ printRequestURI(exchange); is = exchange.getRequestBody(); s = read (is, str1.length()); @@ -182,7 +182,7 @@ public class Test implements HttpHandler { exchange.sendResponseHeaders(200, 0); } break; - case 11: /* test12 */ + case "/test/test12": /* test12 */ printRequestURI(exchange); is = exchange.getRequestBody(); @@ -203,8 +203,8 @@ public class Test implements HttpHandler { } break; } - exchange.close(); count ++; + exchange.close(); } catch (IOException e) { e.printStackTrace(); } diff --git a/jdk/test/sun/net/www/http/HttpClient/B6726695.java b/jdk/test/sun/net/www/http/HttpClient/B6726695.java index e601ea70cf7..9e69e8e3d46 100644 --- a/jdk/test/sun/net/www/http/HttpClient/B6726695.java +++ b/jdk/test/sun/net/www/http/HttpClient/B6726695.java @@ -147,6 +147,8 @@ public class B6726695 extends Thread { serverIgnore(s); } catch (IOException e) { e.printStackTrace(); + } finally { + try { server.close(); } catch (IOException unused) {} } } diff --git a/jdk/test/sun/net/www/http/HttpClient/MultiThreadTest.java b/jdk/test/sun/net/www/http/HttpClient/MultiThreadTest.java index 1118365c213..750e4d0d009 100644 --- a/jdk/test/sun/net/www/http/HttpClient/MultiThreadTest.java +++ b/jdk/test/sun/net/www/http/HttpClient/MultiThreadTest.java @@ -100,11 +100,12 @@ public class MultiThreadTest extends Thread { } } catch (Exception e) { throw new RuntimeException (e.getMessage()); - } - synchronized (threadlock) { - threadCounter --; - if (threadCounter == 0) { - threadlock.notifyAll(); + } finally { + synchronized (threadlock) { + threadCounter --; + if (threadCounter == 0) { + threadlock.notifyAll(); + } } } } diff --git a/jdk/test/sun/net/www/http/HttpClient/ProxyTest.java b/jdk/test/sun/net/www/http/HttpClient/ProxyTest.java index e67fd82ac7f..62395f6fc2c 100644 --- a/jdk/test/sun/net/www/http/HttpClient/ProxyTest.java +++ b/jdk/test/sun/net/www/http/HttpClient/ProxyTest.java @@ -47,7 +47,7 @@ public class ProxyTest { private class HttpProxyServer extends Thread { private ServerSocket server; private int port; - private boolean done = false; + private volatile boolean done = false; private String askedUrl; /** @@ -125,12 +125,8 @@ public class ProxyTest { } } - public HttpProxyServer(int port) { - this.port = port; - } - - public HttpProxyServer() { - this(0); + public HttpProxyServer() throws IOException { + server = new ServerSocket(0); } public int getPort() { @@ -148,51 +144,49 @@ public class ProxyTest { */ synchronized public void terminate() { done = true; + try { server.close(); } catch (IOException unused) {} } public void run() { try { - server = new ServerSocket(port); Socket client; while (!done) { client = server.accept(); (new HttpProxyHandler(client)).start(); } - server.close(); } catch (Exception e) { + } finally { + try { server.close(); } catch (IOException unused) {} } } } - public static void main(String[] args) { + public static void main(String[] args) throws Exception { ProxyTest test = new ProxyTest(); } - public ProxyTest() { + public ProxyTest() throws Exception { + BufferedReader in = null; String testURL = "ftp://anonymous:password@myhost.mydomain/index.html"; HttpProxyServer server = new HttpProxyServer(); try { - server.start(); - int port = 0; - while (port == 0) { - Thread.sleep(500); - port = server.getPort(); - } + server.start(); + int port = server.getPort(); - System.setProperty("ftp.proxyHost","localhost"); - System.setProperty("ftp.proxyPort", String.valueOf(port)); - URL url = new URL(testURL); - InputStream ins = url.openStream(); - BufferedReader in = new BufferedReader(new InputStreamReader(ins)); - String line; - do { - line = in.readLine(); - } while (line != null); - in.close(); - server.terminate(); - server.interrupt(); + Proxy ftpProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", port)); + URL url = new URL(testURL); + InputStream ins = (url.openConnection(ftpProxy)).getInputStream(); + in = new BufferedReader(new InputStreamReader(ins)); + String line; + do { + line = in.readLine(); + } while (line != null); + in.close(); } catch (Exception e) { e.printStackTrace(); + } finally { + server.terminate(); + try { in.close(); } catch (IOException unused) {} } /* * If the URLs don't match, we've got a bug! diff --git a/jdk/test/sun/net/www/http/KeepAliveCache/KeepAliveTimerThread.java b/jdk/test/sun/net/www/http/KeepAliveCache/KeepAliveTimerThread.java index f0cdf6c77b9..6868de89234 100644 --- a/jdk/test/sun/net/www/http/KeepAliveCache/KeepAliveTimerThread.java +++ b/jdk/test/sun/net/www/http/KeepAliveCache/KeepAliveTimerThread.java @@ -91,9 +91,10 @@ public class KeepAliveTimerThread { out.flush(); s.close(); - server.close(); } catch (Exception e) { e.printStackTrace(); + } finally { + try { server.close(); } catch (IOException unused) {} } } } @@ -118,6 +119,8 @@ public class KeepAliveTimerThread { if (grp.activeCount() > 0) { throw new RuntimeException("Keep-alive thread started in wrong thread group"); } + + grp.destroy(); } } diff --git a/jdk/test/sun/net/www/http/KeepAliveStream/KeepAliveStreamCloseWithWrongContentLength.java b/jdk/test/sun/net/www/http/KeepAliveStream/KeepAliveStreamCloseWithWrongContentLength.java index 866e62e9dd8..18f978c5c41 100644 --- a/jdk/test/sun/net/www/http/KeepAliveStream/KeepAliveStreamCloseWithWrongContentLength.java +++ b/jdk/test/sun/net/www/http/KeepAliveStream/KeepAliveStreamCloseWithWrongContentLength.java @@ -43,10 +43,6 @@ public class KeepAliveStreamCloseWithWrongContentLength { srv = s; } - Socket getSocket () { - return (s); - } - public void run() { try { s = srv.accept (); @@ -57,7 +53,7 @@ public class KeepAliveStreamCloseWithWrongContentLength { is.read(); } OutputStreamWriter ow = - new OutputStreamWriter(s.getOutputStream()); + new OutputStreamWriter((os = s.getOutputStream())); ow.write("HTTP/1.0 200 OK\n"); // Note: The client expects 10 bytes. @@ -71,19 +67,16 @@ public class KeepAliveStreamCloseWithWrongContentLength { // Note: The (buggy) server only sends 9 bytes. ow.write("123456789"); ow.flush(); - ow.close(); } catch (Exception e) { + } finally { + try {if (os != null) { os.close(); }} catch (IOException e) {} } } } - /* - * - */ - - public static void main (String[] args) { + public static void main (String[] args) throws Exception { + ServerSocket serversocket = new ServerSocket (0); try { - ServerSocket serversocket = new ServerSocket (0); int port = serversocket.getLocalPort (); XServer server = new XServer (serversocket); server.start (); @@ -100,11 +93,12 @@ public class KeepAliveStreamCloseWithWrongContentLength { } } is.close(); - server.getSocket().close (); } catch (IOException e) { return; } catch (NullPointerException e) { throw new RuntimeException (e); + } finally { + if (serversocket != null) serversocket.close(); } } } diff --git a/jdk/test/sun/net/www/httptest/HttpServer.java b/jdk/test/sun/net/www/httptest/HttpServer.java index 0a999b8a596..8fcca408f7d 100644 --- a/jdk/test/sun/net/www/httptest/HttpServer.java +++ b/jdk/test/sun/net/www/httptest/HttpServer.java @@ -188,6 +188,7 @@ public class HttpServer { sock.configureBlocking (false); sock.register (selector, SelectionKey.OP_READ); nconn ++; + System.out.println("SERVER: new connection. chan[" + sock + "]"); if (nconn == maxconn) { /* deregister */ listenerKey.cancel (); @@ -197,7 +198,9 @@ public class HttpServer { if (key.isReadable()) { boolean closed; SocketChannel chan = (SocketChannel) key.channel(); + System.out.println("SERVER: connection readable. chan[" + chan + "]"); if (key.attachment() != null) { + System.out.println("Server: comsume"); closed = consume (chan); } else { closed = read (chan, key); @@ -375,6 +378,7 @@ public class HttpServer { synchronized void orderlyCloseChannel (SelectionKey key) throws IOException { SocketChannel ch = (SocketChannel)key.channel (); + System.out.println("SERVER: orderlyCloseChannel chan[" + ch + "]"); ch.socket().shutdownOutput(); key.attach (this); clist.add (key); @@ -382,6 +386,8 @@ public class HttpServer { synchronized void abortiveCloseChannel (SelectionKey key) throws IOException { SocketChannel ch = (SocketChannel)key.channel (); + System.out.println("SERVER: abortiveCloseChannel chan[" + ch + "]"); + Socket s = ch.socket (); s.setSoLinger (true, 0); ch.close(); diff --git a/jdk/test/sun/net/www/protocol/http/DigestTest.java b/jdk/test/sun/net/www/protocol/http/DigestTest.java index ba17d52940d..c9d82fdc264 100644 --- a/jdk/test/sun/net/www/protocol/http/DigestTest.java +++ b/jdk/test/sun/net/www/protocol/http/DigestTest.java @@ -95,10 +95,11 @@ class DigestServer extends Thread { os.write (reply.getBytes()); Thread.sleep (2000); s1.close (); - } - catch (Exception e) { + } catch (Exception e) { System.out.println (e); e.printStackTrace(); + } finally { + try { s.close(); } catch (IOException unused) {} } } @@ -204,15 +205,12 @@ public class DigestTest { public static void main(String[] args) throws Exception { - int nLoops = 1; - int nSize = 10; - int port, n =0; - byte b[] = new byte[nSize]; + int port; DigestServer server; ServerSocket sock; try { - sock = new ServerSocket (5000); + sock = new ServerSocket (0); port = sock.getLocalPort (); } catch (Exception e) { @@ -225,21 +223,18 @@ public class DigestTest { boolean passed = false; try { - Authenticator.setDefault (new MyAuthenticator ()); String s = "http://localhost:" + port + DigestServer.uri; URL url = new URL(s); java.net.URLConnection conURL = url.openConnection(); InputStream in = conURL.getInputStream(); - int c; - while ((c = in.read ()) != -1) { - } + while (in.read () != -1) {} in.close (); - } - catch(ProtocolException e) { + } catch(ProtocolException e) { passed = true; } + if (!passed) { throw new RuntimeException ("Expected a ProtocolException from wrong password"); } diff --git a/jdk/test/sun/security/krb5/ConfPlusProp.java b/jdk/test/sun/security/krb5/ConfPlusProp.java index f6304a131b0..e29637b1b15 100644 --- a/jdk/test/sun/security/krb5/ConfPlusProp.java +++ b/jdk/test/sun/security/krb5/ConfPlusProp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -24,6 +24,7 @@ * @test * @bug 6857795 * @bug 6858589 + * @bug 6972005 * @summary krb5.conf ignored if system properties on realm and kdc are provided */ @@ -96,7 +97,8 @@ public class ConfPlusProp { System.setProperty("java.security.krb5.conf", "i-am-not-a file"); refresh(); - checkDefaultRealm(null); + // Default realm might come from DNS + //checkDefaultRealm(null); check("R1", null); check("R2", null); check("R3", null); diff --git a/jdk/test/sun/security/krb5/confplusprop.conf b/jdk/test/sun/security/krb5/confplusprop.conf index 80c925b14cd..5e499483348 100644 --- a/jdk/test/sun/security/krb5/confplusprop.conf +++ b/jdk/test/sun/security/krb5/confplusprop.conf @@ -1,6 +1,7 @@ [libdefaults] default_realm = R1 forwardable = well +dns_lookup_realm = false [realms] R1 = { diff --git a/jdk/test/sun/security/krb5/confplusprop2.conf b/jdk/test/sun/security/krb5/confplusprop2.conf index df00eccbccf..c55464bd846 100644 --- a/jdk/test/sun/security/krb5/confplusprop2.conf +++ b/jdk/test/sun/security/krb5/confplusprop2.conf @@ -1,3 +1,6 @@ +[libdefaults] +dns_lookup_realm = false + [realms] R1 = { kdc = k12 diff --git a/jdk/test/sun/security/util/DerOutputStream/LocaleInTime.java b/jdk/test/sun/security/util/DerOutputStream/LocaleInTime.java new file mode 100644 index 00000000000..dd942680d2e --- /dev/null +++ b/jdk/test/sun/security/util/DerOutputStream/LocaleInTime.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 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. + */ + +/* + * @test + * @bug 6670889 + * @summary Keystore created under Hindi Locale causing ArrayIndexOutOfBoundsException + * @run main/othervm -Duser.language=hi -Duser.region=IN LocaleInTime + */ + +import java.util.Date; +import sun.security.util.DerOutputStream; +import sun.security.util.DerValue; + +public class LocaleInTime { + public static void main(String args[]) throws Exception { + DerOutputStream out = new DerOutputStream(); + out.putUTCTime(new Date()); + DerValue val = new DerValue(out.toByteArray()); + System.out.println(val.getUTCTime()); + } +} diff --git a/jdk/test/sun/security/x509/AlgorithmId/TurkishRegion.java b/jdk/test/sun/security/x509/AlgorithmId/TurkishRegion.java new file mode 100644 index 00000000000..5ca91e02677 --- /dev/null +++ b/jdk/test/sun/security/x509/AlgorithmId/TurkishRegion.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 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. + */ + +/* + * @test + * @bug 6867345 + * @summary Turkish regional options cause NPE in + * sun.security.x509.AlgorithmId.algOID + * @run main/othervm -Duser.language=tr -Duser.region=TR TurkishRegion + * @author Xuelei Fan + */ + +import sun.security.x509.*; + +public class TurkishRegion { + + public static void main(String[] args) throws Exception { + AlgorithmId algId = AlgorithmId.get("PBEWITHMD5ANDDES"); + } +} diff --git a/jdk/test/sun/tools/common/ApplicationSetup.sh b/jdk/test/sun/tools/common/ApplicationSetup.sh index ea2dec2e654..a04989f502e 100644 --- a/jdk/test/sun/tools/common/ApplicationSetup.sh +++ b/jdk/test/sun/tools/common/ApplicationSetup.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. +# 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 @@ -24,54 +24,187 @@ # -# Support function to start and stop a given application +# Support functions to start, stop, wait for or kill a given SimpleApplication -# Starts a given application as background process, usage: -# startApplication [args...] +# Starts a given app as background process, usage: +# startApplication port-file [args...] +# +# The following variables are set: +# +# appJavaPid - application's Java pid +# appOtherPid - pid associated with the app other than appJavaPid +# appPidList - all pids associated with the app +# appOutput - file containing stdout and stderr from the app +# +# Waits for at least one line of output from the app to indicate +# that it is up and running. # -# Waits for application to print something to indicate it is running -# (and initialized). Output is directed to ${TESTCLASSES}/Application.out. -# Sets $pid to be the process-id of the application. - startApplication() { - OUTPUTFILE=${TESTCLASSES}/Application.out - ${JAVA} $1 $2 $3 $4 $5 $6 > ${OUTPUTFILE} & - pid="$!" - - # MKS creates an intermediate shell to launch ${JAVA} so - # ${pid} is not the actual pid. We have put in a small sleep - # to give the intermediate shell process time to launch the - # "java" process. - if [ "$OS" = "Windows" ]; then - sleep 2 - if [ "${isCygwin}" = "true" ] ; then - realpid=`ps -p ${pid} | tail -1 | awk '{print $4;}'` - else - realpid=`ps -o pid,ppid,comm|grep ${pid}|grep "java"|cut -c1-6` - fi - pid=${realpid} - fi - - echo "Waiting for Application to initialize..." - attempts=0 + appOutput="${TESTCLASSES}/Application.out" + + ${JAVA} -classpath "${TESTCLASSES}" "$@" > "$appOutput" 2>&1 & + appJavaPid="$!" + appOtherPid= + appPidList="$appJavaPid" + + echo "INFO: waiting for $1 to initialize..." + _cnt=0 while true; do + # if the app doesn't start then the JavaTest/JTREG timeout will + # kick in so this isn't really a endless loop sleep 1 - out=`tail -1 ${OUTPUTFILE}` - if [ ! -z "$out" ]; then + out=`tail -1 "$appOutput"` + if [ -n "$out" ]; then + # we got some output from the app so it's running break fi - attempts=`expr $attempts + 1` - echo "Waiting $attempts second(s) ..." + _cnt=`expr $_cnt + 1` + echo "INFO: waited $_cnt second(s) ..." done + unset _cnt - echo "Application is process $pid" + if $isWindows; then + # Windows requires special handling + appOtherPid="$appJavaPid" + + if $isCygwin; then + appJavaPid=`ps -p "$appOtherPid" \ + | sed -n ' + # See if $appOtherPid is in PID column; there are sometimes + # non-blanks in column 1 (I and S observed so far) + /^.'"${PATTERN_WS}${PATTERN_WS}*${appOtherPid}${PATTERN_WS}"'/{ + # strip PID column + s/^.'"${PATTERN_WS}${PATTERN_WS}*${appOtherPid}${PATTERN_WS}${PATTERN_WS}"'*// + # strip PPID column + s/^[1-9][0-9]*'"${PATTERN_WS}${PATTERN_WS}"'*// + # strip PGID column + s/^[1-9][0-9]*'"${PATTERN_WS}${PATTERN_WS}"'*// + # strip everything after WINPID column + s/'"${PATTERN_WS}"'.*// + p + q + } + '` + echo "INFO: Cygwin pid=$appOtherPid maps to Windows pid=$appJavaPid" + else + # show PID, PPID and COMM columns only + appJavaPid=`ps -o pid,ppid,comm \ + | sed -n ' + # see if appOtherPid is in either PID or PPID columns + /'"${PATTERN_WS}${appOtherPid}${PATTERN_WS}"'/{ + # see if this is a java command + /java'"${PATTERN_EOL}"'/{ + # strip leading white space + s/^'"${PATTERN_WS}${PATTERN_WS}"'*// + # strip everything after the first word + s/'"${PATTERN_WS}"'.*// + # print the pid and we are done + p + q + } + } + '` + echo "INFO: MKS shell pid=$appOtherPid; Java pid=$appJavaPid" + fi + + if [ -z "$appJavaPid" ]; then + echo "ERROR: could not find app's Java pid." >&2 + killApplication + exit 2 + fi + appPidList="$appOtherPid $appJavaPid" + fi + + echo "INFO: $1 is process $appJavaPid" + echo "INFO: $1 output is in $appOutput" } -# Stops an application by invoking the given class and argument, usage: -# stopApplication + +# Stops a simple application by invoking ShutdownSimpleApplication +# class with a specific port-file, usage: +# stopApplication port-file +# +# Note: When this function returns, the SimpleApplication (or a subclass) +# may still be running because the application has not yet reached the +# shutdown check. +# stopApplication() { - $JAVA -classpath "${TESTCLASSES}" $1 $2 + $JAVA -classpath "${TESTCLASSES}" ShutdownSimpleApplication $1 } + +# Wait for a simple application to stop running. +# +waitForApplication() { + if [ $isWindows = false ]; then + # non-Windows is easy; just one process + echo "INFO: waiting for $appJavaPid" + set +e + wait "$appJavaPid" + set -e + + elif $isCygwin; then + # Cygwin pid and not the Windows pid + echo "INFO: waiting for $appOtherPid" + set +e + wait "$appOtherPid" + set -e + + else # implied isMKS + # MKS has intermediate shell and Java process + echo "INFO: waiting for $appJavaPid" + + # appJavaPid can be empty if pid search in startApplication() failed + if [ -n "$appJavaPid" ]; then + # only need to wait for the Java process + set +e + wait "$appJavaPid" + set -e + fi + fi +} + + +# Kills a simple application by sending a SIGTERM to the appropriate +# process(es); on Windows SIGQUIT (-9) is used. +# +killApplication() +{ + if [ $isWindows = false ]; then + # non-Windows is easy; just one process + echo "INFO: killing $appJavaPid" + set +e + kill -TERM "$appJavaPid" # try a polite SIGTERM first + sleep 2 + # send SIGQUIT (-9) just in case SIGTERM didn't do it + # but don't show any complaints + kill -QUIT "$appJavaPid" > /dev/null 2>&1 + wait "$appJavaPid" + set -e + + elif $isCygwin; then + # Cygwin pid and not the Windows pid + echo "INFO: killing $appOtherPid" + set +e + kill -9 "$appOtherPid" + wait "$appOtherPid" + set -e + + else # implied isMKS + # MKS has intermediate shell and Java process + echo "INFO: killing $appPidList" + set +e + kill -9 $appPidList + set -e + + # appJavaPid can be empty if pid search in startApplication() failed + if [ -n "$appJavaPid" ]; then + # only need to wait for the Java process + set +e + wait "$appJavaPid" + set -e + fi + fi +} diff --git a/jdk/test/sun/tools/common/CommonSetup.sh b/jdk/test/sun/tools/common/CommonSetup.sh index ab8f7fdb13d..02fbc60d165 100644 --- a/jdk/test/sun/tools/common/CommonSetup.sh +++ b/jdk/test/sun/tools/common/CommonSetup.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. +# 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 @@ -24,56 +24,94 @@ # -# Common setup for tool tests. +# Common setup for tool tests and other tests that use jtools. # Checks that TESTJAVA, TESTSRC, and TESTCLASSES environment variables are set. -# Creates the following for use by the tool tests -# JAVA java launcher -# JSTACK jstack utility -# JMAP jmap utility -# JINFO jinfo utility -# JHAT jhat utility -# PS path separator (";" or ":") -# OS operating system +# +# Creates the following constants for use by the caller: +# JAVA - java launcher +# JHAT - jhat utility +# JINFO - jinfo utility +# JMAP - jmap utility +# JPS - jps utility +# JSTACK - jstack utility +# OS - operating system name +# PATTERN_EOL - grep or sed end-of-line pattern +# PATTERN_WS - grep or sed whitespace pattern +# PS - path separator (";" or ":") +# +# Sets the following variables: +# +# isCygwin - true if environment is Cygwin +# isMKS - true if environment is MKS +# isLinux - true if OS is Linux +# isSolaris - true if OS is Solaris +# isWindows - true if OS is Windows -if [ "${TESTJAVA}" = "" ] -then - echo "TESTJAVA not set. Test cannot execute. Failed." +if [ -z "${TESTJAVA}" ]; then + echo "ERROR: TESTJAVA not set. Test cannot execute. Failed." exit 1 fi - -if [ "${TESTSRC}" = "" ] -then - echo "TESTSRC not set. Test cannot execute. Failed." + +if [ -z "${TESTSRC}" ]; then + echo "ERROR: TESTSRC not set. Test cannot execute. Failed." exit 1 fi - -if [ "${TESTCLASSES}" = "" ] -then - echo "TESTCLASSES not set. Test cannot execute. Failed." + +if [ -z "${TESTCLASSES}" ]; then + echo "ERROR: TESTCLASSES not set. Test cannot execute. Failed." exit 1 fi - + +# only enable these after checking the expected incoming env variables +set -eu + JAVA="${TESTJAVA}/bin/java" -JSTACK="${TESTJAVA}/bin/jstack" -JMAP="${TESTJAVA}/bin/jmap" -JINFO="${TESTJAVA}/bin/jinfo" JHAT="${TESTJAVA}/bin/jhat" +JINFO="${TESTJAVA}/bin/jinfo" +JMAP="${TESTJAVA}/bin/jmap" +JPS="${TESTJAVA}/bin/jps" +JSTACK="${TESTJAVA}/bin/jstack" + +isCygwin=false +isMKS=false +isLinux=false +isSolaris=false +isUnknownOS=false +isWindows=false OS=`uname -s` +# start with some UNIX like defaults +PATTERN_EOL='$' +# blank and tab +PATTERN_WS='[ ]' +PS=":" + case "$OS" in - Windows* ) - PS=";" - OS="Windows" - ;; CYGWIN* ) - PS=";" OS="Windows" + PATTERN_EOL='[ ]*$' + # blank and tab + PATTERN_WS='[ \t]' isCygwin=true + isWindows=true + ;; + Linux ) + OS="Linux" + isLinux=true + ;; + SunOS ) + OS="Solaris" + isSolaris=true + ;; + Windows* ) + OS="Windows" + PATTERN_EOL='[ ]*$' + PS=";" + isWindows=true ;; * ) - PS=":" + isUnknownOS=true ;; esac - diff --git a/jdk/test/sun/tools/common/CommonTests.sh b/jdk/test/sun/tools/common/CommonTests.sh new file mode 100644 index 00000000000..ae0287a0c32 --- /dev/null +++ b/jdk/test/sun/tools/common/CommonTests.sh @@ -0,0 +1,314 @@ +#!/bin/sh + +# +# Copyright (c) 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. +# + + +# @test +# @bug 6964018 +# @summary Unit test for common tools infrastructure. +# +# @build SimpleApplication SleeperApplication ShutdownSimpleApplication +# @run shell CommonTests.sh + +. ${TESTSRC}/CommonSetup.sh +. ${TESTSRC}/ApplicationSetup.sh + +# hope for the best: +status=0 + + +# Test program path constants from CommonSetup.sh: +# +for name in JAVA JHAT JINFO JMAP JPS JSTACK; do + eval value=$`echo $name` + + echo "INFO: $name=$value" + if [ -x "$value" ]; then + echo "INFO: '$value' is executable." + else + echo "ERROR: '$value' is not executable." >&2 + status=1 + fi +done + + +# Display flag values from CommonSetup.sh: +# +for name in isCygwin isMKS isLinux isSolaris isUnknownOS isWindows; do + eval value=$`echo $name` + echo "INFO: flag $name=$value" +done + + +# Test OS constant from CommonSetup.sh: +# +if [ -z "$OS" ]; then + echo "ERROR: OS constant cannot be empty." >&2 + status=1 +fi + + +# Display the PATTERN_EOL value: +# +echo "INFO: PATTERN_EOL="`echo "$PATTERN_EOL" | od -c` + + +# Test PATTERN_EOL with 'grep' for a regular line. +# +TESTOUT="${TESTCLASSES}/testout.grep_reg_line_eol" +set +e +echo 'regular line' | grep "line${PATTERN_EOL}" > "$TESTOUT" +set -e +if [ -s "$TESTOUT" ]; then + echo "INFO: PATTERN_EOL works for regular line with grep." +else + echo "ERROR: PATTERN_EOL does not work for regular line with grep." >&2 + status=1 +fi + + +if $isWindows; then + # Test PATTERN_EOL with 'grep' for a CR line. + # + TESTOUT="${TESTCLASSES}/testout.grep_cr_line_eol" + set +e + echo 'CR line ' | grep "line${PATTERN_EOL}" > "$TESTOUT" + set -e + if [ -s "$TESTOUT" ]; then + echo "INFO: PATTERN_EOL works for CR line with grep." + else + echo "ERROR: PATTERN_EOL does not work for CR line with grep." >&2 + status=1 + fi +fi + + +# Test PATTERN_EOL with 'sed' for a regular line. +# +TESTOUT="${TESTCLASSES}/testout.sed_reg_line_eol" +echo 'regular line' | sed -n "/line${PATTERN_EOL}/p" > "$TESTOUT" +if [ -s "$TESTOUT" ]; then + echo "INFO: PATTERN_EOL works for regular line with sed." +else + echo "ERROR: PATTERN_EOL does not work for regular line with sed." >&2 + status=1 +fi + + +if $isWindows; then + # Test PATTERN_EOL with 'sed' for a CR line. + # + TESTOUT="${TESTCLASSES}/testout.sed_cr_line_eol" + echo 'CR line ' | sed -n "/line${PATTERN_EOL}/p" > "$TESTOUT" + if [ -s "$TESTOUT" ]; then + echo "INFO: PATTERN_EOL works for CR line with sed." + else + echo "ERROR: PATTERN_EOL does not work for CR line with sed." >&2 + status=1 + fi +fi + + +# Display the PATTERN_WS value: +# +echo "INFO: PATTERN_WS="`echo "$PATTERN_WS" | od -c` + + +# Test PATTERN_WS with 'grep' for a blank. +# +TESTOUT="${TESTCLASSES}/testout.grep_blank" +set +e +echo 'blank: ' | grep "$PATTERN_WS" > "$TESTOUT" +set -e +if [ -s "$TESTOUT" ]; then + echo "INFO: PATTERN_WS works for blanks with grep." +else + echo "ERROR: PATTERN_WS does not work for blanks with grep." >&2 + status=1 +fi + + +# Test PATTERN_WS with 'grep' for a tab. +# +TESTOUT="${TESTCLASSES}/testout.grep_tab" +set +e +echo 'tab: ' | grep "$PATTERN_WS" > "$TESTOUT" +set -e +if [ -s "$TESTOUT" ]; then + echo "INFO: PATTERN_WS works for tabs with grep." +else + echo "ERROR: PATTERN_WS does not work for tabs with grep." >&2 + status=1 +fi + + +# Test PATTERN_WS with 'sed' for a blank. +# +TESTOUT="${TESTCLASSES}/testout.sed_blank" +echo 'blank: ' | sed -n "/$PATTERN_WS/p" > "$TESTOUT" +if [ -s "$TESTOUT" ]; then + echo "INFO: PATTERN_WS works for blanks with sed." +else + echo "ERROR: PATTERN_WS does not work for blanks with sed." >&2 + status=1 +fi + + +# Test PATTERN_WS with 'sed' for a tab. +# +TESTOUT="${TESTCLASSES}/testout.sed_tab" +echo 'tab: ' | sed -n "/$PATTERN_WS/p" > "$TESTOUT" +if [ -s "$TESTOUT" ]; then + echo "INFO: PATTERN_WS works for tabs with sed." +else + echo "ERROR: PATTERN_WS does not work for tabs with sed." >&2 + status=1 +fi + + +# Test startApplication and use PORTFILE for coordination +# The app sleeps for 30 seconds. +# +PORTFILE="${TESTCLASSES}"/shutdown.port +startApplication SleeperApplication "${PORTFILE}" 30 + + +# Test appJavaPid in "ps" cmd output. +# +TESTOUT="${TESTCLASSES}/testout.ps_app" +set +e +if $isCygwin; then + # On Cygwin, appJavaPid is the Windows pid for the Java process + # and appOtherPid is the Cygwin pid for the Java process. + ps -p "$appOtherPid" \ + | grep "${PATTERN_WS}${appJavaPid}${PATTERN_WS}" > "$TESTOUT" +else + # output only pid and comm columns to avoid mismatches + ps -eo pid,comm \ + | grep "^${PATTERN_WS}*${appJavaPid}${PATTERN_WS}" > "$TESTOUT" +fi +set -e +if [ -s "$TESTOUT" ]; then + echo "INFO: begin appJavaPid=$appJavaPid in 'ps' cmd output:" + cat "$TESTOUT" + echo "INFO: end appJavaPid=$appJavaPid in 'ps' cmd output." +else + echo "ERROR: 'ps' cmd should show appJavaPid=$appJavaPid." >&2 + status=1 +fi + +if [ -n "$appOtherPid" ]; then + # Test appOtherPid in "ps" cmd output, if we have one. + # + TESTOUT="${TESTCLASSES}/testout.ps_other" + set +e + if $isCygwin; then + ps -p "$appOtherPid" \ + | grep "${PATTERN_WS}${appOtherPid}${PATTERN_WS}" > "$TESTOUT" + else + # output only pid and comm columns to avoid mismatches + ps -eo pid,comm \ + | grep "^${PATTERN_WS}*${appOtherPid}${PATTERN_WS}" > "$TESTOUT" + fi + set -e + if [ -s "$TESTOUT" ]; then + echo "INFO: begin appOtherPid=$appOtherPid in 'ps' cmd output:" + cat "$TESTOUT" + echo "INFO: end appOtherPid=$appOtherPid in 'ps' cmd output." + else + echo "ERROR: 'ps' cmd should show appOtherPid=$appOtherPid." >&2 + status=1 + fi +fi + + +# Test stopApplication and PORTFILE for coordination +# +stopApplication "${PORTFILE}" + + +# Test application still running after stopApplication. +# +# stopApplication just lets the app know that it can stop, but the +# app might still be doing work. This test just demonstrates that +# fact and doesn't fail if the app is already done. +# +TESTOUT="${TESTCLASSES}/testout.after_stop" +set +e +if $isCygwin; then + # On Cygwin, appJavaPid is the Windows pid for the Java process + # and appOtherPid is the Cygwin pid for the Java process. + ps -p "$appOtherPid" \ + | grep "${PATTERN_WS}${appJavaPid}${PATTERN_WS}" > "$TESTOUT" +else + # output only pid and comm columns to avoid mismatches + ps -eo pid,comm \ + | grep "^${PATTERN_WS}*${appJavaPid}${PATTERN_WS}" > "$TESTOUT" +fi +set -e +if [ -s "$TESTOUT" ]; then + echo "INFO: it is okay for appJavaPid=$appJavaPid to still be running" \ + "after stopApplication() is called." + echo "INFO: begin 'after_stop' output:" + cat "$TESTOUT" + echo "INFO: end 'after_stop' output." +fi + + +# Test waitForApplication +# +# The app might already be gone so this function shouldn't generate +# a fatal error in either call. +# +waitForApplication + +if [ $isWindows = false ]; then + # Windows can recycle pids quickly so we can't use this test there + TESTOUT="${TESTCLASSES}/testout.after_kill" + set +e + # output only pid and comm columns to avoid mismatches + ps -eo pid,comm \ + | grep "^${PATTERN_WS}*${appJavaPid}${PATTERN_WS}" > "$TESTOUT" + set -e + if [ -s "$TESTOUT" ]; then + echo "ERROR: 'ps' cmd should not show appJavaPid." >&2 + echo "ERROR: begin 'after_kill' output:" >&2 + cat "$TESTOUT" >&2 + echo "ERROR: end 'after_kill' output." >&2 + status=1 + else + echo "INFO: 'ps' cmd does not show appJavaPid after" \ + "waitForApplication() is called." + fi +fi + + +# Test killApplication +# +# The app is already be gone so this function shouldn't generate +# a fatal error. +# +killApplication + +exit $status diff --git a/jdk/test/sun/tools/common/ShutdownSimpleApplication.java b/jdk/test/sun/tools/common/ShutdownSimpleApplication.java index 78ef1d31c2d..314bb579bad 100644 --- a/jdk/test/sun/tools/common/ShutdownSimpleApplication.java +++ b/jdk/test/sun/tools/common/ShutdownSimpleApplication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -22,10 +22,13 @@ */ /* + * Used to shutdown SimpleApplication (or a subclass). The argument to + * this class is the name of a file that contains the TCP port number + * on which SimpleApplication (or a subclass) is listening. * - * - * Used to shutdown SimpleApplication. The argument to this class is - * the TCP port number where SimpleApplication is listening. + * Note: When this program returns, the SimpleApplication (or a subclass) + * may still be running because the application has not yet reached the + * shutdown check. */ import java.net.Socket; import java.net.InetSocketAddress; @@ -35,6 +38,11 @@ import java.io.FileInputStream; public class ShutdownSimpleApplication { public static void main(String args[]) throws Exception { + if (args.length != 1) { + throw new RuntimeException("Usage: ShutdownSimpleApplication" + + " port-file"); + } + // read the (TCP) port number from the given file File f = new File(args[0]); @@ -42,21 +50,27 @@ public class ShutdownSimpleApplication { byte b[] = new byte[8]; int n = fis.read(b); if (n < 1) { - throw new RuntimeException("Empty file"); + throw new RuntimeException("Empty port-file"); } fis.close(); String str = new String(b, 0, n, "UTF-8"); - System.out.println("Port number of application is: " + str); + System.out.println("INFO: Port number of SimpleApplication: " + str); int port = Integer.parseInt(str); // Now connect to the port (which will shutdown application) - System.out.println("Connecting to port " + port + - " to shutdown Application ..."); + System.out.println("INFO: Connecting to port " + port + + " to shutdown SimpleApplication ..."); + System.out.flush(); Socket s = new Socket(); s.connect( new InetSocketAddress(port) ); s.close(); + + System.out.println("INFO: done connecting to SimpleApplication."); + System.out.flush(); + + System.exit(0); } } diff --git a/jdk/test/sun/tools/common/SimpleApplication.java b/jdk/test/sun/tools/common/SimpleApplication.java index 050f010a774..c7e6b0bdac4 100644 --- a/jdk/test/sun/tools/common/SimpleApplication.java +++ b/jdk/test/sun/tools/common/SimpleApplication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -22,10 +22,12 @@ */ /* + * A simple application used by unit tests. The first argument to this + * class is the name of a file to which a TCP port number can be written. * - * - * A simple application used for tool unit tests. It does nothing else - * bind to a TCP port and wait for a shutdown message. + * By default, this class does nothing other than bind to a TCP port, + * write the TCP port number to a file, and wait for an incoming connection + * in order to complete the application shutdown protocol. */ import java.net.Socket; import java.net.ServerSocket; @@ -33,25 +35,86 @@ import java.io.File; import java.io.FileOutputStream; public class SimpleApplication { - public static void main(String args[]) throws Exception { + private static SimpleApplication myApp; // simple app or a subclass + private static String myAppName; // simple app name + private static int myPort; // coordination port # + private static ServerSocket mySS; // coordination socket + + // protected so a subclass can extend it; not public so creation is + // limited. + protected SimpleApplication() { + // save simple app (or subclass) name for messages + myAppName = getClass().getName(); + } + + // return the simple application (or a subclass) + final public static SimpleApplication getMyApp() { + return myApp; + } + + // set the simple application (for use by a subclass) + final public static void setMyApp(SimpleApplication _myApp) { + myApp = _myApp; + } + + // execute the application finish protocol + final public void doMyAppFinish(String[] args) throws Exception { + System.out.println("INFO: " + myAppName + " is waiting on port: " + + myPort); + System.out.flush(); + + // wait for test harness to connect + Socket s = mySS.accept(); + s.close(); + mySS.close(); + + System.out.println("INFO: " + myAppName + " is shutting down."); + System.out.flush(); + } + + // execute the application start protocol + final public void doMyAppStart(String[] args) throws Exception { + if (args.length < 1) { + throw new RuntimeException("Usage: " + myAppName + + " port-file [arg(s)]"); + } + // bind to a random port - ServerSocket ss = new ServerSocket(0); - int port = ss.getLocalPort(); + mySS = new ServerSocket(0); + myPort = mySS.getLocalPort(); // Write the port number to the given file File f = new File(args[0]); FileOutputStream fos = new FileOutputStream(f); - fos.write( Integer.toString(port).getBytes("UTF-8") ); + fos.write( Integer.toString(myPort).getBytes("UTF-8") ); fos.close(); - System.out.println("Application waiting on port: " + port); + System.out.println("INFO: " + myAppName + " created socket on port: " + + myPort); + System.out.flush(); + } + + // execute the app work (subclass can override this) + public void doMyAppWork(String[] args) throws Exception { + } + + public static void main(String[] args) throws Exception { + if (myApp == null) { + // create myApp since a subclass hasn't done so + myApp = new SimpleApplication(); + } + + myApp.doMyAppStart(args); // do the app start protocol + + System.out.println("INFO: " + myAppName + " is calling doMyAppWork()"); + System.out.flush(); + myApp.doMyAppWork(args); // do the app work + System.out.println("INFO: " + myAppName + " returned from" + + " doMyAppWork()"); System.out.flush(); - // wait for test harness to connect - Socket s = ss.accept(); - s.close(); - ss.close(); + myApp.doMyAppFinish(args); // do the app finish protocol - System.out.println("Application shutdown."); + System.exit(0); } } diff --git a/jdk/test/sun/tools/common/SleeperApplication.java b/jdk/test/sun/tools/common/SleeperApplication.java new file mode 100644 index 00000000000..b96d9b07ac3 --- /dev/null +++ b/jdk/test/sun/tools/common/SleeperApplication.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 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 example subclass of SimpleApplication that illustrates how to + * override the doMyAppWork() method. + */ + +public class SleeperApplication extends SimpleApplication { + public static int DEFAULT_SLEEP_TIME = 60; // time is in seconds + + // execute the sleeper app work + public void doMyAppWork(String[] args) throws Exception { + int sleep_time = DEFAULT_SLEEP_TIME; + + // args[0] is the port-file + if (args.length < 2) { + System.out.println("INFO: using default sleep time of " + + sleep_time + " seconds."); + } else { + try { + sleep_time = Integer.parseInt(args[1]); + } catch (NumberFormatException nfe) { + throw new RuntimeException("Error: '" + args[1] + + "': is not a valid seconds value."); + } + } + + Thread.sleep(sleep_time * 1000); // our "work" is to sleep + } + + public static void main(String[] args) throws Exception { + SleeperApplication myApp = new SleeperApplication(); + + SimpleApplication.setMyApp(myApp); + + SimpleApplication.main(args); + } +} diff --git a/jdk/test/sun/tools/jhat/ParseTest.sh b/jdk/test/sun/tools/jhat/ParseTest.sh index 35dc84e1f43..9bc9294eb71 100644 --- a/jdk/test/sun/tools/jhat/ParseTest.sh +++ b/jdk/test/sun/tools/jhat/ParseTest.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2006, 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 @@ -32,7 +32,11 @@ # @run shell ParseTest.sh . ${TESTSRC}/../common/CommonSetup.sh -. ${TESTSRC}/../common/ApplicationSetup.sh + +# all return statuses are checked in this test +set +e + +failed=0 DUMPFILE="minimal.bin" diff --git a/jdk/test/sun/tools/jinfo/Basic.sh b/jdk/test/sun/tools/jinfo/Basic.sh index e88db448e14..57f40af414a 100644 --- a/jdk/test/sun/tools/jinfo/Basic.sh +++ b/jdk/test/sun/tools/jinfo/Basic.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2006, 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 @@ -35,53 +35,57 @@ . ${TESTSRC}/../common/CommonSetup.sh . ${TESTSRC}/../common/ApplicationSetup.sh -# Start application (send output to shutdown.port) +# Start application and use PORTFILE for coordination PORTFILE="${TESTCLASSES}"/shutdown.port -startApplication \ - -classpath "${TESTCLASSES}" SimpleApplication "${PORTFILE}" +startApplication SimpleApplication "${PORTFILE}" + +# all return statuses are checked in this test +set +e failed=0 -if [ "$OS" != "Windows" ]; then +if [ $isWindows = false ]; then # -sysprops option - ${JINFO} -sysprops $pid + ${JINFO} -sysprops $appJavaPid if [ $? != 0 ]; then failed=1; fi # -flags option - ${JINFO} -flags $pid + ${JINFO} -flags $appJavaPid if [ $? != 0 ]; then failed=1; fi # no option - ${JINFO} $pid + ${JINFO} $appJavaPid if [ $? != 0 ]; then failed=1; fi fi # -flag option -${JINFO} -flag +PrintGC $pid +${JINFO} -flag +PrintGC $appJavaPid if [ $? != 0 ]; then failed=1; fi -${JINFO} -flag -PrintGC $pid +${JINFO} -flag -PrintGC $appJavaPid if [ $? != 0 ]; then failed=1; fi -${JINFO} -flag PrintGC $pid +${JINFO} -flag PrintGC $appJavaPid if [ $? != 0 ]; then failed=1; fi -if [ "$OS" = "SunOS" ]; then +if $isSolaris; then - ${JINFO} -flag +ExtendedDTraceProbes $pid + ${JINFO} -flag +ExtendedDTraceProbes $appJavaPid if [ $? != 0 ]; then failed=1; fi - ${JINFO} -flag -ExtendedDTraceProbes $pid + ${JINFO} -flag -ExtendedDTraceProbes $appJavaPid if [ $? != 0 ]; then failed=1; fi - ${JINFO} -flag ExtendedDTraceProbes $pid + ${JINFO} -flag ExtendedDTraceProbes $appJavaPid if [ $? != 0 ]; then failed=1; fi fi -stopApplication ShutdownSimpleApplication "${PORTFILE}" +set -e + +stopApplication "${PORTFILE}" +waitForApplication exit $failed - diff --git a/jdk/test/sun/tools/jmap/Basic.sh b/jdk/test/sun/tools/jmap/Basic.sh index 3b4e872e71f..f1c0b34b443 100644 --- a/jdk/test/sun/tools/jmap/Basic.sh +++ b/jdk/test/sun/tools/jmap/Basic.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. +# 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 @@ -35,24 +35,25 @@ . ${TESTSRC}/../common/CommonSetup.sh . ${TESTSRC}/../common/ApplicationSetup.sh -# Start application (send output to shutdown.port) +# Start application and use PORTFILE for coordination PORTFILE="${TESTCLASSES}"/shutdown.port -startApplication \ - -classpath "${TESTCLASSES}" SimpleApplication "${PORTFILE}" +startApplication SimpleApplication "${PORTFILE}" + +# all return statuses are checked in this test +set +e failed=0 # -histo[:live] option -${JMAP} -histo $pid +${JMAP} -histo $appJavaPid if [ $? != 0 ]; then failed=1; fi -${JMAP} -histo:live $pid +${JMAP} -histo:live $appJavaPid if [ $? != 0 ]; then failed=1; fi # -dump option -p=`expr $pid` -DUMPFILE="java_pid${p}.hprof" -${JMAP} -dump:format=b,file=${DUMPFILE} $pid +DUMPFILE="java_pid${appJavaPid}.hprof" +${JMAP} -dump:format=b,file=${DUMPFILE} $appJavaPid if [ $? != 0 ]; then failed=1; fi # check that heap dump is parsable @@ -63,7 +64,7 @@ if [ $? != 0 ]; then failed=1; fi rm ${DUMPFILE} # -dump:live option -${JMAP} -dump:live,format=b,file=${DUMPFILE} $pid +${JMAP} -dump:live,format=b,file=${DUMPFILE} $appJavaPid if [ $? != 0 ]; then failed=1; fi # check that heap dump is parsable @@ -71,9 +72,11 @@ ${JHAT} -parseonly true ${DUMPFILE} if [ $? != 0 ]; then failed=1; fi # dump file is large so remove it -rm ${DUMPFILE} +rm -f ${DUMPFILE} -stopApplication ShutdownSimpleApplication "${PORTFILE}" +set -e + +stopApplication "${PORTFILE}" +waitForApplication exit $failed - diff --git a/jdk/test/sun/tools/jrunscript/common.sh b/jdk/test/sun/tools/jrunscript/common.sh index 3c15672ac3e..2b5bfd652b5 100644 --- a/jdk/test/sun/tools/jrunscript/common.sh +++ b/jdk/test/sun/tools/jrunscript/common.sh @@ -1,5 +1,5 @@ # -# Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. +# 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 @@ -43,10 +43,20 @@ setup() { Windows_*) PS=";" FS="\\" + # MKS diff deals with trailing CRs automatically + golden_diff="diff" + ;; + CYGWIN*) + PS=":" + FS="/" + # Cygwin diff needs to be told to ignore trailing CRs + golden_diff="diff --strip-trailing-cr" ;; *) PS=":" FS="/" + # Assume any other platform doesn't have the trailing CR stuff + golden_diff="diff" ;; esac diff --git a/jdk/test/sun/tools/jrunscript/jrunscript-eTest.sh b/jdk/test/sun/tools/jrunscript/jrunscript-eTest.sh index 190f145523b..7291c8708b7 100644 --- a/jdk/test/sun/tools/jrunscript/jrunscript-eTest.sh +++ b/jdk/test/sun/tools/jrunscript/jrunscript-eTest.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. +# 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 @@ -42,7 +42,7 @@ fi rm -f jrunscript-eTest.out 2>/dev/null ${JRUNSCRIPT} -e "println('hello')" > jrunscript-eTest.out 2>&1 -diff jrunscript-eTest.out ${TESTSRC}/dash-e.out +$golden_diff jrunscript-eTest.out ${TESTSRC}/dash-e.out if [ $? != 0 ] then echo "Output of jrunscript -e differ from expected output. Failed." @@ -55,7 +55,7 @@ fi rm -f jrunscript-eTest.out 2>/dev/null ${JRUNSCRIPT} -l js -e "println('hello')" > jrunscript-eTest.out 2>&1 -diff jrunscript-eTest.out ${TESTSRC}/dash-e.out +$golden_diff jrunscript-eTest.out ${TESTSRC}/dash-e.out if [ $? != 0 ] then echo "Output of jrunscript -e differ from expected output. Failed." diff --git a/jdk/test/sun/tools/jrunscript/jrunscript-fTest.sh b/jdk/test/sun/tools/jrunscript/jrunscript-fTest.sh index 9644cd3dbab..fd2feecbd56 100644 --- a/jdk/test/sun/tools/jrunscript/jrunscript-fTest.sh +++ b/jdk/test/sun/tools/jrunscript/jrunscript-fTest.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. +# 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 @@ -42,7 +42,7 @@ fi rm -f jrunscript-fTest.out 2>/dev/null ${JRUNSCRIPT} -f ${TESTSRC}/hello.js > jrunscript-fTest.out 2>&1 -diff jrunscript-fTest.out ${TESTSRC}/dash-f.out +$golden_diff jrunscript-fTest.out ${TESTSRC}/dash-f.out if [ $? != 0 ] then echo "Output of jrunscript -f differ from expected output. Failed." @@ -56,7 +56,7 @@ fi rm -f jrunscript-fTest.out 2>/dev/null ${JRUNSCRIPT} -l js -f ${TESTSRC}/hello.js > jrunscript-fTest.out 2>&1 -diff jrunscript-fTest.out ${TESTSRC}/dash-f.out +$golden_diff jrunscript-fTest.out ${TESTSRC}/dash-f.out if [ $? != 0 ] then echo "Output of jrunscript -f differ from expected output. Failed." diff --git a/jdk/test/sun/tools/jrunscript/jrunscriptTest.sh b/jdk/test/sun/tools/jrunscript/jrunscriptTest.sh index ea411c6b9b4..a07415b1e2d 100644 --- a/jdk/test/sun/tools/jrunscript/jrunscriptTest.sh +++ b/jdk/test/sun/tools/jrunscript/jrunscriptTest.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. +# 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 @@ -49,7 +49,7 @@ java.lang.System.out.println('hello world from script'); new java.lang.Runnable() { run: function() { println('I am runnable'); }}.run(); EOF -diff jrunscriptTest.out ${TESTSRC}/repl.out +$golden_diff jrunscriptTest.out ${TESTSRC}/repl.out if [ $? != 0 ] then echo "Output of jrunscript session differ from expected output. Failed." @@ -67,7 +67,7 @@ java.lang.System.out.println('hello world from script'); new java.lang.Runnable() { run: function() { println('I am runnable'); }}.run(); EOF -diff jrunscriptTest.out ${TESTSRC}/repl.out +$golden_diff jrunscriptTest.out ${TESTSRC}/repl.out if [ $? != 0 ] then echo "Output of jrunscript -l js differ from expected output. Failed." diff --git a/jdk/test/sun/tools/jstack/Basic.sh b/jdk/test/sun/tools/jstack/Basic.sh index dcbdd4bc753..1a2b8eb37a9 100644 --- a/jdk/test/sun/tools/jstack/Basic.sh +++ b/jdk/test/sun/tools/jstack/Basic.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. +# 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 @@ -35,22 +35,26 @@ . ${TESTSRC}/../common/CommonSetup.sh . ${TESTSRC}/../common/ApplicationSetup.sh -# Start application (send output to shutdown.port) +# Start application and use PORTFILE for coordination PORTFILE="${TESTCLASSES}"/shutdown.port -startApplication \ - -classpath "${TESTCLASSES}" SimpleApplication "${PORTFILE}" +startApplication SimpleApplication "${PORTFILE}" + +# all return statuses are checked in this test +set +e failed=0 # normal -$JSTACK $pid 2>&1 +$JSTACK $appJavaPid 2>&1 if [ $? != 0 ]; then failed=1; fi # long -$JSTACK -l $pid 2>&1 +$JSTACK -l $appJavaPid 2>&1 if [ $? != 0 ]; then failed=1; fi -stopApplication ShutdownSimpleApplication "${PORTFILE}" +set -e + +stopApplication "${PORTFILE}" +waitForApplication exit $failed - diff --git a/langtools/.hgtags b/langtools/.hgtags index f21369ccd0e..96bc75dd353 100644 --- a/langtools/.hgtags +++ b/langtools/.hgtags @@ -77,3 +77,7 @@ c0a41294297ed397098dd92b647f481f0e1bb8fa jdk7-b97 d1d7595fa824925651f09b8ffcb86c9cf39807be jdk7-b100 20a8fe72ee7b673f59c319a5222fe0eebbd92082 jdk7-b101 ff9c0a0bf7edf637a7dac5062b920924536ed79c jdk7-b102 +bd85271c580ce4600b1b2d5598daa19d02174cf7 jdk7-b103 +fc7219517ec16b28d729d259020a25b05ffdf0b6 jdk7-b104 +aaecac256d39c7cb536e70d20ddd833fc118e43a jdk7-b105 +112fcc00659dda1a356ec75d964584e4dae0228f jdk7-b106 diff --git a/langtools/make/build.properties b/langtools/make/build.properties index f9a87321d41..4ba6256f053 100644 --- a/langtools/make/build.properties +++ b/langtools/make/build.properties @@ -107,7 +107,8 @@ javac.includes = \ javax/annotation/processing/ \ javax/lang/model/ \ javax/tools/ \ - com/sun/source/ com/sun/tools/javac/ + com/sun/source/ \ + com/sun/tools/javac/ javac.tests = \ tools/javac diff --git a/langtools/make/build.xml b/langtools/make/build.xml index 1abad67a9df..d269f396534 100644 --- a/langtools/make/build.xml +++ b/langtools/make/build.xml @@ -322,6 +322,35 @@ datafile="${build.coverage.dir}/cobertura.ser"/> + + + + + + + + + + + + + + + +