提交 379b15fc 编写于 作者: L lana

Merge

......@@ -182,3 +182,5 @@ e8569a473cee7f4955bd9e76a9bdf6c6a07ced27 jdk8-b52
d94613ac03d8de375ef60493e2bb76dbd30d875d jdk8-b58
abad1f417bd3df4296631fc943cd3b7f5062c88a jdk8-b59
cec8fa02f15634acd7d02d04b0b2d8c044cdbaaa jdk8-b60
61ddb3fd000a09ab05bff1940b0ac211661e94cf jdk8-b61
50b8b17449d200c66bfd68fb4f3a9197432c9e2b jdk8-b62
......@@ -94,9 +94,9 @@ ifeq ($(PLATFORM), windows)
LDOUTPUT = -Fe
# JDK name required here
RC_FLAGS += /D "JDK_FNAME=$(PGRM).exe" \
/D "JDK_INTERNAL_NAME=$(PGRM)" \
/D "JDK_FTYPE=0x1L"
RC_FLAGS += -D "JDK_FNAME=$(PGRM).exe" \
-D "JDK_INTERNAL_NAME=$(PGRM)" \
-D "JDK_FTYPE=0x1L"
RES = $(OBJDIR)/$(PGRM).res
else
......@@ -161,7 +161,7 @@ $(UNPACK_EXE): $(UNPACK_EXE_FILES_o) updatefiles winres
$(CP) mapfile-vers-unpack200 $(TEMPDIR)/mapfile-vers
$(LINKER) $(LDDFLAGS) $(sort $(UNPACK_EXE_FILES_o)) $(RES) $(LIBCXX) $(LDOUTPUT)$(TEMPDIR)/unpack200$(EXE_SUFFIX)
ifdef MT
$(MT) /manifest $(OBJDIR)/unpack200$(EXE_SUFFIX).manifest /outputresource:$(TEMPDIR)/unpack200$(EXE_SUFFIX);#1
$(MT) -manifest $(OBJDIR)/unpack200$(EXE_SUFFIX).manifest -outputresource:$(TEMPDIR)/unpack200$(EXE_SUFFIX);#1
endif
$(CP) $(TEMPDIR)/unpack200$(EXE_SUFFIX) $(UNPACK_EXE)
@$(call binary_file_verification,$@)
......
......@@ -78,7 +78,7 @@ ifeq ($(COMPILER_VERSION), VS2010)
MS_RUNTIME_LIBRARIES = $(MSVCRNN_DLL)
endif
EXTRA_LFLAGS += /LIBPATH:$(DXSDK_LIB_PATH)
EXTRA_LFLAGS += -LIBPATH:$(DXSDK_LIB_PATH)
# Full Debug Symbols has been enabled on Windows since JDK1.4.1.
# The Full Debug Symbols (FDS) default for VARIANT == OPT builds is
......@@ -198,7 +198,7 @@ CC_OPT = $(CC_OPT/$(OPTIMIZATION_LEVEL))
# -MTd Use static debug version (better than -MDd, no runtime issues)
# -D_DEBUG Change use of malloc/free/etc to use special debug ones (-MTd)
#
# NOTE: We also will use /D _STATIC_CPPLIB so we don't need msvcpnn.dll
# NOTE: We also will use -D _STATIC_CPPLIB so we don't need msvcpnn.dll
#
# If MS_RUNTIME_STATIC is requested we may have a problem, it is no longer
# supported by VS2010
......@@ -223,12 +223,12 @@ ifeq ($(MFC_DEBUG), true)
endif
# Always add _STATIC_CPPLIB definition
STATIC_CPPLIB_OPTION = /D _STATIC_CPPLIB
STATIC_CPPLIB_OPTION = -D _STATIC_CPPLIB
# Silence the warning about using _STATIC_CPPLIB
ifneq ($(SHOW_ALL_WARNINGS),true)
# Needed with VS2010 to turn off the deprecated warning.
STATIC_CPPLIB_OPTION += /D _DISABLE_DEPRECATE_STATIC_CPPLIB
STATIC_CPPLIB_OPTION += -D _DISABLE_DEPRECATE_STATIC_CPPLIB
endif
MS_RUNTIME_OPTION += $(STATIC_CPPLIB_OPTION)
......@@ -242,7 +242,7 @@ ifeq ($(CC_VERSION),msvc)
# -Od Turns off optimization and speeds compilation
# -YX -Fp/.../foobar.pch Use precompiled headers (try someday?)
# -nologo Don't print out startup message
# /D _STATIC_CPPLIB
# -D _STATIC_CPPLIB
# Use static link for the C++ runtime (so msvcpnn.dll not needed)
#
ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
......@@ -258,12 +258,12 @@ ifeq ($(CC_VERSION),msvc)
CFLAGS_COMMON += $(MS_RUNTIME_OPTION) $(CFLAGS_$(COMPILER_VERSION))
ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
LDEBUG = /debug
LDEBUG = -debug
endif
ifeq ($(VTUNE_SUPPORT), true)
OTHER_CFLAGS = -Z7 -Ox
LDEBUG += /pdb:NONE
LDEBUG += -pdb:NONE
endif
# VS2010, always need safe exception handlers, not needed on 64bit
......@@ -272,7 +272,7 @@ ifeq ($(CC_VERSION),msvc)
endif
# LFLAGS are the flags given to $(LINK) and used to build the actual DLL file
BASELFLAGS = -nologo /opt:REF /incremental:no
BASELFLAGS = -nologo -opt:REF -incremental:no
LFLAGS = $(BASELFLAGS) $(LDEBUG) $(EXTRA_LFLAGS) $(LFLAGS_$(COMPILER_VERSION))
LDDFLAGS += $(LFLAGS_$(COMPILER_VERSION))
......@@ -404,7 +404,7 @@ else
JDK_UPDATE_VER := 0
endif
RC_FLAGS = /l 0x409 /r
RC_FLAGS = -l 0x409 -r
ifeq ($(VARIANT), OPT)
RC_FLAGS += -d NDEBUG
......
......@@ -292,9 +292,9 @@ endif
ifeq ($(PLATFORM),windows)
# JDK name required here
RC_FLAGS += /D "JDK_FNAME=$(LIBRARY).dll" \
/D "JDK_INTERNAL_NAME=$(LIBRARY)" \
/D "JDK_FTYPE=0x2L"
RC_FLAGS += -D "JDK_FNAME=$(LIBRARY).dll" \
-D "JDK_INTERNAL_NAME=$(LIBRARY)" \
-D "JDK_FTYPE=0x2L"
endif
# Native library building
......
......@@ -206,9 +206,9 @@ endif
@$(ECHO) Created $@
# JDK name required here
RC_FLAGS += /D "JDK_FNAME=$(LIBRARY).dll" \
/D "JDK_INTERNAL_NAME=$(LIBRARY)" \
/D "JDK_FTYPE=0x2L"
RC_FLAGS += -D "JDK_FNAME=$(LIBRARY).dll" \
-D "JDK_INTERNAL_NAME=$(LIBRARY)" \
-D "JDK_FTYPE=0x2L"
$(OBJDIR)/$(LIBRARY).res: $(VERSIONINFO_RESOURCE)
ifndef LOCAL_RESOURCE_FILE
......
......@@ -157,9 +157,9 @@ $(ACTUAL_PROGRAM):: classes $(INIT)
#
ifeq ($(PLATFORM), windows)
# JDK name required here
RC_FLAGS += /D "JDK_FNAME=$(PROGRAM)$(EXE_SUFFIX)" \
/D "JDK_INTERNAL_NAME=$(PROGRAM)" \
/D "JDK_FTYPE=0x1L"
RC_FLAGS += -D "JDK_FNAME=$(PROGRAM)$(EXE_SUFFIX)" \
-D "JDK_INTERNAL_NAME=$(PROGRAM)" \
-D "JDK_FTYPE=0x1L"
$(OBJDIR)/$(PROGRAM).res: $(VERSIONINFO_RESOURCE)
@$(prep-target)
......@@ -201,11 +201,11 @@ endif
@$(prep-target)
@set -- $?; \
$(ECHO) Rebuilding $@ because of $$1 $$2 $$3 $$4 $$5 $$6 $${7:+...};
$(LINK) -out:$@ /STACK:$(STACK_SIZE) \
$(LINK) -out:$@ -STACK:$(STACK_SIZE) \
$(MAP_OPTION) $(LFLAGS) $(LDFLAGS) \
@$(OBJDIR)/$(PROGRAM).lcf $(LDLIBS)
ifdef MT
$(MT) /manifest $(OBJDIR)/$(PROGRAM).exe.manifest /outputresource:$@;#1
$(MT) -manifest $(OBJDIR)/$(PROGRAM).exe.manifest /outputresource:$@;#1
endif
@$(call binary_file_verification,$@)
ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
......
......@@ -784,11 +784,22 @@ initial-image-jre:: initial-image-jre-setup \
$(RT_JAR) $(RESOURCES_JAR) $(JSSE_JAR) $(JFR_JAR) \
$(BUILDMETAINDEX_JARFILE)
@# Copy in bin directory
ifeq ($(USING_MSYS),true)
# No cpio in MinGW/MSYS
$(CD) $(OUTPUTDIR) && $(TAR) -cf - bin | ($(CD) $(JRE_IMAGE_DIR) && $(TAR) -xpf -)
else
$(CD) $(OUTPUTDIR) && $(FIND) bin -depth | $(CPIO) -pdum $(JRE_IMAGE_DIR)
endif
@# CTE plugin security change require new empty directory lib/applet
$(MKDIR) -p $(JRE_IMAGE_DIR)/lib/applet
@# Copy in lib directory
ifeq ($(USING_MSYS),true)
# No cpio in MinGW/MSYS
$(CD) $(OUTPUTDIR) && $(TAR) -cf - lib | ($(CD) $(JRE_IMAGE_DIR) && $(TAR) -xpf -)
else
$(CD) $(OUTPUTDIR) && $(FIND) lib -depth | $(CPIO) -pdum $(JRE_IMAGE_DIR)
endif
ifeq ($(USING_CYGWIN),true)
$(RM) -rf $(JRE_IMAGE_DIR)/[A-Za-z]:
$(RM) -rf $(OUTPUTDIR)/[A-Za-z]:
......@@ -919,11 +930,17 @@ endif
# only places from which we copy everything), but because the presence
# of this file causes cygwin's find to bomb out, thus breaking the build
# in "install".
initial-image-jdk-setup:
$(RM) -r $(JDK_IMAGE_DIR)
$(MKDIR) -p $(JDK_IMAGE_DIR)/jre
ifeq ($(USING_MSYS),true)
($(CD) $(JRE_IMAGE_DIR) && $(TAR) -cf - . \
| ($(CD) $(JDK_IMAGE_DIR)/jre && $(TAR) -xpf -))
else
($(CD) $(JRE_IMAGE_DIR) && $(FIND) . -depth -print \
| $(CPIO) -pdum $(JDK_IMAGE_DIR)/jre )
endif
ifeq ($(USING_CYGWIN),true)
$(RM) -rf $(JRE_IMAGE_DIR)/[A-Za-z]:
$(RM) -rf $(JDK_IMAGE_DIR)/jre/[A-Za-z]:
......
......@@ -169,15 +169,19 @@ CD = cd # intrinsic unix command
ifeq ($(PLATFORM),windows)
ifdef USING_CYGWIN
# Intrinsic unix command, with backslash-escaped character interpretation
ECHO = $(UNIXCOMMAND_PATH)echo -e
ZIPEXE = $(UNIXCOMMAND_PATH)zip
UNZIP = $(UNIXCOMMAND_PATH)unzip
ECHO = $(UNIXCOMMAND_PATH)echo -e
ZIPEXE = $(UNIXCOMMAND_PATH)zip
UNZIP = $(UNIXCOMMAND_PATH)unzip
# Some CYGWIN nawk versions require BINMODE=w for proper '\r' interpretation
NAWK = $(UNIXCOMMAND_PATH)awk -v BINMODE=w
NAWK = $(UNIXCOMMAND_PATH)awk -v BINMODE=w
else
ZIPEXE = $(UTILS_DEVTOOL_PATH)zip
UNZIP = $(UTILS_DEVTOOL_PATH)unzip
NAWK = $(UNIXCOMMAND_PATH)awk
ifdef USING_MSYS
ECHO = $(UTILS_COMMAND_PATH)echo -e
AR = $(UTILS_DEVTOOL_PATH)ar
endif
endif
# Re-define some utilities
LEX =# override GNU Make intrinsic: no lex on windows
......
......@@ -112,6 +112,15 @@ define OptFullPath
$(shell if [ "$1" != "" -a -d "$1" ]; then $(CYGPATH_CMD) "$1" 2> $(DEV_NULL); else echo "$1"; fi)
endef
else
ifdef USING_MSYS
DOSPATH_CMD:=$(shell cd $(JDK_TOPDIR) 2> $(DEV_NULL) && pwd)/make/tools/msys_build_scripts/dospath.sh
define FullPath
$(subst \,/,$(shell $(DOSPATH_CMD) $1))
endef
define OptFullPath
$(shell if [ "$1" != "" -a -d "$1" ]; then (cd $1 && pwd); else echo "$1"; fi)
endef
else
# Temporary until we upgrade to MKS 8.7, MKS pwd returns mixed mode path
define FullPath
$(shell cd $1 2> $(DEV_NULL) && pwd)
......@@ -120,6 +129,7 @@ define OptFullPath
$(shell if [ "$1" != "" -a -d "$1" ]; then (cd $1 && pwd); else echo "$1"; fi)
endef
endif
endif
# System drive
ifdef SYSTEMDRIVE
......@@ -146,43 +156,47 @@ else
ifdef USING_CYGWIN
UNIXCOMMAND_PATH :=$(call PrefixPath,/usr/bin)
else
ifdef ROOTDIR
xROOTDIR :="$(subst \,/,$(ROOTDIR))"
_rootdir :=$(call FullPath,$(xROOTDIR))
ifdef USING_MSYS
UNIXCOMMAND_PATH :=$(call PrefixPath,/bin)
else
xROOTDIR :="$(_system_drive)/mksnt"
_rootdir :=$(call FullPath,$(xROOTDIR))
endif
ifneq ($(_rootdir),)
UNIXCOMMAND_PATH :=$(call PrefixPath,$(_rootdir)/mksnt)
endif
endif
ifdef ROOTDIR
xROOTDIR :="$(subst \,/,$(ROOTDIR))"
_rootdir :=$(call FullPath,$(xROOTDIR))
else
xROOTDIR :="$(_system_drive)/mksnt"
_rootdir :=$(call FullPath,$(xROOTDIR))
endif
ifneq ($(_rootdir),)
UNIXCOMMAND_PATH :=$(call PrefixPath,$(_rootdir)/mksnt)
endif
endif # USING_MSYS
endif # USING_CYGWIN
endif
UNIXCOMMAND_PATH:=$(call AltCheckSpaces,UNIXCOMMAND_PATH)
# Get version of MKS or CYGWIN
ifndef USING_CYGWIN
_MKS_VER :=$(shell $(MKSINFO) 2>&1 | $(GREP) Release | $(TAIL) -1 | $(SED) -e 's@.*\(Release.*\)@\1@')
MKS_VER :=$(call GetVersion,$(_MKS_VER))
# At this point, we can re-define FullPath to use DOSNAME_CMD
CHECK_MKS87:=$(call CheckVersions,$(MKS_VER),8.7)
TRY_DOSNAME:=false
ifeq ($(CHECK_MKS87),same)
TRY_DOSNAME:=true
endif
# Newer should be ok
ifeq ($(CHECK_MKS87),newer)
TRY_DOSNAME:=true
endif
ifeq ($(TRY_DOSNAME),true)
ifeq ($(shell $(UNIXCOMMAND_PATH)dosname -s $(_system_drive)/ 2> $(DEV_NULL)),$(_system_drive)/)
_DOSNAME=$(UNIXCOMMAND_PATH)dosname
DOSNAME_CMD:=$(_DOSNAME) -s
ifdef USING_MKS
_MKS_VER :=$(shell $(MKSINFO) 2>&1 | $(GREP) Release | $(TAIL) -1 | $(SED) -e 's@.*\(Release.*\)@\1@')
MKS_VER :=$(call GetVersion,$(_MKS_VER))
# At this point, we can re-define FullPath to use DOSNAME_CMD
CHECK_MKS87:=$(call CheckVersions,$(MKS_VER),8.7)
TRY_DOSNAME:=false
ifeq ($(CHECK_MKS87),same)
TRY_DOSNAME:=true
endif
# Newer should be ok
ifeq ($(CHECK_MKS87),newer)
TRY_DOSNAME:=true
endif
ifeq ($(TRY_DOSNAME),true)
ifeq ($(shell $(UNIXCOMMAND_PATH)dosname -s $(_system_drive)/ 2> $(DEV_NULL)),$(_system_drive)/)
_DOSNAME=$(UNIXCOMMAND_PATH)dosname
DOSNAME_CMD:=$(_DOSNAME) -s
define FullPath
$(subst //,/,$(shell echo $1 | $(DOSNAME_CMD) 2> $(DEV_NULL)))
endef
endif # test dosname -s
endif # TRY_DOSNAME
endif # test dosname -s
endif # TRY_DOSNAME
endif # MKS
# We try to get references to what we need via the default component
......@@ -440,10 +454,14 @@ else
ifdef USING_CYGWIN
DEVTOOLS_PATH :=$(UNIXCOMMAND_PATH)
else
xDEVTOOLS_PATH :="$(_system_drive)/utils"
fxDEVTOOLS_PATH :=$(call FullPath,$(xDEVTOOLS_PATH))
DEVTOOLS_PATH :=$(call PrefixPath,$(fxDEVTOOLS_PATH))
endif
ifdef USING_MSYS
DEVTOOLS_PATH :=$(UNIXCOMMAND_PATH)
else
xDEVTOOLS_PATH :="$(_system_drive)/utils"
fxDEVTOOLS_PATH :=$(call FullPath,$(xDEVTOOLS_PATH))
DEVTOOLS_PATH :=$(call PrefixPath,$(fxDEVTOOLS_PATH))
endif # USING_MSYS
endif # USING_CYGWIN
endif
DEVTOOLS_PATH:=$(call AltCheckSpaces,DEVTOOLS_PATH)
......@@ -636,7 +654,7 @@ HOTSPOT_LIB_PATH:=$(call AltCheckValue,HOTSPOT_LIB_PATH)
# Special define for checking the binaries
# All windows dll and exe files should have been built with /NXCOMPAT
# All windows dll and exe files should have been built with -NXCOMPAT
# and be setup for dynamic base addresses.
# In addition, we should not be dependent on certain dll files that
# we do not or cannot redistribute.
......@@ -648,37 +666,37 @@ else
BANNED_DLLS=msvcp100[.]dll|msvcr100d[.]dll|msvcrtd[.]dll
endif
# Check for /safeseh (only used on 32bit)
# Check for -safeseh (only used on 32bit)
define binary_file_safeseh_verification # binary_file
( \
$(ECHO) "Checking for /SAFESEH usage in: $1" && \
if [ "`$(DUMPBIN) /loadconfig $1 | $(EGREP) -i 'Safe Exception Handler Table'`" = "" ] ; then \
$(ECHO) "Checking for -SAFESEH usage in: $1" && \
if [ "`$(DUMPBIN) -loadconfig $1 | $(EGREP) -i 'Safe Exception Handler Table'`" = "" ] ; then \
$(ECHO) "ERROR: Did not find 'Safe Exception Handler Table' in loadconfig: $1" ; \
$(DUMPBIN) /loadconfig $1 ; \
$(DUMPBIN) -loadconfig $1 ; \
exit 6 ; \
fi ; \
)
endef
# Check for /NXCOMPAT usage
# Check for -NXCOMPAT usage
define binary_file_nxcompat_verification # binary_file
( \
$(ECHO) "Checking for /NXCOMPAT usage in: $1" && \
if [ "`$(DUMPBIN) /headers $1 | $(EGREP) -i 'NX compatible'`" = "" ] ; then \
$(ECHO) "Checking for -NXCOMPAT usage in: $1" && \
if [ "`$(DUMPBIN) -headers $1 | $(EGREP) -i 'NX compatible'`" = "" ] ; then \
$(ECHO) "ERROR: Did not find 'NX compatible' in headers: $1" ; \
$(DUMPBIN) /headers $1 ; \
$(DUMPBIN) -headers $1 ; \
exit 7 ; \
fi ; \
)
endef
# Check for /DYNAMICBASE usage
# Check for -DYNAMICBASE usage
define binary_file_dynamicbase_verification # binary_file
( \
$(ECHO) "Checking for /DYNAMICBASE usage in: $1" && \
if [ "`$(DUMPBIN) /headers $1 | $(EGREP) -i 'Dynamic base'`" = "" ] ; then \
$(ECHO) "Checking for -DYNAMICBASE usage in: $1" && \
if [ "`$(DUMPBIN) -headers $1 | $(EGREP) -i 'Dynamic base'`" = "" ] ; then \
$(ECHO) "ERROR: Did not find 'Dynamic base' in headers: $1" ; \
$(DUMPBIN) /headers $1 ; \
$(DUMPBIN) -headers $1 ; \
exit 8 ; \
fi ; \
)
......@@ -688,9 +706,9 @@ endef
define binary_file_dll_verification # binary_file
( \
$(ECHO) "Checking for banned dependencies in: $1" && \
if [ "`$(DUMPBIN) /dependents $1 | $(EGREP) -i '$(BANNED_DLLS)'`" != "" ] ; then \
if [ "`$(DUMPBIN) -dependents $1 | $(EGREP) -i '$(BANNED_DLLS)'`" != "" ] ; then \
$(ECHO) "ERROR: Found use of $(BANNED_DLLS)"; \
$(DUMPBIN) /dependents $1 ; \
$(DUMPBIN) -dependents $1 ; \
exit 9 ; \
fi ; \
)
......
......@@ -70,6 +70,8 @@ PLATFORM_SHARED=done
# LIBARCH32 solaris only: sparc or i386
# LIBARCH64 solaris only: sparcv9 or amd64
# USING_CYGWIN windows only: true or false
# USING_MSYS windows only: true or false
# USING_MKS windows only: true or false
# ISHIELD_TEMP_MIN windows only: minimum disk space in temp area
# Only run uname once in this make session.
......@@ -306,6 +308,8 @@ endif
# Windows with and without CYGWIN will be slightly different
ifeq ($(SYSTEM_UNAME), Windows_NT)
PLATFORM = windows
USING_MKS = true
export USING_MKS
endif
ifneq (,$(findstring CYGWIN,$(SYSTEM_UNAME)))
PLATFORM = windows
......@@ -318,6 +322,11 @@ ifneq (,$(findstring CYGWIN,$(SYSTEM_UNAME)))
export CYGWIN_HOME
endif
endif
ifneq (,$(findstring MINGW,$(SYSTEM_UNAME)))
PLATFORM = windows
USING_MSYS = true
export USING_MSYS
endif
# Platform settings specific to Windows
ifeq ($(PLATFORM), windows)
......@@ -395,11 +404,12 @@ ifeq ($(PLATFORM), windows)
endif
ARCH_FAMILY = $(ARCH)
# Where is unwanted output to be delivered?
# MKS uses the special file "NUL", cygwin uses the customary unix file.
ifeq ($(USING_CYGWIN),true)
DEV_NULL = /dev/null
else
# MKS uses the special file "NUL"; Cygwin and MinGW/MSYS use the
# customary unix file.
ifeq ($(USING_MKS),true)
DEV_NULL = NUL
else
DEV_NULL = /dev/null
endif
export DEV_NULL
# Classpath separator
......@@ -440,28 +450,11 @@ ifeq ($(PLATFORM), windows)
_MB_OF_MEMORY := \
$(shell free -m | grep Mem: | awk '{print $$2;}' )
else
# Windows 2000 has the mem utility, but two memory areas
# extended memory is what is beyond 1024M
_B_OF_EXT_MEMORY := \
$(shell mem 2> $(DEV_NULL) | \
grep 'total contiguous extended memory' | awk '{print $$1;}')
ifeq ($(_B_OF_EXT_MEMORY),)
_B_OF_MEMORY := \
$(shell mem 2> $(DEV_NULL) | \
grep 'total conventional memory' | awk '{print $$1;}')
else
_B_OF_MEMORY := \
$(shell expr 1048576 '+' $(_B_OF_EXT_MEMORY) 2> $(DEV_NULL))
endif
ifeq ($(_B_OF_MEMORY),)
# Windows 2003 has the systeminfo utility use it if mem doesn't work
_MB_OF_MEMORY := \
$(shell systeminfo 2> $(DEV_NULL) | \
grep 'Total Physical Memory:' | \
awk '{print $$4;}' | sed -e 's@,@@')
else
_MB_OF_MEMORY := $(shell expr $(_B_OF_MEMORY) '/' 1024 2> $(DEV_NULL))
endif
# Windows XP and higher has the systeminfo utility
_MB_OF_MEMORY := \
$(shell systeminfo 2> $(DEV_NULL) | \
grep 'Total Physical Memory:' | \
awk '{print $$4;}' | sed -e 's@,@@')
endif
ifeq ($(shell expr $(_MB_OF_MEMORY) '+' 0 2> $(DEV_NULL)), $(_MB_OF_MEMORY))
MB_OF_MEMORY := $(_MB_OF_MEMORY)
......
......@@ -182,8 +182,13 @@ ifeq ($(PLATFORM),windows)
ALL_SETTINGS+=$(call addRequiredVersionSetting,CYGWIN_VER)
ALL_SETTINGS+=$(call addRequiredSetting,CYGPATH_CMD)
else
ALL_SETTINGS+=$(call addRequiredVersionSetting,MKS_VER)
ALL_SETTINGS+=$(call addOptionalSetting,DOSNAME_CMD)
ifdef USING_MSYS
ALL_SETTINGS+=$(call addRequiredSetting,USING_MSYS)
ALL_SETTINGS+=$(call addRequiredSetting,DOSPATH_CMD)
else
ALL_SETTINGS+=$(call addRequiredVersionSetting,MKS_VER)
ALL_SETTINGS+=$(call addOptionalSetting,DOSNAME_CMD)
endif
endif
endif
ifeq ($(PLATFORM),linux)
......
......@@ -394,7 +394,7 @@ endif
ifeq ($(PLATFORM), windows)
MKS_CHECK :=$(call CheckVersions,$(MKS_VER),$(REQUIRED_MKS_VER))
sane-mks:
ifndef USING_CYGWIN
ifdef USING_MKS
ifeq ($(MKS_CHECK),missing)
@$(call OfficialErrorMessage,MKS version,$(MKS_VER),$(REQUIRED_MKS_VER))
endif
......@@ -904,14 +904,25 @@ sane-unixcommand_path:
"" >> $(ERROR_FILE) ; \
fi
ifeq ($(PLATFORM), windows)
@for utility in cpio ar file m4 ; do \
ifeq ($(USING_MSYS), true)
@for utility in $(AR) $(FILE) $(M4) ; do \
if [ ! -r "`$(WHICH) $${utility}`" ]; then \
$(ECHO) "WARNING: You do not have the utility $${utility} in the \n" \
" directory $(UNIXCOMMAND_PATH). \n" \
" The utilities cpio, ar, file, and m4 are required. \n" \
" The utilities ar, file and m4 are required. \n" \
"" >> $(WARNING_FILE) ; \
fi; \
done
else
@for utility in $(AR) $(CPIO) $(FILE) $(M4) ; do \
if [ ! -r "`$(WHICH) $${utility}`" ]; then \
$(ECHO) "WARNING: You do not have the utility $${utility} in the \n" \
" directory $(UNIXCOMMAND_PATH). \n" \
" The utilities ar, cpio, file and m4 are required. \n" \
"" >> $(WARNING_FILE) ; \
fi; \
done
endif
endif
######################################################
......@@ -998,7 +1009,8 @@ ifeq ($(PLATFORM), windows)
" This is normally obtained from the WINDOWSSDKDIR." \
"" >> $(ERROR_FILE)
endif
ifeq ($(wildcard $(DUMPBIN)),)
# MinGW/MSYS make 3.81 will not tolerate a path with a quoted substring
ifeq ($(wildcard $(subst ",,$(DUMPBIN))),)
@$(ECHO) "ERROR: Cannot find the DUMPBIN utility from path: $(DUMPBIN)\n" \
" This is normally obtained from the COMPILER_PATH." \
"" >> $(ERROR_FILE)
......
......@@ -176,17 +176,38 @@ else
else
windows_arch=i586
fi
repo=`hg root | sed -e 's@\\\\@/@g'`
# We need to check if we are running a CYGWIN shell
if [ "$(uname -a | fgrep Cygwin)" != "" -a -f /bin/cygpath ] ; then
if [ "$(echo ${osname} | fgrep Cygwin)" != "" -a -f /bin/cygpath ] ; then
# For CYGWIN, uname will have "Cygwin" in it, and /bin/cygpath should exist
# Utility to convert to short pathnames without spaces
cygpath="/usr/bin/cygpath -a -m -s"
cygpathp="/usr/bin/cygpath -p"
# Most unix utilities are in the /usr/bin
unixcommand_path="/usr/bin"
# Make the prompt tell you CYGWIN
export PS1="CYGWIN:${COMPUTERNAME}:${USERNAME}[\!] "
elif [ "$(echo ${osname} | fgrep MINGW)" != "" ] ; then
# Utility to convert to short pathnames without spaces
cygpath="${repo}/make/tools/msys_build_scripts/dospath.sh"
if [ ! -f ${cygpath} ] ; then
echo "ERROR: Cannot find cygpath or equivalent on this machine"
exit 1
fi
# Utility to fix a path to MinGW/MSYS format - the equivalent of 'cygpath -p'
for tfile in "${repo}/make/scripts/fixpath.pl" "${repo}/../make/scripts/fixpath.pl"; do
if [ -f ${tfile} ] ; then
cygpathp="/bin/perl ${tfile} -m"
fi
done;
if [ -z "${cygpathp}" ] ; then
echo "ERROR: Cannot find make/scripts/fixpath.pl on this machine"
exit 1
fi
unixcommand_path="/usr/bin"
else
echo "ERROR: Cannot find CYGWIN on this machine"
echo "ERROR: Cannot find CYGWIN or MinGW/MSYS on this machine"
exit 1
fi
if [ "${ALT_UNIXCOMMAND_PATH}" != "" ] ; then
......@@ -204,17 +225,18 @@ else
else
sys_root=$(${cygpath} "C:/WINNT")
fi
path4sdk="${unixcommand_path};${sys_root}/system32;${sys_root};${sys_root}/System32/Wbem"
if [ ! -d "${sys_root}" ] ; then
echo "WARNING: No system root found at: ${sys_root}"
fi
# Build a : separated path making sure each segment is acceptable to ${osname}
path4sdk="${unixcommand_path}:"`${cygpathp} "${sys_root}/system32;${sys_root};${sys_root}/System32/Wbem"`
# Compiler setup (nasty part)
# NOTE: You can use vcvars32.bat to set PATH, LIB, and INCLUDE.
# NOTE: CYGWIN has a link.exe too, make sure the compilers are first
# Use supplied vsvars.sh
repo=`hg root`
if [ -f "${repo}/make/scripts/vsvars.sh" ] ; then
eval `sh ${repo}/make/scripts/vsvars.sh -v10`
elif [ -f "${repo}/../make/scripts/vsvars.sh" ] ; then
......
......@@ -128,8 +128,6 @@ FILES_java = \
sun/net/www/content/audio/x_wav.java \
sun/net/www/protocol/ftp/Handler.java \
sun/net/www/protocol/ftp/FtpURLConnection.java \
sun/net/www/protocol/gopher/GopherClient.java \
sun/net/www/protocol/gopher/Handler.java \
sun/net/www/protocol/mailto/Handler.java \
sun/net/www/protocol/mailto/MailToURLConnection.java \
sun/net/idn/Punycode.java \
......
......@@ -37,11 +37,11 @@ ifeq ($(OPENJDK),true)
# Start with CFLAGS (which gets us the required -xarch setting on solaris)
ifeq ($(PLATFORM), windows)
FT_OPTIONS = /nologo /c
FT_OPTIONS = -nologo -c
FREETYPE_DLL = $(FREETYPE_LIB_PATH)/freetype.dll
FT_LD_OPTIONS = $(FREETYPE_LIB_PATH)/freetype.lib
ifdef MT
FT_LD_OPTIONS += /manifest
FT_LD_OPTIONS += -manifest
endif
else
FT_OPTIONS = $(CFLAGS)
......@@ -72,11 +72,11 @@ $(FT_TEST): freetypecheck.c
$(prep-target)
ifeq ($(PLATFORM), windows)
$(CC) $(FT_OPTIONS) $(CC_OBJECT_OUTPUT_FLAG)$(FT_OBJ) $<
$(LINK) $(FT_LD_OPTIONS) /OUT:$(FT_TEST) $(FT_OBJ)
$(LINK) $(FT_LD_OPTIONS) -OUT:$(FT_TEST) $(FT_OBJ)
$(CP) $(FREETYPE_DLL) $(@D)/
ifdef MT
$(CP) $(MSVCRNN_DLL_PATH)/$(MSVCRNN_DLL) $(@D)/
$(MT) /manifest $(FT_TEST).manifest /outputresource:$(FT_TEST);#1
$(MT) -manifest $(FT_TEST).manifest -outputresource:$(FT_TEST);#1
endif
else
@$(CC) $(FT_OPTIONS) -o $@ $< $(FT_LD_OPTIONS)
......
#
# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# A shell script which converts its first argument, which must be an existing
# path name, into a DOS (aka 8.3) path name. If the path is a file, only the
# directory part of the whole path will be converted.
# This shell script executes the Visual Basic helper script 'dospath.vbs'
# which must be located in the same directory as this script itself.
# The Visual Basic script will be invoked trough the "Windows Script Host"
# which is available by default on Windows since Windows 98.
pushd `dirname "$0"` > /dev/null
ABS_PATH=`pwd`
popd > /dev/null
if [ -d "$1" ]; then
echo `cd "$1" && cscript.exe -nologo $ABS_PATH/dospath.vbs`;
elif [ -f "$1" ]; then
DIR=`dirname "$1"`;
echo `cd "$DIR" && cscript.exe -nologo $ABS_PATH/dospath.vbs`\\`basename "$1"`;
fi
'
' Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
' DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
'
' This code is free software; you can redistribute it and/or modify it
' under the terms of the GNU General Public License version 2 only, as
' published by the Free Software Foundation. Oracle designates this
' particular file as subject to the "Classpath" exception as provided
' by Oracle in the LICENSE file that accompanied this code.
'
' This code is distributed in the hope that it will be useful, but WITHOUT
' ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
' FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
' version 2 for more details (a copy is included in the LICENSE file that
' accompanied this code).
'
' You should have received a copy of the GNU General Public License version
' 2 along with this work; if not, write to the Free Software Foundation,
' Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
'
' Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
' or visit www.oracle.com if you need additional information or have any
' questions.
'
'
' Visual Basic Script which returns the DOS (aka 8.3) filename of the current
' directory.
' Only called from 'dospath.sh' during a Windows build under MinGW/MSYS.
'
Set fso=CreateObject("Scripting.FileSystemObject")
Set path = fso.GetFolder(".")
WScript.Echo path.ShortPath
......@@ -379,6 +379,19 @@ public class AquaFileChooserUI extends FileChooserUI {
}
}
updateButtonState(getFileChooser());
} else if (prop.equals(JFileChooser.SELECTED_FILES_CHANGED_PROPERTY)) {
JFileChooser fileChooser = getFileChooser();
if (!fileChooser.isDirectorySelectionEnabled()) {
final File[] files = (File[]) e.getNewValue();
if (files != null) {
for (int selectedRow : fFileList.getSelectedRows()) {
File file = (File) fFileList.getValueAt(selectedRow, 0);
if (fileChooser.isTraversable(file)) {
fFileList.removeSelectedIndex(selectedRow);
}
}
}
}
} else if (prop.equals(JFileChooser.DIRECTORY_CHANGED_PROPERTY)) {
fFileList.clearSelection();
final File currentDirectory = getFileChooser().getCurrentDirectory();
......
......@@ -33,9 +33,7 @@ import java.awt.DisplayMode;
import sun.java2d.opengl.CGLGraphicsConfig;
import sun.awt.FullScreenCapable;
public class CGraphicsDevice extends GraphicsDevice {
public final class CGraphicsDevice extends GraphicsDevice {
// CoreGraphics display ID
private final int displayID;
......@@ -108,11 +106,6 @@ public class CGraphicsDevice extends GraphicsDevice {
return nativeGetYResolution(displayID);
}
public int getScreenResolution() {
// TODO: report non-72 value when HiDPI is turned on
return 72;
}
private static native double nativeGetXResolution(int displayID);
private static native double nativeGetYResolution(int displayID);
......@@ -194,6 +187,9 @@ public class CGraphicsDevice extends GraphicsDevice {
@Override
public void setDisplayMode(DisplayMode dm) {
if (dm == null) {
throw new IllegalArgumentException("Invalid display mode");
}
nativeSetDisplayMode(displayID, dm.getWidth(), dm.getHeight(), dm.getBitDepth(), dm.getRefreshRate());
if (isFullScreenSupported() && getFullScreenWindow() != null) {
getFullScreenWindow().setSize(dm.getWidth(), dm.getHeight());
......
......@@ -65,7 +65,7 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
private static native void nativeDispose(long nsWindowPtr);
private static native CPlatformWindow nativeGetTopmostPlatformWindowUnderMouse();
private static native int nativeGetNSWindowDisplayID_AppKitThread(long nsWindowPtr);
private static native int nativeGetNSWindowDisplayID(long nsWindowPtr);
// Loger to report issues happened during execution but that do not affect functionality
private static final PlatformLogger logger = PlatformLogger.getLogger("sun.lwawt.macosx.CPlatformWindow");
......@@ -444,7 +444,7 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
public GraphicsDevice getGraphicsDevice() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
CGraphicsEnvironment cge = (CGraphicsEnvironment)ge;
int displayID = nativeGetNSWindowDisplayID_AppKitThread(getNSWindowPtr());
int displayID = nativeGetNSWindowDisplayID(getNSWindowPtr());
GraphicsDevice gd = cge.getScreenDevice(displayID);
if (gd == null) {
// this could possibly happen during device removal
......
......@@ -26,6 +26,7 @@
package sun.lwawt.macosx;
import sun.awt.SunToolkit;
import sun.lwawt.macosx.event.NSEvent;
import javax.swing.*;
import java.awt.*;
......@@ -42,6 +43,16 @@ public class CTrayIcon extends CFRetainedResource implements TrayIconPeer {
private JDialog messageDialog;
private DialogEventHandler handler;
// In order to construct MouseEvent object, we need to specify a
// Component target. Because TrayIcon isn't Component's subclass,
// we use this dummy frame instead
private final Frame dummyFrame;
// A bitmask that indicates what mouse buttons produce MOUSE_CLICKED events
// on MOUSE_RELEASE. Click events are only generated if there were no drag
// events between MOUSE_PRESSED and MOUSE_RELEASED for particular button
private static int mouseClickButtons = 0;
CTrayIcon(TrayIcon target) {
super(0, true);
......@@ -49,6 +60,7 @@ public class CTrayIcon extends CFRetainedResource implements TrayIconPeer {
this.handler = null;
this.target = target;
this.popup = target.getPopupMenu();
this.dummyFrame = new Frame();
setPtr(createModel());
//if no one else is creating the peer.
......@@ -119,6 +131,8 @@ public class CTrayIcon extends CFRetainedResource implements TrayIconPeer {
disposeMessageDialog();
}
dummyFrame.dispose();
LWCToolkit.targetDisposedPeer(target, this);
target = null;
......@@ -161,17 +175,78 @@ public class CTrayIcon extends CFRetainedResource implements TrayIconPeer {
private native void setNativeImage(final long model, final long nsimage, final boolean autosize);
//invocation from the AWTTrayIcon.m
public void performAction() {
private void postEvent(final AWTEvent event) {
SunToolkit.executeOnEventHandlerThread(target, new Runnable() {
public void run() {
final String cmd = target.getActionCommand();
final ActionEvent event = new ActionEvent(target, ActionEvent.ACTION_PERFORMED, cmd);
SunToolkit.postEvent(SunToolkit.targetToAppContext(target), event);
}
});
}
//invocation from the AWTTrayIcon.m
private void handleMouseEvent(NSEvent nsEvent) {
int buttonNumber = nsEvent.getButtonNumber();
final SunToolkit tk = (SunToolkit)Toolkit.getDefaultToolkit();
if ((buttonNumber > 2 && !tk.areExtraMouseButtonsEnabled())
|| buttonNumber > tk.getNumberOfButtons() - 1) {
return;
}
int jeventType = NSEvent.nsToJavaEventType(nsEvent.getType());
int jbuttonNumber = MouseEvent.NOBUTTON;
int jclickCount = 0;
if (jeventType != MouseEvent.MOUSE_MOVED) {
jbuttonNumber = NSEvent.nsToJavaButton(buttonNumber);
jclickCount = nsEvent.getClickCount();
}
int jmodifiers = NSEvent.nsToJavaMouseModifiers(buttonNumber,
nsEvent.getModifierFlags());
boolean isPopupTrigger = NSEvent.isPopupTrigger(jmodifiers);
int eventButtonMask = (jbuttonNumber > 0)?
MouseEvent.getMaskForButton(jbuttonNumber) : 0;
long when = System.currentTimeMillis();
if (jeventType == MouseEvent.MOUSE_PRESSED) {
mouseClickButtons |= eventButtonMask;
} else if (jeventType == MouseEvent.MOUSE_DRAGGED) {
mouseClickButtons = 0;
}
// The MouseEvent's coordinates are relative to screen
int absX = nsEvent.getAbsX();
int absY = nsEvent.getAbsY();
MouseEvent mouseEvent = new MouseEvent(dummyFrame, jeventType, when,
jmodifiers, absX, absY, absX, absY, jclickCount, isPopupTrigger,
jbuttonNumber);
mouseEvent.setSource(target);
postEvent(mouseEvent);
// fire ACTION event
if (jeventType == MouseEvent.MOUSE_PRESSED && isPopupTrigger) {
final String cmd = target.getActionCommand();
final ActionEvent event = new ActionEvent(target,
ActionEvent.ACTION_PERFORMED, cmd);
postEvent(event);
}
// synthesize CLICKED event
if (jeventType == MouseEvent.MOUSE_RELEASED) {
if ((mouseClickButtons & eventButtonMask) != 0) {
MouseEvent clickEvent = new MouseEvent(dummyFrame,
MouseEvent.MOUSE_CLICKED, when, jmodifiers, absX, absY,
absX, absY, jclickCount, isPopupTrigger, jbuttonNumber);
clickEvent.setSource(target);
postEvent(clickEvent);
}
mouseClickButtons &= ~eventButtonMask;
}
}
private native Point2D nativeGetIconLocation(long trayIconModel);
public void displayMessageOnEDT(String caption, String text,
......@@ -256,6 +331,9 @@ public class CTrayIcon extends CFRetainedResource implements TrayIconPeer {
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setModal(false);
dialog.setModalExclusionType(Dialog.ModalExclusionType.TOOLKIT_EXCLUDE);
dialog.setAlwaysOnTop(true);
dialog.setAutoRequestFocus(false);
dialog.setResizable(false);
dialog.setContentPane(op);
......
......@@ -53,7 +53,7 @@ class NamedCursor extends Cursor {
/**
* Mac OS X Cocoa-based AWT Toolkit.
*/
public class LWCToolkit extends LWToolkit {
public final class LWCToolkit extends LWToolkit {
// While it is possible to enumerate all mouse devices
// and query them for the number of buttons, the code
// that does it is rather complex. Instead, we opt for
......@@ -278,7 +278,6 @@ public class LWCToolkit extends LWToolkit {
return new CMouseInfoPeer();
}
@Override
protected int getScreenHeight() {
return GraphicsEnvironment.getLocalGraphicsEnvironment()
......@@ -333,8 +332,9 @@ public class LWCToolkit extends LWToolkit {
@Override
public int getScreenResolution() throws HeadlessException {
return ((CGraphicsDevice) GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()).getScreenResolution();
return (int) ((CGraphicsDevice) GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice())
.getXResolution();
}
@Override
......
......@@ -324,6 +324,13 @@ AWT_ASSERT_APPKIT_THREAD;
}
}
+ (NSNumber *) getNSWindowDisplayID_AppKitThread:(NSWindow *)window {
AWT_ASSERT_APPKIT_THREAD;
NSScreen *screen = [window screen];
NSDictionary *deviceDescription = [screen deviceDescription];
return [deviceDescription objectForKey:@"NSScreenNumber"];
}
- (void) dealloc {
AWT_ASSERT_APPKIT_THREAD;
......@@ -1113,19 +1120,22 @@ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMou
* Signature: (J)I
*/
JNIEXPORT jint JNICALL
Java_sun_lwawt_macosx_CPlatformWindow_nativeGetNSWindowDisplayID_1AppKitThread
Java_sun_lwawt_macosx_CPlatformWindow_nativeGetNSWindowDisplayID
(JNIEnv *env, jclass clazz, jlong windowPtr)
{
jint ret; // CGDirectDisplayID
__block jint ret; // CGDirectDisplayID
JNF_COCOA_ENTER(env);
AWT_ASSERT_APPKIT_THREAD;
NSWindow *window = OBJC(windowPtr);
NSScreen *screen = [window screen];
NSDictionary *deviceDescription = [screen deviceDescription];
NSNumber *displayID = [deviceDescription objectForKey:@"NSScreenNumber"];
ret = (jint)[displayID intValue];
if ([NSThread isMainThread]) {
ret = (jint)[[AWTWindow getNSWindowDisplayID_AppKitThread: window] intValue];
} else {
[JNFRunLoop performOnMainThreadWaiting:YES withBlock:^(){
ret = (jint)[[AWTWindow getNSWindowDisplayID_AppKitThread: window] intValue];
}];
}
JNF_COCOA_EXIT(env);
......
......@@ -53,6 +53,7 @@ extern "C" {
- (jobject) peer;
- (void) setImage:(NSImage *) imagePtr sizing:(BOOL)autosize;
- (NSPoint) getLocationOnScreen;
- (void) deliverJavaMouseEvent:(NSEvent*) event;
@end //AWTTrayIcon
......@@ -68,6 +69,7 @@ extern "C" {
-(id)initWithTrayIcon:(AWTTrayIcon *)theTrayIcon;
-(void)setHighlighted:(BOOL)aFlag;
-(void)setImage:(NSImage*)anImage;
-(void)setTrayIcon:(AWTTrayIcon*)theTrayIcon;
@end //AWTTrayIconView
......
......@@ -29,6 +29,7 @@
#import "CTrayIcon.h"
#import "ThreadUtilities.h"
#include "GeomUtilities.h"
#import "LWCToolkit.h"
#define kImageInset 4.0
......@@ -76,8 +77,9 @@ static NSSize ScaledImageSizeForStatusBar(NSSize imageSize) {
// Its a bad idea to force the item to release our view by setting
// the item's view to nil: it can lead to a crash in some scenarios.
// The item will release the view later on, so just set the view's image
// to nil since we are done with it.
// and tray icon to nil since we are done with it.
[view setImage: nil];
[view setTrayIcon: nil];
[view release];
[theItem release];
......@@ -115,6 +117,45 @@ static NSSize ScaledImageSizeForStatusBar(NSSize imageSize) {
return [[view window] convertBaseToScreen: NSZeroPoint];
}
-(void) deliverJavaMouseEvent: (NSEvent *) event {
[AWTToolkit eventCountPlusPlus];
JNIEnv *env = [ThreadUtilities getJNIEnv];
NSPoint eventLocation = [event locationInWindow];
NSPoint localPoint = [view convertPoint: eventLocation fromView: nil];
localPoint.y = [view bounds].size.height - localPoint.y;
NSPoint absP = [NSEvent mouseLocation];
NSEventType type = [event type];
NSRect screenRect = [[NSScreen mainScreen] frame];
absP.y = screenRect.size.height - absP.y;
jint clickCount;
clickCount = [event clickCount];
static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/event/NSEvent");
static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDD)V");
jobject jEvent = JNFNewObject(env, jctor_NSEvent,
[event type],
[event modifierFlags],
clickCount,
[event buttonNumber],
(jint)localPoint.x, (jint)localPoint.y,
(jint)absP.x, (jint)absP.y,
[event deltaY],
[event deltaX]);
if (jEvent == nil) {
// Unable to create event by some reason.
return;
}
static JNF_CLASS_CACHE(jc_TrayIcon, "sun/lwawt/macosx/CTrayIcon");
static JNF_MEMBER_CACHE(jm_handleMouseEvent, jc_TrayIcon, "handleMouseEvent", "(Lsun/lwawt/macosx/event/NSEvent;)V");
JNFCallVoidMethod(env, peer, jm_handleMouseEvent, jEvent);
}
@end //AWTTrayIcon
//================================================
......@@ -123,7 +164,7 @@ static NSSize ScaledImageSizeForStatusBar(NSSize imageSize) {
-(id)initWithTrayIcon:(AWTTrayIcon *)theTrayIcon {
self = [super initWithFrame:NSMakeRect(0, 0, 1, 1)];
trayIcon = theTrayIcon;
[self setTrayIcon: theTrayIcon];
isHighlighted = NO;
image = nil;
......@@ -153,6 +194,10 @@ static NSSize ScaledImageSizeForStatusBar(NSSize imageSize) {
}
}
-(void)setTrayIcon:(AWTTrayIcon*)theTrayIcon {
trayIcon = theTrayIcon;
}
- (void)menuWillOpen:(NSMenu *)menu
{
[self setHighlighted:YES];
......@@ -191,30 +236,57 @@ static NSSize ScaledImageSizeForStatusBar(NSSize imageSize) {
];
}
- (void) mouseDown:(NSEvent *)e {
//find CTrayIcon.getPopupMenuModel method and call it to get popup menu ptr.
JNIEnv *env = [ThreadUtilities getJNIEnv];
static JNF_CLASS_CACHE(jc_CTrayIcon, "sun/lwawt/macosx/CTrayIcon");
static JNF_MEMBER_CACHE(jm_getPopupMenuModel, jc_CTrayIcon, "getPopupMenuModel", "()J");
static JNF_MEMBER_CACHE(jm_performAction, jc_CTrayIcon, "performAction", "()V");
jlong res = JNFCallLongMethod(env, trayIcon.peer, jm_getPopupMenuModel);
if (res != 0) {
CPopupMenu *cmenu = jlong_to_ptr(res);
NSMenu* menu = [cmenu menu];
[menu setDelegate:self];
[trayIcon.theItem popUpStatusItemMenu:menu];
[self setNeedsDisplay:YES];
} else {
JNFCallVoidMethod(env, trayIcon.peer, jm_performAction);
- (void)mouseDown:(NSEvent *)event {
[trayIcon deliverJavaMouseEvent: event];
// don't show the menu on ctrl+click: it triggers ACTION event, like right click
if (([event modifierFlags] & NSControlKeyMask) == 0) {
//find CTrayIcon.getPopupMenuModel method and call it to get popup menu ptr.
JNIEnv *env = [ThreadUtilities getJNIEnv];
static JNF_CLASS_CACHE(jc_CTrayIcon, "sun/lwawt/macosx/CTrayIcon");
static JNF_MEMBER_CACHE(jm_getPopupMenuModel, jc_CTrayIcon, "getPopupMenuModel", "()J");
jlong res = JNFCallLongMethod(env, trayIcon.peer, jm_getPopupMenuModel);
if (res != 0) {
CPopupMenu *cmenu = jlong_to_ptr(res);
NSMenu* menu = [cmenu menu];
[menu setDelegate:self];
[trayIcon.theItem popUpStatusItemMenu:menu];
[self setNeedsDisplay:YES];
}
}
}
- (void) rightMouseDown:(NSEvent *)e {
// Call CTrayIcon.performAction() method on right mouse press
JNIEnv *env = [ThreadUtilities getJNIEnv];
static JNF_CLASS_CACHE(jc_CTrayIcon, "sun/lwawt/macosx/CTrayIcon");
static JNF_MEMBER_CACHE(jm_performAction, jc_CTrayIcon, "performAction", "()V");
JNFCallVoidMethod(env, trayIcon.peer, jm_performAction);
- (void) mouseUp:(NSEvent *)event {
[trayIcon deliverJavaMouseEvent: event];
}
- (void) mouseDragged:(NSEvent *)event {
[trayIcon deliverJavaMouseEvent: event];
}
- (void) rightMouseDown:(NSEvent *)event {
[trayIcon deliverJavaMouseEvent: event];
}
- (void) rightMouseUp:(NSEvent *)event {
[trayIcon deliverJavaMouseEvent: event];
}
- (void) rightMouseDragged:(NSEvent *)event {
[trayIcon deliverJavaMouseEvent: event];
}
- (void) otherMouseDown:(NSEvent *)event {
[trayIcon deliverJavaMouseEvent: event];
}
- (void) otherMouseUp:(NSEvent *)event {
[trayIcon deliverJavaMouseEvent: event];
}
- (void) otherMouseDragged:(NSEvent *)event {
[trayIcon deliverJavaMouseEvent: event];
}
......
/*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -37,6 +37,9 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
......@@ -46,6 +49,8 @@ import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import sun.misc.SharedSecrets;
/**
* The main class to parse JavaBeans XML archive.
*
......@@ -56,11 +61,10 @@ import org.xml.sax.helpers.DefaultHandler;
* @see ElementHandler
*/
public final class DocumentHandler extends DefaultHandler {
private final Map<String, Class<? extends ElementHandler>> handlers = new HashMap<String, Class<? extends ElementHandler>>();
private final Map<String, Object> environment = new HashMap<String, Object>();
private final List<Object> objects = new ArrayList<Object>();
private final AccessControlContext acc = AccessController.getContext();
private final Map<String, Class<? extends ElementHandler>> handlers = new HashMap<>();
private final Map<String, Object> environment = new HashMap<>();
private final List<Object> objects = new ArrayList<>();
private Reference<ClassLoader> loader;
private ExceptionListener listener;
......@@ -351,23 +355,32 @@ public final class DocumentHandler extends DefaultHandler {
*
* @param input the input source to parse
*/
public void parse(InputSource input) {
try {
SAXParserFactory.newInstance().newSAXParser().parse(input, this);
public void parse(final InputSource input) {
if ((this.acc == null) && (null != System.getSecurityManager())) {
throw new SecurityException("AccessControlContext is not set");
}
catch (ParserConfigurationException exception) {
handleException(exception);
}
catch (SAXException wrapper) {
Exception exception = wrapper.getException();
if (exception == null) {
exception = wrapper;
AccessControlContext stack = AccessController.getContext();
SharedSecrets.getJavaSecurityAccess().doIntersectionPrivilege(new PrivilegedAction<Void>() {
public Void run() {
try {
SAXParserFactory.newInstance().newSAXParser().parse(input, DocumentHandler.this);
}
catch (ParserConfigurationException exception) {
handleException(exception);
}
catch (SAXException wrapper) {
Exception exception = wrapper.getException();
if (exception == null) {
exception = wrapper;
}
handleException(exception);
}
catch (IOException exception) {
handleException(exception);
}
return null;
}
handleException(exception);
}
catch (IOException exception) {
handleException(exception);
}
}, stack, this.acc);
}
/**
......
/*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2012, 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,6 +35,8 @@ import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import sun.reflect.misc.MethodUtil;
/**
* This class is intended to handle &lt;property&gt; element.
* This element simplifies access to the properties.
......@@ -168,11 +170,11 @@ final class PropertyElementHandler extends AccessorElementHandler {
private static Object getPropertyValue(Object bean, String name, Integer index) throws IllegalAccessException, IntrospectionException, InvocationTargetException, NoSuchMethodException {
Class<?> type = bean.getClass();
if (index == null) {
return findGetter(type, name).invoke(bean);
return MethodUtil.invoke(findGetter(type, name), bean, new Object[] {});
} else if (type.isArray() && (name == null)) {
return Array.get(bean, index);
} else {
return findGetter(type, name, int.class).invoke(bean, index);
return MethodUtil.invoke(findGetter(type, name, int.class), bean, new Object[] {index});
}
}
......@@ -197,11 +199,11 @@ final class PropertyElementHandler extends AccessorElementHandler {
: null;
if (index == null) {
findSetter(type, name, param).invoke(bean, value);
MethodUtil.invoke(findSetter(type, name, param), bean, new Object[] {value});
} else if (type.isArray() && (name == null)) {
Array.set(bean, index, value);
} else {
findSetter(type, name, int.class, param).invoke(bean, index, value);
MethodUtil.invoke(findSetter(type, name, int.class, param), bean, new Object[] {index, value});
}
}
......
......@@ -68,9 +68,9 @@ public class ServerNotifForwarder {
this.notifBuffer = notifBuffer;
this.connectionId = connectionId;
connectionTimeout = EnvHelp.getServerConnectionTimeout(env);
checkNotificationEmission = EnvHelp.computeBooleanFromString(
env,
"jmx.remote.x.check.notification.emission",false);
String stringBoolean = (String) env.get("jmx.remote.x.check.notification.emission");
checkNotificationEmission = EnvHelp.computeBooleanFromString( stringBoolean );
notificationAccessController =
EnvHelp.getNotificationAccessController(env);
}
......
......@@ -665,97 +665,57 @@ public class EnvHelp {
* Computes a boolean value from a string value retrieved from a
* property in the given map.
*
* @param env the environment map.
* @param prop the name of the property in the environment map whose
* returned string value must be converted into a boolean value.
* @param systemProperty if true, consult a system property of the
* same name if there is no entry in the environment map.
* @param stringBoolean the string value that must be converted
* into a boolean value.
*
* @return
* <ul>
* <li>{@code false} if {@code env.get(prop)} is {@code null}</li>
* <li>{@code false} if {@code stringBoolean} is {@code null}</li>
* <li>{@code false} if
* {@code ((String)env.get(prop)).equalsIgnoreCase("false")}
* {@code stringBoolean.equalsIgnoreCase("false")}
* is {@code true}</li>
* <li>{@code true} if
* {@code ((String)env.get(prop)).equalsIgnoreCase("true")}
* {@code stringBoolean.equalsIgnoreCase("true")}
* is {@code true}</li>
* </ul>
*
* @throws IllegalArgumentException if {@code env} is {@code null} or
* {@code env.get(prop)} is not {@code null} and
* @throws IllegalArgumentException if
* {@code ((String)env.get(prop)).equalsIgnoreCase("false")} and
* {@code ((String)env.get(prop)).equalsIgnoreCase("true")} are
* {@code false}.
* @throws ClassCastException if {@code env.get(prop)} cannot be cast
* to {@code String}.
*/
public static boolean computeBooleanFromString(
Map<String, ?> env, String prop, boolean systemProperty) {
if (env == null)
throw new IllegalArgumentException("env map cannot be null");
public static boolean computeBooleanFromString(String stringBoolean) {
// returns a default value of 'false' if no property is found...
return computeBooleanFromString(env,prop,systemProperty,false);
return computeBooleanFromString(stringBoolean,false);
}
/**
* Computes a boolean value from a string value retrieved from a
* property in the given map.
*
* @param env the environment map.
* @param prop the name of the property in the environment map whose
* returned string value must be converted into a boolean value.
* @param systemProperty if true, consult a system property of the
* same name if there is no entry in the environment map.
* @param stringBoolean the string value that must be converted
* into a boolean value.
* @param defaultValue a default value to return in case no property
* was defined.
*
* @return
* <ul>
* <li>{@code defaultValue} if {@code env.get(prop)} is {@code null}
* and {@code systemProperty} is {@code false}</li>
* <li>{@code defaultValue} if {@code env.get(prop)} is {@code null}
* and {@code systemProperty} is {@code true} and
* {@code System.getProperty(prop)} is {@code null}</li>
* <li>{@code false} if {@code env.get(prop)} is {@code null}
* and {@code systemProperty} is {@code true} and
* {@code System.getProperty(prop).equalsIgnoreCase("false")}
* is {@code true}</li>
* <li>{@code true} if {@code env.get(prop)} is {@code null}
* and {@code systemProperty} is {@code true} and
* {@code System.getProperty(prop).equalsIgnoreCase("true")}
* is {@code true}</li>
* <li>{@code defaultValue} if {@code stringBoolean}
* is {@code null}</li>
* <li>{@code false} if
* {@code ((String)env.get(prop)).equalsIgnoreCase("false")}
* {@code stringBoolean.equalsIgnoreCase("false")}
* is {@code true}</li>
* <li>{@code true} if
* {@code ((String)env.get(prop)).equalsIgnoreCase("true")}
* {@code stringBoolean.equalsIgnoreCase("true")}
* is {@code true}</li>
* </ul>
*
* @throws IllegalArgumentException if {@code env} is {@code null} or
* {@code env.get(prop)} is not {@code null} and
* @throws IllegalArgumentException if
* {@code ((String)env.get(prop)).equalsIgnoreCase("false")} and
* {@code ((String)env.get(prop)).equalsIgnoreCase("true")} are
* {@code false}.
* @throws ClassCastException if {@code env.get(prop)} cannot be cast
* to {@code String}.
*/
public static boolean computeBooleanFromString(
Map<String, ?> env, String prop,
boolean systemProperty, boolean defaultValue) {
if (env == null)
throw new IllegalArgumentException("env map cannot be null");
String stringBoolean = (String) env.get(prop);
if (stringBoolean == null && systemProperty) {
stringBoolean =
AccessController.doPrivileged(new GetPropertyAction(prop));
}
public static boolean computeBooleanFromString( String stringBoolean, boolean defaultValue) {
if (stringBoolean == null)
return defaultValue;
else if (stringBoolean.equalsIgnoreCase("true"))
......@@ -763,8 +723,8 @@ public class EnvHelp {
else if (stringBoolean.equalsIgnoreCase("false"))
return false;
else
throw new IllegalArgumentException(prop +
" must be \"true\" or \"false\" instead of \"" +
throw new IllegalArgumentException(
"Property value must be \"true\" or \"false\" instead of \"" +
stringBoolean + "\"");
}
......
/*
* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2012, 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
......@@ -29,6 +29,9 @@ import com.sun.beans.decoder.DocumentHandler;
import java.io.Closeable;
import java.io.InputStream;
import java.io.IOException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
......@@ -61,6 +64,7 @@ import org.xml.sax.helpers.DefaultHandler;
* @author Philip Milne
*/
public class XMLDecoder implements AutoCloseable {
private final AccessControlContext acc = AccessController.getContext();
private final DocumentHandler handler = new DocumentHandler();
private final InputSource input;
private Object owner;
......@@ -189,7 +193,15 @@ public class XMLDecoder implements AutoCloseable {
return false;
}
if (this.array == null) {
this.handler.parse(this.input);
if ((this.acc == null) && (null != System.getSecurityManager())) {
throw new SecurityException("AccessControlContext is not set");
}
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
XMLDecoder.this.handler.parse(XMLDecoder.this.input);
return null;
}
}, this.acc);
this.array = this.handler.getObjects();
}
return true;
......
......@@ -407,7 +407,7 @@ public final class FilePermission extends Permission implements Serializable {
* @return a hash code value for this object.
*/
public int hashCode() {
return this.cpath.hashCode();
return 0;
}
/**
......
......@@ -79,7 +79,7 @@ import com.sun.xml.internal.ws.org.objectweb.asm.Type;
default : throw new InternalError("unexpected xtype: " + xtype);
}
} catch (Throwable t) {
throw new InternalError(t);
throw newInternalError(t);
}
}
......@@ -97,7 +97,7 @@ import com.sun.xml.internal.ws.org.objectweb.asm.Type;
case 'D': return cloneExtendD(type, form, (double) x);
}
} catch (Throwable t) {
throw new InternalError(t);
throw newInternalError(t);
}
throw new InternalError("unexpected type: " + xtype);
}
......@@ -115,7 +115,7 @@ import com.sun.xml.internal.ws.org.objectweb.asm.Type;
try {
return clone(srcType, form);
} catch (Throwable t) {
throw new InternalError(t);
throw newInternalError(t);
}
}
......@@ -124,7 +124,7 @@ import com.sun.xml.internal.ws.org.objectweb.asm.Type;
try {
return clone(newType, form.permuteArguments(1, reorder, basicTypes(newType.parameterList())));
} catch (Throwable t) {
throw new InternalError(t);
throw newInternalError(t);
}
}
......@@ -166,7 +166,7 @@ import com.sun.xml.internal.ws.org.objectweb.asm.Type;
case 'J': return argJ(i);
}
} catch (Throwable ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
throw new InternalError("unexpected type: " + speciesData().types+"."+i);
}
......@@ -192,7 +192,7 @@ import com.sun.xml.internal.ws.org.objectweb.asm.Type;
try {
return (MethodHandle) argL(0);
} catch (Throwable ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
}
......@@ -464,7 +464,7 @@ import com.sun.xml.internal.ws.org.objectweb.asm.Type;
}
}
} catch (Throwable e) {
throw new InternalError(e);
throw newInternalError(e);
}
for (SpeciesData d : CACHE.values()) {
......@@ -748,7 +748,7 @@ import com.sun.xml.internal.ws.org.objectweb.asm.Type;
try {
return LOOKUP.findGetter(cbmhClass, fieldName, fieldType);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new InternalError(e);
throw newInternalError(e);
}
}
......@@ -776,7 +776,7 @@ import com.sun.xml.internal.ws.org.objectweb.asm.Type;
Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA");
return (SpeciesData) F_SPECIES_DATA.get(null);
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
}
......@@ -802,7 +802,7 @@ import com.sun.xml.internal.ws.org.objectweb.asm.Type;
try {
return linkConstructor(LOOKUP.findConstructor(cbmh, MethodType.fromMethodDescriptorString(makeSignature(types, true), null)));
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | TypeNotPresentException e) {
throw new InternalError(e);
throw newInternalError(e);
}
}
......@@ -833,7 +833,7 @@ import com.sun.xml.internal.ws.org.objectweb.asm.Type;
linkerMN = MemberName.getFactory().resolveOrFail(REF_invokeStatic, linkerMN, null, NoSuchMethodException.class);
assert(linkerMN.isStatic());
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
// extend arguments array
Object[] newArgs = Arrays.copyOf(initName.arguments, initName.arguments.length + 1);
......
......@@ -222,7 +222,7 @@ public class CallSite {
GET_TARGET = IMPL_LOOKUP.
findVirtual(CallSite.class, "getTarget", MethodType.methodType(MethodHandle.class));
} catch (ReflectiveOperationException e) {
throw new InternalError(e);
throw newInternalError(e);
}
}
......
......@@ -218,7 +218,7 @@ class DirectMethodHandle extends MethodHandle {
try {
linker = IMPL_NAMES.resolveOrFail(REF_invokeStatic, linker, null, NoSuchMethodException.class);
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
final int DMH_THIS = 0;
final int ARG_BASE = 1;
......@@ -554,7 +554,7 @@ class DirectMethodHandle extends MethodHandle {
try {
linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, NoSuchMethodException.class);
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
// What is the external type of the lambda form?
......@@ -653,7 +653,7 @@ class DirectMethodHandle extends MethodHandle {
nf.resolve();
}
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
}
}
......@@ -138,7 +138,7 @@ class InvokerBytecodeGenerator {
DUMP_CLASS_FILES_DIR = dumpDir;
System.out.println("Dumping class files to "+DUMP_CLASS_FILES_DIR+"/...");
} catch (Exception e) {
throw new InternalError(e);
throw newInternalError(e);
}
} else {
DUMP_CLASS_FILES_COUNTERS = null;
......@@ -162,7 +162,7 @@ class InvokerBytecodeGenerator {
file.close();
return null;
} catch (IOException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
}
});
......@@ -279,7 +279,7 @@ class InvokerBytecodeGenerator {
try {
member = MEMBERNAME_FACTORY.resolveOrFail(REF_invokeStatic, member, HOST_CLASS, ReflectiveOperationException.class);
} catch (ReflectiveOperationException e) {
throw new InternalError(e);
throw newInternalError(e);
}
//System.out.println("resolveInvokerMember => "+member);
return member;
......
......@@ -27,6 +27,7 @@ package java.lang.invoke;
import java.util.Arrays;
import sun.invoke.empty.Empty;
import static java.lang.invoke.MethodHandleStatics.*;
import static java.lang.invoke.MethodHandleNatives.Constants.*;
import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
import static java.lang.invoke.LambdaForm.*;
......@@ -128,9 +129,8 @@ class Invokers {
try {
//Lookup.findVirtual(MethodHandle.class, name, type);
return IMPL_LOOKUP.resolveOrFail(REF_invokeVirtual, MethodHandle.class, name, type);
} catch (ReflectiveOperationException ex) {
throw new InternalError("JVM cannot find invoker for "+type, ex);
throw newInternalError("JVM cannot find invoker for "+type, ex);
}
}
......@@ -176,7 +176,7 @@ class Invokers {
.findVirtual(MethodHandle.class, "asSpreader",
MethodType.methodType(MethodHandle.class, Class.class, int.class));
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
makeSpreader = MethodHandles.insertArguments(makeSpreader, 1, Object[].class, spreadArgCount);
vaInvoker = MethodHandles.filterArgument(arrayInvoker, 0, makeSpreader);
......@@ -215,7 +215,7 @@ class Invokers {
.findStatic(CallSite.class, "uninitializedCallSite",
MethodType.methodType(Empty.class));
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
}
invoker = MethodHandles.explicitCastArguments(invoker, MethodType.methodType(targetType.returnType()));
......@@ -389,7 +389,7 @@ class Invokers {
form.genericInvoker = gamh;
return gamh;
} catch (Exception ex) {
throw new InternalError("Exception while resolving inexact invoke", ex);
throw newInternalError("Exception while resolving inexact invoke", ex);
}
}
......@@ -456,7 +456,7 @@ class Invokers {
NF_getCallSiteTarget.resolve();
// bound
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
}
......
......@@ -457,7 +457,7 @@ class LambdaForm {
isCompiled = true;
return vmentry;
} catch (Error | Exception ex) {
throw new InternalError(this.toString(), ex);
throw newInternalError(this.toString(), ex);
}
}
......@@ -1547,7 +1547,7 @@ class LambdaForm {
try {
zmem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zmem, null, NoSuchMethodException.class);
} catch (IllegalAccessException|NoSuchMethodException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
NamedFunction zcon = new NamedFunction(zmem);
Name n = new Name(zcon).newIndex(0);
......
......@@ -558,7 +558,7 @@ import java.util.Objects;
try {
return (MemberName) super.clone();
} catch (CloneNotSupportedException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
}
......
......@@ -1372,7 +1372,7 @@ assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
NF_reinvokerTarget = new LambdaForm.NamedFunction(MethodHandle.class
.getDeclaredMethod("reinvokerTarget"));
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
}
......@@ -1397,7 +1397,7 @@ assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
try {
FORM_OFFSET = UNSAFE.objectFieldOffset(MethodHandle.class.getDeclaredField("form"));
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
}
}
/*
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2012, 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,13 +25,14 @@
package java.lang.invoke;
import sun.invoke.util.VerifyType;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import sun.invoke.empty.Empty;
import sun.invoke.util.ValueConversions;
import sun.invoke.util.VerifyType;
import sun.invoke.util.Wrapper;
import static java.lang.invoke.LambdaForm.*;
import static java.lang.invoke.MethodHandleStatics.*;
......@@ -478,7 +479,7 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
.getDeclaredMethod("checkSpreadArgument", Object.class, int.class));
NF_checkSpreadArgument.resolve();
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw newInternalError(ex);
}
}
......@@ -781,4 +782,168 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
return mh;
}
/**
* Create an alias for the method handle which, when called,
* appears to be called from the same class loader and protection domain
* as hostClass.
* This is an expensive no-op unless the method which is called
* is sensitive to its caller. A small number of system methods
* are in this category, including Class.forName and Method.invoke.
*/
static
MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
return BindCaller.bindCaller(mh, hostClass);
}
// Put the whole mess into its own nested class.
// That way we can lazily load the code and set up the constants.
private static class BindCaller {
static
MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
// Do not use this function to inject calls into system classes.
if (hostClass == null) {
hostClass = C_Trampoline;
} else if (hostClass.isArray() ||
hostClass.isPrimitive() ||
hostClass.getName().startsWith("java.") ||
hostClass.getName().startsWith("sun.")) {
throw new InternalError(); // does not happen, and should not anyway
}
// For simplicity, convert mh to a varargs-like method.
MethodHandle vamh = prepareForInvoker(mh);
// Cache the result of makeInjectedInvoker once per argument class.
MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass);
return restoreToType(bccInvoker.bindTo(vamh), mh.type());
}
// This class ("Trampoline") is known to be inside a dead-end class loader.
// Inject all doubtful calls into this class.
private static Class<?> C_Trampoline;
static {
Class<?> tramp = null;
try {
final int FRAME_COUNT_ARG = 1; // [0] Reflection [1] Trampoline
java.lang.reflect.Method gcc = sun.reflect.Reflection.class.getMethod("getCallerClass", int.class);
tramp = (Class<?>) sun.reflect.misc.MethodUtil.invoke(gcc, null, new Object[]{ FRAME_COUNT_ARG });
if (tramp.getClassLoader() == BindCaller.class.getClassLoader())
throw new RuntimeException(tramp.getName()+" class loader");
} catch (Throwable ex) {
throw new InternalError(ex);
}
C_Trampoline = tramp;
}
private static MethodHandle makeInjectedInvoker(Class<?> hostClass) {
Class<?> bcc = UNSAFE.defineAnonymousClass(hostClass, T_BYTES, null);
if (hostClass.getClassLoader() != bcc.getClassLoader())
throw new InternalError(hostClass.getName()+" (CL)");
try {
if (hostClass.getProtectionDomain() != bcc.getProtectionDomain())
throw new InternalError(hostClass.getName()+" (PD)");
} catch (SecurityException ex) {
// Self-check was blocked by security manager. This is OK.
// In fact the whole try body could be turned into an assertion.
}
try {
MethodHandle init = IMPL_LOOKUP.findStatic(bcc, "init", MethodType.methodType(void.class));
init.invokeExact(); // force initialization of the class
} catch (Throwable ex) {
throw uncaughtException(ex);
}
MethodHandle bccInvoker;
try {
MethodType invokerMT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
bccInvoker = IMPL_LOOKUP.findStatic(bcc, "invoke_V", invokerMT);
} catch (ReflectiveOperationException ex) {
throw uncaughtException(ex);
}
// Test the invoker, to ensure that it really injects into the right place.
try {
MethodHandle vamh = prepareForInvoker(MH_checkCallerClass);
Object ok = bccInvoker.invokeExact(vamh, new Object[]{hostClass, bcc});
} catch (Throwable ex) {
throw new InternalError(ex);
}
return bccInvoker;
}
private static ClassValue<MethodHandle> CV_makeInjectedInvoker = new ClassValue<MethodHandle>() {
@Override protected MethodHandle computeValue(Class<?> hostClass) {
return makeInjectedInvoker(hostClass);
}
};
// Adapt mh so that it can be called directly from an injected invoker:
private static MethodHandle prepareForInvoker(MethodHandle mh) {
mh = mh.asFixedArity();
MethodType mt = mh.type();
int arity = mt.parameterCount();
MethodHandle vamh = mh.asType(mt.generic());
vamh.internalForm().compileToBytecode(); // eliminate LFI stack frames
vamh = vamh.asSpreader(Object[].class, arity);
vamh.internalForm().compileToBytecode(); // eliminate LFI stack frames
return vamh;
}
// Undo the adapter effect of prepareForInvoker:
private static MethodHandle restoreToType(MethodHandle vamh, MethodType type) {
return vamh.asCollector(Object[].class, type.parameterCount()).asType(type);
}
private static final MethodHandle MH_checkCallerClass;
static {
final Class<?> THIS_CLASS = BindCaller.class;
assert(checkCallerClass(THIS_CLASS, THIS_CLASS));
try {
MH_checkCallerClass = IMPL_LOOKUP
.findStatic(THIS_CLASS, "checkCallerClass",
MethodType.methodType(boolean.class, Class.class, Class.class));
assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS, THIS_CLASS));
} catch (Throwable ex) {
throw new InternalError(ex);
}
}
private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) {
final int FRAME_COUNT_ARG = 2; // [0] Reflection [1] BindCaller [2] Expected
Class<?> actual = sun.reflect.Reflection.getCallerClass(FRAME_COUNT_ARG);
if (actual != expected && actual != expected2)
throw new InternalError("found "+actual.getName()+", expected "+expected.getName()
+(expected == expected2 ? "" : ", or else "+expected2.getName()));
return true;
}
private static final byte[] T_BYTES;
static {
final Object[] values = {null};
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
try {
Class<T> tClass = T.class;
String tName = tClass.getName();
String tResource = tName.substring(tName.lastIndexOf('.')+1)+".class";
java.net.URLConnection uconn = tClass.getResource(tResource).openConnection();
int len = uconn.getContentLength();
byte[] bytes = new byte[len];
try (java.io.InputStream str = uconn.getInputStream()) {
int nr = str.read(bytes);
if (nr != len) throw new java.io.IOException(tResource);
}
values[0] = bytes;
} catch (java.io.IOException ex) {
throw new InternalError(ex);
}
return null;
}
});
T_BYTES = (byte[]) values[0];
}
// The following class is used as a template for Unsafe.defineAnonymousClass:
private static class T {
static void init() { } // side effect: initializes this class
static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable {
return vamh.invokeExact(args);
}
}
}
}
......@@ -385,4 +385,101 @@ class MethodHandleNatives {
throw err;
}
}
/**
* Is this method a caller-sensitive method?
* I.e., does it call Reflection.getCallerClass or a similer method
* to ask about the identity of its caller?
*/
// FIXME: Replace this pattern match by an annotation @sun.reflect.CallerSensitive.
static boolean isCallerSensitive(MemberName mem) {
assert(mem.isInvocable());
Class<?> defc = mem.getDeclaringClass();
switch (mem.getName()) {
case "doPrivileged":
return defc == java.security.AccessController.class;
case "getUnsafe":
return defc == sun.misc.Unsafe.class;
case "lookup":
return defc == java.lang.invoke.MethodHandles.class;
case "invoke":
return defc == java.lang.reflect.Method.class;
case "get":
case "getBoolean":
case "getByte":
case "getChar":
case "getShort":
case "getInt":
case "getLong":
case "getFloat":
case "getDouble":
case "set":
case "setBoolean":
case "setByte":
case "setChar":
case "setShort":
case "setInt":
case "setLong":
case "setFloat":
case "setDouble":
return defc == java.lang.reflect.Field.class;
case "newInstance":
if (defc == java.lang.reflect.Constructor.class) return true;
if (defc == java.lang.Class.class) return true;
break;
case "forName":
case "getClassLoader":
case "getClasses":
case "getFields":
case "getMethods":
case "getConstructors":
case "getDeclaredClasses":
case "getDeclaredFields":
case "getDeclaredMethods":
case "getDeclaredConstructors":
case "getField":
case "getMethod":
case "getConstructor":
case "getDeclaredField":
case "getDeclaredMethod":
case "getDeclaredConstructor":
return defc == java.lang.Class.class;
case "getConnection":
case "getDriver":
case "getDrivers":
case "deregisterDriver":
return defc == java.sql.DriverManager.class;
case "newUpdater":
if (defc == java.util.concurrent.atomic.AtomicIntegerFieldUpdater.class) return true;
if (defc == java.util.concurrent.atomic.AtomicLongFieldUpdater.class) return true;
if (defc == java.util.concurrent.atomic.AtomicReferenceFieldUpdater.class) return true;
break;
case "getContextClassLoader":
return defc == java.lang.Thread.class;
case "getPackage":
case "getPackages":
return defc == java.lang.Package.class;
case "getParent":
case "getSystemClassLoader":
return defc == java.lang.ClassLoader.class;
case "load":
case "loadLibrary":
if (defc == java.lang.Runtime.class) return true;
if (defc == java.lang.System.class) return true;
break;
case "getCallerClass":
if (defc == sun.reflect.Reflection.class) return true;
if (defc == java.lang.System.class) return true;
break;
case "getCallerClassLoader":
return defc == java.lang.ClassLoader.class;
case "getProxyClass":
case "newProxyInstance":
return defc == java.lang.reflect.Proxy.class;
case "getBundle":
case "clearCache":
return defc == java.util.ResourceBundle.class;
}
return false;
}
}
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2012, 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
......@@ -93,6 +93,12 @@ import sun.misc.Unsafe;
}
// handy shared exception makers (they simplify the common case code)
/*non-public*/ static InternalError newInternalError(String message, Throwable cause) {
return new InternalError(message, cause);
}
/*non-public*/ static InternalError newInternalError(Throwable cause) {
return new InternalError(cause);
}
/*non-public*/ static RuntimeException newIllegalStateException(String message) {
return new IllegalStateException(message);
}
......@@ -108,8 +114,8 @@ import sun.misc.Unsafe;
/*non-public*/ static RuntimeException newIllegalArgumentException(String message, Object obj, Object obj2) {
return new IllegalArgumentException(message(message, obj, obj2));
}
/*non-public*/ static Error uncaughtException(Exception ex) {
throw new InternalError("uncaught exception", ex);
/*non-public*/ static Error uncaughtException(Throwable ex) {
throw newInternalError("uncaught exception", ex);
}
static Error NYI() {
throw new AssertionError("NYI");
......
/*
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2012, 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
......@@ -329,6 +329,7 @@ public class MethodHandles {
* where {@code defcPkg} is the package of {@code defc}.
* </ul>
*/
// FIXME in MR1: clarify that the bytecode behavior of a caller-ID method (like Class.forName) is relative to the lookupClass used to create the method handle, not the dynamic caller of the method handle
public static final
class Lookup {
/** The class on behalf of whom the lookup is being performed. */
......@@ -1209,6 +1210,7 @@ return mh1;
if (method.isMethodHandleInvoke())
return fakeMethodHandleInvoke(method);
MethodHandle mh = DirectMethodHandle.make(refc, method);
mh = maybeBindCaller(method, mh);
mh = mh.setVarargs(method);
if (doRestrict)
mh = restrictReceiver(method, mh, lookupClass());
......@@ -1217,6 +1219,16 @@ return mh1;
private MethodHandle fakeMethodHandleInvoke(MemberName method) {
return throwException(method.getReturnType(), UnsupportedOperationException.class);
}
private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh) throws IllegalAccessException {
if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
return mh;
Class<?> hostClass = lookupClass;
if ((allowedModes & PRIVATE) == 0) // caller must use full-power lookup
hostClass = null;
MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
// Note: caller will apply varargs after this step happens.
return cbmh;
}
private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
checkField(refKind, refc, field);
MethodHandle mh = DirectMethodHandle.make(refc, field);
......@@ -1229,6 +1241,7 @@ return mh1;
private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
assert(ctor.isConstructor());
checkAccess(REF_newInvokeSpecial, refc, ctor);
assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here
return DirectMethodHandle.make(ctor).setVarargs(ctor);
}
......
/*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2012, 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
......@@ -290,11 +290,11 @@ public final class AccessController {
*/
public static <T> T doPrivilegedWithCombiner(PrivilegedAction<T> action) {
DomainCombiner dc = null;
AccessControlContext acc = getStackAccessControlContext();
if (acc == null || (dc = acc.getAssignedCombiner()) == null) {
if (acc == null) {
return AccessController.doPrivileged(action);
}
DomainCombiner dc = acc.getAssignedCombiner();
return AccessController.doPrivileged(action, preserveCombiner(dc));
}
......@@ -386,11 +386,11 @@ public final class AccessController {
public static <T> T doPrivilegedWithCombiner
(PrivilegedExceptionAction<T> action) throws PrivilegedActionException {
DomainCombiner dc = null;
AccessControlContext acc = getStackAccessControlContext();
if (acc == null || (dc = acc.getAssignedCombiner()) == null) {
if (acc == null) {
return AccessController.doPrivileged(action);
}
DomainCombiner dc = acc.getAssignedCombiner();
return AccessController.doPrivileged(action, preserveCombiner(dc));
}
......@@ -417,7 +417,12 @@ public final class AccessController {
// perform 'combine' on the caller of doPrivileged,
// even if the caller is from the bootclasspath
ProtectionDomain[] pds = new ProtectionDomain[] {callerPd};
return new AccessControlContext(combiner.combine(pds, null), combiner);
if (combiner == null) {
return new AccessControlContext(pds);
} else {
return new AccessControlContext(combiner.combine(pds, null),
combiner);
}
}
......
......@@ -358,14 +358,21 @@ public final class ServiceLoader<S>
}
String cn = nextName;
nextName = null;
Class<?> c = null;
try {
S p = service.cast(Class.forName(cn, true, loader)
.newInstance());
providers.put(cn, p);
return p;
c = Class.forName(cn, false, loader);
} catch (ClassNotFoundException x) {
fail(service,
"Provider " + cn + " not found");
}
if (!service.isAssignableFrom(c)) {
fail(service,
"Provider " + cn + " not a subtype");
}
try {
S p = service.cast(c.newInstance());
providers.put(cn, p);
return p;
} catch (Throwable x) {
fail(service,
"Provider " + cn + " could not be instantiated: " + x,
......
......@@ -530,18 +530,17 @@ public class Executors {
return AccessController.doPrivileged(
new PrivilegedExceptionAction<T>() {
public T run() throws Exception {
ClassLoader savedcl = null;
Thread t = Thread.currentThread();
try {
ClassLoader cl = t.getContextClassLoader();
if (ccl != cl) {
t.setContextClassLoader(ccl);
savedcl = cl;
}
ClassLoader cl = t.getContextClassLoader();
if (ccl == cl) {
return task.call();
} finally {
if (savedcl != null)
t.setContextClassLoader(savedcl);
} else {
t.setContextClassLoader(ccl);
try {
return task.call();
} finally {
t.setContextClassLoader(cl);
}
}
}
}, acc);
......
......@@ -233,7 +233,7 @@ public class FileHandler extends StreamHandler {
* @exception NullPointerException if pattern property is an empty String.
*/
public FileHandler() throws IOException, SecurityException {
checkAccess();
checkPermission();
configure();
openFiles();
}
......@@ -259,7 +259,7 @@ public class FileHandler extends StreamHandler {
if (pattern.length() < 1 ) {
throw new IllegalArgumentException();
}
checkAccess();
checkPermission();
configure();
this.pattern = pattern;
this.limit = 0;
......@@ -291,7 +291,7 @@ public class FileHandler extends StreamHandler {
if (pattern.length() < 1 ) {
throw new IllegalArgumentException();
}
checkAccess();
checkPermission();
configure();
this.pattern = pattern;
this.limit = 0;
......@@ -328,7 +328,7 @@ public class FileHandler extends StreamHandler {
if (limit < 0 || count < 1 || pattern.length() < 1) {
throw new IllegalArgumentException();
}
checkAccess();
checkPermission();
configure();
this.pattern = pattern;
this.limit = limit;
......@@ -367,7 +367,7 @@ public class FileHandler extends StreamHandler {
if (limit < 0 || count < 1 || pattern.length() < 1) {
throw new IllegalArgumentException();
}
checkAccess();
checkPermission();
configure();
this.pattern = pattern;
this.limit = limit;
......@@ -380,7 +380,7 @@ public class FileHandler extends StreamHandler {
// configured instance variables.
private void openFiles() throws IOException {
LogManager manager = LogManager.getLogManager();
manager.checkAccess();
manager.checkPermission();
if (count < 1) {
throw new IllegalArgumentException("file count = " + count);
}
......
......@@ -111,7 +111,7 @@ public abstract class Handler {
* the caller does not have <tt>LoggingPermission("control")</tt>.
*/
public void setFormatter(Formatter newFormatter) throws SecurityException {
checkAccess();
checkPermission();
// Check for a null pointer:
newFormatter.getClass();
formatter = newFormatter;
......@@ -140,7 +140,7 @@ public abstract class Handler {
*/
public void setEncoding(String encoding)
throws SecurityException, java.io.UnsupportedEncodingException {
checkAccess();
checkPermission();
if (encoding != null) {
try {
if(!java.nio.charset.Charset.isSupported(encoding)) {
......@@ -175,7 +175,7 @@ public abstract class Handler {
* the caller does not have <tt>LoggingPermission("control")</tt>.
*/
public void setFilter(Filter newFilter) throws SecurityException {
checkAccess();
checkPermission();
filter = newFilter;
}
......@@ -199,7 +199,7 @@ public abstract class Handler {
* the caller does not have <tt>LoggingPermission("control")</tt>.
*/
public void setErrorManager(ErrorManager em) {
checkAccess();
checkPermission();
if (em == null) {
throw new NullPointerException();
}
......@@ -213,7 +213,7 @@ public abstract class Handler {
* the caller does not have <tt>LoggingPermission("control")</tt>.
*/
public ErrorManager getErrorManager() {
checkAccess();
checkPermission();
return errorManager;
}
......@@ -253,7 +253,7 @@ public abstract class Handler {
if (newLevel == null) {
throw new NullPointerException();
}
checkAccess();
checkPermission();
logLevel = newLevel;
}
......@@ -296,9 +296,9 @@ public abstract class Handler {
// If "sealed" is true, we check that the caller has
// appropriate security privileges to update Handler
// state and if not throw a SecurityException.
void checkAccess() throws SecurityException {
void checkPermission() throws SecurityException {
if (sealed) {
manager.checkAccess();
manager.checkPermission();
}
}
}
......@@ -321,7 +321,7 @@ public class LogManager {
@Deprecated
public void addPropertyChangeListener(PropertyChangeListener l) throws SecurityException {
PropertyChangeListener listener = Objects.requireNonNull(l);
checkAccess();
checkPermission();
synchronized (listenerMap) {
// increment the registration count if already registered
Integer value = listenerMap.get(listener);
......@@ -352,7 +352,7 @@ public class LogManager {
*/
@Deprecated
public void removePropertyChangeListener(PropertyChangeListener l) throws SecurityException {
checkAccess();
checkPermission();
if (l != null) {
PropertyChangeListener listener = l;
synchronized (listenerMap) {
......@@ -807,7 +807,7 @@ public class LogManager {
* @exception IOException if there are IO problems reading the configuration.
*/
public void readConfiguration() throws IOException, SecurityException {
checkAccess();
checkPermission();
// if a configuration class is specified, load it and use it.
String cname = System.getProperty("java.util.logging.config.class");
......@@ -865,7 +865,7 @@ public class LogManager {
*/
public void reset() throws SecurityException {
checkAccess();
checkPermission();
synchronized (this) {
props = new Properties();
// Since we are doing a reset we no longer want to initialize
......@@ -950,7 +950,7 @@ public class LogManager {
* @exception IOException if there are problems reading from the stream.
*/
public void readConfiguration(InputStream ins) throws IOException, SecurityException {
checkAccess();
checkPermission();
reset();
// Load the properties
......@@ -1127,8 +1127,13 @@ public class LogManager {
loadLoggerHandlers(rootLogger, null, "handlers");
}
private final Permission controlPermission = new LoggingPermission("control", null);
private Permission ourPermission = new LoggingPermission("control", null);
void checkPermission() {
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(controlPermission);
}
/**
* Check that the current context is trusted to modify the logging
......@@ -1141,11 +1146,7 @@ public class LogManager {
* the caller does not have LoggingPermission("control").
*/
public void checkAccess() throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
return;
}
sm.checkPermission(ourPermission);
checkPermission();
}
// Nested class to represent a node in our tree of named loggers.
......
......@@ -276,13 +276,13 @@ public class Logger {
this.manager = manager;
}
private void checkAccess() throws SecurityException {
private void checkPermission() throws SecurityException {
if (!anonymous) {
if (manager == null) {
// Complete initialization of the global Logger.
manager = LogManager.getLogManager();
}
manager.checkAccess();
manager.checkPermission();
}
}
......@@ -482,7 +482,7 @@ public class Logger {
* the caller does not have LoggingPermission("control").
*/
public void setFilter(Filter newFilter) throws SecurityException {
checkAccess();
checkPermission();
filter = newFilter;
}
......@@ -1168,7 +1168,7 @@ public class Logger {
* the caller does not have LoggingPermission("control").
*/
public void setLevel(Level newLevel) throws SecurityException {
checkAccess();
checkPermission();
synchronized (treeLock) {
levelObject = newLevel;
updateEffectiveLevel();
......@@ -1223,7 +1223,7 @@ public class Logger {
public void addHandler(Handler handler) throws SecurityException {
// Check for null handler
handler.getClass();
checkAccess();
checkPermission();
handlers.add(handler);
}
......@@ -1237,7 +1237,7 @@ public class Logger {
* the caller does not have LoggingPermission("control").
*/
public void removeHandler(Handler handler) throws SecurityException {
checkAccess();
checkPermission();
if (handler == null) {
return;
}
......@@ -1265,7 +1265,7 @@ public class Logger {
* the caller does not have LoggingPermission("control").
*/
public void setUseParentHandlers(boolean useParentHandlers) {
checkAccess();
checkPermission();
this.useParentHandlers = useParentHandlers;
}
......@@ -1420,7 +1420,7 @@ public class Logger {
if (parent == null) {
throw new NullPointerException();
}
manager.checkAccess();
manager.checkPermission();
doSetParent(parent);
}
......
......@@ -257,7 +257,7 @@ public class MemoryHandler extends Handler {
throw new NullPointerException();
}
LogManager manager = LogManager.getLogManager();
checkAccess();
checkPermission();
pushLevel = newLevel;
}
......
......@@ -263,7 +263,7 @@ public class StreamHandler extends Handler {
}
private synchronized void flushAndClose() throws SecurityException {
checkAccess();
checkPermission();
if (writer != null) {
try {
if (!doneHeader) {
......
......@@ -1245,13 +1245,12 @@ public class DescriptorSupport
return s.substring(1, s.length() - 1);
}
final String className = s.substring(1, slash);
final Constructor<?> constr;
try {
ReflectUtil.checkPackageAccess(className);
final ClassLoader contextClassLoader =
Thread.currentThread().getContextClassLoader();
if (contextClassLoader == null) {
ReflectUtil.checkPackageAccess(className);
}
final Class<?> c =
Class.forName(className, false, contextClassLoader);
constr = c.getConstructor(new Class<?>[] {String.class});
......
/*
* Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2012, 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,54 +25,40 @@
package javax.management.remote.rmi;
import static com.sun.jmx.mbeanserver.Util.cast;
import com.sun.jmx.remote.internal.ServerCommunicatorAdmin;
import com.sun.jmx.remote.internal.ServerNotifForwarder;
import com.sun.jmx.remote.security.JMXSubjectDomainCombiner;
import com.sun.jmx.remote.security.SubjectDelegator;
import com.sun.jmx.remote.util.ClassLoaderWithRepository;
import com.sun.jmx.remote.util.ClassLogger;
import com.sun.jmx.remote.util.EnvHelp;
import com.sun.jmx.remote.util.OrderClassLoaders;
import java.io.IOException;
import java.rmi.MarshalledObject;
import java.rmi.UnmarshalException;
import java.rmi.server.Unreferenced;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.NotificationFilter;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.RuntimeOperationsException;
import javax.management.*;
import javax.management.remote.JMXServerErrorException;
import javax.management.remote.NotificationResult;
import javax.management.remote.TargetedNotification;
import javax.security.auth.Subject;
import static com.sun.jmx.mbeanserver.Util.cast;
import com.sun.jmx.remote.internal.ServerCommunicatorAdmin;
import com.sun.jmx.remote.internal.ServerNotifForwarder;
import com.sun.jmx.remote.security.JMXSubjectDomainCombiner;
import com.sun.jmx.remote.security.SubjectDelegator;
import com.sun.jmx.remote.util.ClassLoaderWithRepository;
import com.sun.jmx.remote.util.ClassLogger;
import com.sun.jmx.remote.util.EnvHelp;
import com.sun.jmx.remote.util.OrderClassLoaders;
/**
* <p>Implementation of the {@link RMIConnection} interface. User
* code will not usually reference this class.</p>
......@@ -143,6 +129,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
this.mbeanServer = rmiServer.getMBeanServer();
final ClassLoader dcl = defaultClassLoader;
this.classLoaderWithRepository =
AccessController.doPrivileged(
new PrivilegedAction<ClassLoaderWithRepository>() {
......@@ -151,13 +138,40 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
mbeanServer.getClassLoaderRepository(),
dcl);
}
},
withPermissions( new MBeanPermission("*", "getClassLoaderRepository"),
new RuntimePermission("createClassLoader"))
);
this.defaultContextClassLoader =
AccessController.doPrivileged(
new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return new CombinedClassLoader(Thread.currentThread().getContextClassLoader(),
dcl);
}
});
serverCommunicatorAdmin = new
RMIServerCommunicatorAdmin(EnvHelp.getServerConnectionTimeout(env));
this.env = env;
}
private static AccessControlContext withPermissions(Permission ... perms){
Permissions col = new Permissions();
for (Permission thePerm : perms ) {
col.add(thePerm);
}
final ProtectionDomain pd = new ProtectionDomain(null, col);
return new AccessControlContext( new ProtectionDomain[] { pd });
}
private synchronized ServerNotifForwarder getServerNotifFwd() {
// Lazily created when first use. Mainly when
// addNotificationListener is first called.
......@@ -507,7 +521,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
"connectionId=" + connectionId
+" unwrapping query with defaultClassLoader.");
queryValue = unwrap(query, defaultClassLoader, QueryExp.class);
queryValue = unwrap(query, defaultContextClassLoader, QueryExp.class);
try {
final Object params[] = new Object[] { name, queryValue };
......@@ -542,7 +556,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
"connectionId=" + connectionId
+" unwrapping query with defaultClassLoader.");
queryValue = unwrap(query, defaultClassLoader, QueryExp.class);
queryValue = unwrap(query, defaultContextClassLoader, QueryExp.class);
try {
final Object params[] = new Object[] { name, queryValue };
......@@ -1330,7 +1344,9 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
public ClassLoader run() throws InstanceNotFoundException {
return mbeanServer.getClassLoader(name);
}
});
},
withPermissions(new MBeanPermission("*", "getClassLoader"))
);
} catch (PrivilegedActionException pe) {
throw (InstanceNotFoundException) extractException(pe);
}
......@@ -1345,7 +1361,9 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
public Object run() throws InstanceNotFoundException {
return mbeanServer.getClassLoaderFor(name);
}
});
},
withPermissions(new MBeanPermission("*", "getClassLoaderFor"))
);
} catch (PrivilegedActionException pe) {
throw (InstanceNotFoundException) extractException(pe);
}
......@@ -1572,7 +1590,8 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
ClassLoader orderCL = AccessController.doPrivileged(
new PrivilegedExceptionAction<ClassLoader>() {
public ClassLoader run() throws Exception {
return new OrderClassLoaders(cl1, cl2);
return new CombinedClassLoader(Thread.currentThread().getContextClassLoader(),
new OrderClassLoaders(cl1, cl2));
}
}
);
......@@ -1664,6 +1683,8 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
private final ClassLoader defaultClassLoader;
private final ClassLoader defaultContextClassLoader;
private final ClassLoaderWithRepository classLoaderWithRepository;
private boolean terminated = false;
......@@ -1746,4 +1767,43 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
private static final ClassLogger logger =
new ClassLogger("javax.management.remote.rmi", "RMIConnectionImpl");
private static final class CombinedClassLoader extends ClassLoader {
private final static class ClassLoaderWrapper extends ClassLoader {
ClassLoaderWrapper(ClassLoader cl) {
super(cl);
}
@Override
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
return super.loadClass(name, resolve);
}
};
final ClassLoaderWrapper defaultCL;
private CombinedClassLoader(ClassLoader parent, ClassLoader defaultCL) {
super(parent);
this.defaultCL = new ClassLoaderWrapper(defaultCL);
}
@Override
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
try {
super.loadClass(name, resolve);
} catch(Exception e) {
for(Throwable t = e; t != null; t = t.getCause()) {
if(t instanceof SecurityException) {
throw t==e?(SecurityException)t:new SecurityException(t.getMessage(), e);
}
}
}
final Class<?> cl = defaultCL.loadClass(name, resolve);
return cl;
}
}
}
......@@ -277,9 +277,9 @@ public class RMIConnector implements JMXConnector, Serializable, JMXAddressable
// Check for secure RMIServer stub if the corresponding
// client-side environment property is set to "true".
//
boolean checkStub = EnvHelp.computeBooleanFromString(
usemap,
"jmx.remote.x.check.stub",false);
String stringBoolean = (String) usemap.get("jmx.remote.x.check.stub");
boolean checkStub = EnvHelp.computeBooleanFromString(stringBoolean);
if (checkStub) checkStub(stub, rmiServerImplStubClass);
// Connect IIOP Stub if needed.
......
......@@ -412,9 +412,8 @@ public class RMIConnectorServer extends JMXConnectorServer {
if (tracing)
logger.trace("start", "Using external directory: " + jndiUrl);
final boolean rebind = EnvHelp.computeBooleanFromString(
attributes,
JNDI_REBIND_ATTRIBUTE,false);
String stringBoolean = (String) attributes.get(JNDI_REBIND_ATTRIBUTE);
final boolean rebind = EnvHelp.computeBooleanFromString( stringBoolean );
if (tracing)
logger.trace("start", JNDI_REBIND_ATTRIBUTE + "=" + rebind);
......
......@@ -24,6 +24,8 @@
*/
package javax.swing.text;
import sun.reflect.misc.ConstructorUtil;
import java.io.Serializable;
import java.lang.reflect.*;
import java.text.ParseException;
......@@ -245,7 +247,7 @@ public class DefaultFormatter extends JFormattedTextField.AbstractFormatter
Constructor cons;
try {
cons = vc.getConstructor(new Class[] { String.class });
cons = ConstructorUtil.getConstructor(vc, new Class[]{String.class});
} catch (NoSuchMethodException nsme) {
cons = null;
......
/*
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2012, 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
......@@ -73,74 +73,14 @@ import sun.misc.IOUtils;
public class AnonymousClassLoader {
final Class<?> hostClass;
// Note: Do not refactor the calls to checkHostClass unless you
// also adjust this constant:
private static int CHC_CALLERS = 3;
public AnonymousClassLoader() {
this.hostClass = checkHostClass(null);
}
public AnonymousClassLoader(Class<?> hostClass) {
this.hostClass = checkHostClass(hostClass);
// Privileged constructor.
private AnonymousClassLoader(Class<?> hostClass) {
this.hostClass = hostClass;
}
private static Class<?> getTopLevelClass(Class<?> clazz) {
for(Class<?> outer = clazz.getDeclaringClass(); outer != null;
outer = outer.getDeclaringClass()) {
clazz = outer;
}
return clazz;
}
private static Class<?> checkHostClass(Class<?> hostClass) {
// called only from the constructor
// does a context-sensitive check on caller class
// CC[0..3] = {Reflection, this.checkHostClass, this.<init>, caller}
Class<?> caller = sun.reflect.Reflection.getCallerClass(CHC_CALLERS);
if (caller == null) {
// called from the JVM directly
if (hostClass == null)
return AnonymousClassLoader.class; // anything central will do
return hostClass;
}
if (hostClass == null)
hostClass = caller; // default value is caller itself
// anonymous class will access hostClass on behalf of caller
Class<?> callee = hostClass;
if (caller == callee)
// caller can always nominate itself to grant caller's own access rights
return hostClass;
// normalize caller and callee to their top-level classes:
caller = getTopLevelClass(caller);
callee = getTopLevelClass(callee);
if (caller == callee)
return caller;
ClassLoader callerCL = caller.getClassLoader();
if (callerCL == null) {
// caller is trusted code, so accept the proposed hostClass
return hostClass;
}
// %%% should do something with doPrivileged, because trusted
// code should have a way to execute on behalf of
// partially-trusted clients
// Does the caller have the right to access the private
// members of the callee? If not, raise an error.
final int ACC_PRIVATE = 2;
try {
sun.reflect.Reflection.ensureMemberAccess(caller, callee, null, ACC_PRIVATE);
} catch (IllegalAccessException ee) {
throw new IllegalArgumentException(ee);
}
return hostClass;
public static AnonymousClassLoader make(sun.misc.Unsafe unsafe, Class<?> hostClass) {
if (unsafe == null) throw new NullPointerException();
return new AnonymousClassLoader(hostClass);
}
public Class<?> loadClass(byte[] classFile) {
......@@ -249,7 +189,7 @@ public class AnonymousClassLoader {
private static int fakeNameCounter = 99999;
// ignore two warnings on this line:
static sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
private static sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
// preceding line requires that this class be on the boot class path
static private final Method defineAnonymousClass;
......
/*
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2012, 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
......@@ -475,7 +475,7 @@ public class ValueConversions {
.findStatic(THIS_CLASS, "fillNewTypedArray",
MethodType.methodType(Object[].class, Object[].class, Integer.class, Object[].class));
} catch (NoSuchMethodException | IllegalAccessException ex) {
throw new InternalError("uncaught exception", ex);
throw newInternalError("uncaught exception", ex);
}
}
......@@ -489,7 +489,7 @@ public class ValueConversions {
COPY_AS_PRIMITIVE_ARRAY = IMPL_LOOKUP.findStatic(THIS_CLASS, "copyAsPrimitiveArray", MethodType.methodType(Object.class, Wrapper.class, Object[].class));
MAKE_LIST = IMPL_LOOKUP.findStatic(THIS_CLASS, "makeList", MethodType.methodType(List.class, Object[].class));
} catch (ReflectiveOperationException ex) {
throw new InternalError("uncaught exception", ex);
throw newInternalError("uncaught exception", ex);
}
}
}
......@@ -522,14 +522,19 @@ public class ValueConversions {
static {
MethodHandle mh = null;
try {
java.lang.reflect.Method m = MethodHandles.class
final java.lang.reflect.Method m = MethodHandles.class
.getDeclaredMethod("collectArguments",
MethodHandle.class, int.class, MethodHandle.class);
m.setAccessible(true);
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
m.setAccessible(true);
return null;
}
});
mh = IMPL_LOOKUP.unreflect(m);
} catch (ReflectiveOperationException | SecurityException ex) {
throw new InternalError(ex);
} catch (ReflectiveOperationException ex) {
throw newInternalError(ex);
}
COLLECT_ARGUMENTS = mh;
}
......@@ -1209,4 +1214,12 @@ public class ValueConversions {
private static MethodHandle buildVarargsList(int nargs) {
return MethodHandles.filterReturnValue(varargsArray(nargs), LazyStatics.MAKE_LIST);
}
// handy shared exception makers (they simplify the common case code)
private static InternalError newInternalError(String message, Throwable cause) {
return new InternalError(message, cause);
}
private static InternalError newInternalError(Throwable cause) {
return new InternalError(cause);
}
}
......@@ -284,12 +284,20 @@ public final class Service<S> {
}
String cn = nextName;
nextName = null;
Class<?> c = null;
try {
return service.cast(Class.forName(cn, true, loader).newInstance());
c = Class.forName(cn, false, loader);
} catch (ClassNotFoundException x) {
fail(service,
"Provider " + cn + " not found");
} catch (Exception x) {
}
if (!service.isAssignableFrom(c)) {
fail(service,
"Provider " + cn + " not a subtype");
}
try {
return service.cast(c.newInstance());
} catch (Throwable x) {
fail(service,
"Provider " + cn + " could not be instantiated: " + x,
x);
......
/*
* Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.net.www.protocol.gopher;
import java.io.*;
import java.util.*;
import java.net.*;
import sun.net.www.*;
import sun.net.NetworkClient;
import java.net.URL;
import java.net.URLStreamHandler;
import sun.security.action.GetBooleanAction;
/** Class to maintain the state of a gopher fetch and handle the protocol */
public class GopherClient extends NetworkClient implements Runnable {
/* The following three data members are left in for binary
* backwards-compatibility. Unfortunately, HotJava sets them directly
* when it wants to change the settings. The new design has us not
* cache these, so this is unnecessary, but eliminating the data members
* would break HJB 1.1 under JDK 1.2.
*
* These data members are not used, and their values are meaningless.
* REMIND: Take them out for JDK 2.0!
*/
/**
* @deprecated
*/
@Deprecated
public static boolean useGopherProxy;
/**
* @deprecated
*/
@Deprecated
public static String gopherProxyHost;
/**
* @deprecated
*/
@Deprecated
public static int gopherProxyPort;
static {
useGopherProxy = java.security.AccessController.doPrivileged(
new sun.security.action.GetBooleanAction("gopherProxySet"))
.booleanValue();
gopherProxyHost = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("gopherProxyHost"));
gopherProxyPort = java.security.AccessController.doPrivileged(
new sun.security.action.GetIntegerAction("gopherProxyPort", 80))
.intValue();
}
PipedOutputStream os;
URL u;
int gtype;
String gkey;
sun.net.www.URLConnection connection;
GopherClient(sun.net.www.URLConnection connection) {
this.connection = connection;
}
/**
* @return true if gopher connections should go through a proxy, according
* to system properties.
*/
public static boolean getUseGopherProxy() {
return java.security.AccessController.doPrivileged(
new GetBooleanAction("gopherProxySet")).booleanValue();
}
/**
* @return the proxy host to use, or null if nothing is set.
*/
public static String getGopherProxyHost() {
String host = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("gopherProxyHost"));
if ("".equals(host)) {
host = null;
}
return host;
}
/**
* @return the proxy port to use. Will default reasonably.
*/
public static int getGopherProxyPort() {
return java.security.AccessController.doPrivileged(
new sun.security.action.GetIntegerAction("gopherProxyPort", 80))
.intValue();
}
/** Given a url, setup to fetch the gopher document it refers to */
InputStream openStream(URL u) throws IOException {
this.u = u;
this.os = os;
int i = 0;
String s = u.getFile();
int limit = s.length();
int c = '1';
while (i < limit && (c = s.charAt(i)) == '/')
i++;
gtype = c == '/' ? '1' : c;
if (i < limit)
i++;
gkey = s.substring(i);
openServer(u.getHost(), u.getPort() <= 0 ? 70 : u.getPort());
MessageHeader msgh = new MessageHeader();
switch (gtype) {
case '0':
case '7':
msgh.add("content-type", "text/plain");
break;
case '1':
msgh.add("content-type", "text/html");
break;
case 'g':
case 'I':
msgh.add("content-type", "image/gif");
break;
default:
msgh.add("content-type", "content/unknown");
break;
}
if (gtype != '7') {
serverOutput.print(decodePercent(gkey) + "\r\n");
serverOutput.flush();
} else if ((i = gkey.indexOf('?')) >= 0) {
serverOutput.print(decodePercent(gkey.substring(0, i) + "\t" +
gkey.substring(i + 1) + "\r\n"));
serverOutput.flush();
msgh.add("content-type", "text/html");
} else {
msgh.add("content-type", "text/html");
}
connection.setProperties(msgh);
if (msgh.findValue("content-type") == "text/html") {
os = new PipedOutputStream();
PipedInputStream ret = new PipedInputStream();
ret.connect(os);
new Thread(this).start();
return ret;
}
return new GopherInputStream(this, serverInput);
}
/** Translate all the instances of %NN into the character they represent */
private String decodePercent(String s) {
if (s == null || s.indexOf('%') < 0)
return s;
int limit = s.length();
char d[] = new char[limit];
int dp = 0;
for (int sp = 0; sp < limit; sp++) {
int c = s.charAt(sp);
if (c == '%' && sp + 2 < limit) {
int s1 = s.charAt(sp + 1);
int s2 = s.charAt(sp + 2);
if ('0' <= s1 && s1 <= '9')
s1 = s1 - '0';
else if ('a' <= s1 && s1 <= 'f')
s1 = s1 - 'a' + 10;
else if ('A' <= s1 && s1 <= 'F')
s1 = s1 - 'A' + 10;
else
s1 = -1;
if ('0' <= s2 && s2 <= '9')
s2 = s2 - '0';
else if ('a' <= s2 && s2 <= 'f')
s2 = s2 - 'a' + 10;
else if ('A' <= s2 && s2 <= 'F')
s2 = s2 - 'A' + 10;
else
s2 = -1;
if (s1 >= 0 && s2 >= 0) {
c = (s1 << 4) | s2;
sp += 2;
}
}
d[dp++] = (char) c;
}
return new String(d, 0, dp);
}
/** Turn special characters into the %NN form */
private String encodePercent(String s) {
if (s == null)
return s;
int limit = s.length();
char d[] = null;
int dp = 0;
for (int sp = 0; sp < limit; sp++) {
int c = s.charAt(sp);
if (c <= ' ' || c == '"' || c == '%') {
if (d == null)
d = s.toCharArray();
if (dp + 3 >= d.length) {
char nd[] = new char[dp + 10];
System.arraycopy(d, 0, nd, 0, dp);
d = nd;
}
d[dp] = '%';
int dig = (c >> 4) & 0xF;
d[dp + 1] = (char) (dig < 10 ? '0' + dig : 'A' - 10 + dig);
dig = c & 0xF;
d[dp + 2] = (char) (dig < 10 ? '0' + dig : 'A' - 10 + dig);
dp += 3;
} else {
if (d != null) {
if (dp >= d.length) {
char nd[] = new char[dp + 10];
System.arraycopy(d, 0, nd, 0, dp);
d = nd;
}
d[dp] = (char) c;
}
dp++;
}
}
return d == null ? s : new String(d, 0, dp);
}
/** This method is run as a seperate thread when an incoming gopher
document requires translation to html */
public void run() {
int qpos = -1;
try {
if (gtype == '7' && (qpos = gkey.indexOf('?')) < 0) {
PrintStream ps = new PrintStream(os, false, encoding);
ps.print("<html><head><title>Searchable Gopher Index</title></head>\n<body><h1>Searchable Gopher Index</h1><isindex>\n</body></html>\n");
} else if (gtype != '1' && gtype != '7') {
byte buf[] = new byte[2048];
try {
int n;
while ((n = serverInput.read(buf)) >= 0)
os.write(buf, 0, n);
} catch(Exception e) {
}
} else {
PrintStream ps = new PrintStream(os, false, encoding);
String title = null;
if (gtype == '7')
title = "Results of searching for \"" + gkey.substring(qpos + 1)
+ "\" on " + u.getHost();
else
title = "Gopher directory " + gkey + " from " + u.getHost();
ps.print("<html><head><title>");
ps.print(title);
ps.print("</title></head>\n<body>\n<H1>");
ps.print(title);
ps.print("</h1><dl compact>\n");
BufferedReader ds = new BufferedReader(new InputStreamReader(serverInput));
String s;
while ((s = ds.readLine()) != null) {
int len = s.length();
while (len > 0 && s.charAt(len - 1) <= ' ')
len--;
if (len <= 0)
continue;
int key = s.charAt(0);
int t1 = s.indexOf('\t');
int t2 = t1 > 0 ? s.indexOf('\t', t1 + 1) : -1;
int t3 = t2 > 0 ? s.indexOf('\t', t2 + 1) : -1;
if (t3 < 0) {
// ps.print("<br><i>"+s+"</i>\n");
continue;
}
String port = t3 + 1 < len ? ":" + s.substring(t3 + 1, len) : "";
String host = t2 + 1 < t3 ? s.substring(t2 + 1, t3) : u.getHost();
ps.print("<dt><a href=\"gopher://" + host + port + "/"
+ s.substring(0, 1) + encodePercent(s.substring(t1 + 1, t2)) + "\">\n");
ps.print("<img align=middle border=0 width=25 height=32 src=");
switch (key) {
default:
ps.print(System.getProperty("java.net.ftp.imagepath.file"));
break;
case '0':
ps.print(System.getProperty("java.net.ftp.imagepath.text"));
break;
case '1':
ps.print(System.getProperty("java.net.ftp.imagepath.directory"));
break;
case 'g':
ps.print(System.getProperty("java.net.ftp.imagepath.gif"));
break;
}
ps.print(".gif align=middle><dd>\n");
ps.print(s.substring(1, t1) + "</a>\n");
}
ps.print("</dl></body>\n");
ps.close();
}
} catch (UnsupportedEncodingException e) {
throw new InternalError(encoding+ " encoding not found", e);
} catch (IOException e) {
} finally {
try {
closeServer();
os.close();
} catch (IOException e2) {
}
}
}
}
/** An input stream that does nothing more than hold on to the NetworkClient
that created it. This is used when only the input stream is needed, and
the network client needs to be closed when the input stream is closed. */
class GopherInputStream extends FilterInputStream {
NetworkClient parent;
GopherInputStream(NetworkClient o, InputStream fd) {
super(fd);
parent = o;
}
public void close() {
try {
parent.closeServer();
super.close();
} catch (IOException e) {
}
}
}
......@@ -405,7 +405,8 @@ public class RegistryImpl extends java.rmi.server.RemoteServer
*/
perms.add(new SocketPermission("*", "connect,accept"));
perms.add(new RuntimePermission("accessClassInPackage.sun.*"));
perms.add(new RuntimePermission("accessClassInPackage.sun.jvmstat.*"));
perms.add(new RuntimePermission("accessClassInPackage.sun.jvm.hotspot.*"));
perms.add(new FilePermission("<<ALL FILES>>", "read"));
......
......@@ -56,12 +56,6 @@ implements java.io.Serializable {
private static final long serialVersionUID = 3581829991155417889L;
/**
* This static object will be seeded by SeedGenerator, and used
* to seed future instances of SecureRandom
*/
private static SecureRandom seeder;
private static final int DIGEST_SIZE = 20;
private transient MessageDigest digest;
private byte[] state;
......@@ -172,6 +166,28 @@ implements java.io.Serializable {
state[0]++;
}
/**
* This static object will be seeded by SeedGenerator, and used
* to seed future instances of SHA1PRNG SecureRandoms.
*
* Bloch, Effective Java Second Edition: Item 71
*/
private static class SeederHolder {
private static final SecureRandom seeder;
static {
/*
* Call to SeedGenerator.generateSeed() to add additional
* seed material (likely from the Native implementation).
*/
seeder = new SecureRandom(SeedGenerator.getSystemEntropy());
byte [] b = new byte[DIGEST_SIZE];
SeedGenerator.generateSeed(b);
seeder.engineSetSeed(b);
}
}
/**
* Generates a user-specified number of random bytes.
*
......@@ -183,13 +199,8 @@ implements java.io.Serializable {
byte[] output = remainder;
if (state == null) {
if (seeder == null) {
seeder = new SecureRandom(SeedGenerator.getSystemEntropy());
seeder.engineSetSeed(engineGenerateSeed(DIGEST_SIZE));
}
byte[] seed = new byte[DIGEST_SIZE];
seeder.engineNextBytes(seed);
SeederHolder.seeder.engineNextBytes(seed);
state = digest.digest(seed);
}
......
......@@ -191,6 +191,7 @@ public class HandshakeInStream extends InputStream {
byte[] getBytes8() throws IOException {
int len = getInt8();
verifyLength(len);
byte b[] = new byte[len];
read(b, 0, len);
......@@ -199,6 +200,7 @@ public class HandshakeInStream extends InputStream {
public byte[] getBytes16() throws IOException {
int len = getInt16();
verifyLength(len);
byte b[] = new byte[len];
read(b, 0, len);
......@@ -207,10 +209,19 @@ public class HandshakeInStream extends InputStream {
byte[] getBytes24() throws IOException {
int len = getInt24();
verifyLength(len);
byte b[] = new byte[len];
read(b, 0, len);
return b;
}
// Is a length greater than available bytes in the record?
private void verifyLength(int len) throws SSLException {
if (len > available()) {
throw new SSLException(
"Not enough data to fill declared vector size");
}
}
}
......@@ -1079,7 +1079,6 @@ abstract class Handshaker {
if (debug != null && Debug.isOn("handshake")) {
System.out.println("RSA master secret generation error:");
e.printStackTrace(System.out);
System.out.println("Generating new random premaster secret");
}
if (requestedVersion != null) {
......@@ -1146,7 +1145,6 @@ abstract class Handshaker {
System.out.println("RSA PreMasterSecret version error: expected"
+ protocolVersion + " or " + requestedVersion + ", decrypted: "
+ premasterVersion);
System.out.println("Generating new random premaster secret");
}
preMasterSecret =
RSAClientKeyExchange.generateDummySecret(requestedVersion);
......
/*
* Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2012, 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
......@@ -36,6 +36,7 @@ import javax.crypto.spec.*;
import javax.net.ssl.*;
import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
import sun.security.util.KeyLength;
/**
* This is the client key exchange message (CLIENT --> SERVER) used with
......@@ -192,26 +193,38 @@ final class RSAClientKeyExchange extends HandshakeMessage {
"unable to get the plaintext of the premaster secret");
}
// We are not always able to get the encoded key of the
// premaster secret. Pass the cheking to master secret
int keySize = KeyLength.getKeySize(secretKey);
if (keySize > 0 && keySize != 384) { // 384 = 48 * 8
if (debug != null && Debug.isOn("handshake")) {
System.out.println(
"incorrect length of premaster secret: " +
(keySize/8));
}
return generateDummySecret(clientHelloVersion);
}
// The key size is exactly 48 bytes or not accessible.
//
// Conservatively, pass the checking to master secret
// calculation.
return secretKey;
} else if (encoded.length == 48) {
// check the version
if (clientHelloVersion.major == encoded[0] &&
clientHelloVersion.minor == encoded[1]) {
return secretKey;
} else if (clientHelloVersion.v <= ProtocolVersion.TLS10.v) {
} else if (clientHelloVersion.v <= ProtocolVersion.TLS10.v &&
currentVersion.major == encoded[0] &&
currentVersion.minor == encoded[1]) {
/*
* we never checked the client_version in server side
* for TLS v1.0 and SSL v3.0. For compatibility, we
* maintain this behavior.
* For compatibility, we maintain the behavior that the
* version in pre_master_secret can be the negotiated
* version for TLS v1.0 and SSL v3.0.
*/
if (currentVersion.major == encoded[0] &&
currentVersion.minor == encoded[1]) {
this.protocolVersion = currentVersion;
return secretKey;
}
this.protocolVersion = currentVersion;
return secretKey;
}
if (debug != null && Debug.isOn("handshake")) {
......@@ -220,22 +233,23 @@ final class RSAClientKeyExchange extends HandshakeMessage {
", while PreMasterSecret.client_version is " +
ProtocolVersion.valueOf(encoded[0], encoded[1]));
}
return generateDummySecret(clientHelloVersion);
} else {
if (debug != null && Debug.isOn("handshake")) {
System.out.println(
"incorrect length of premaster secret: " +
encoded.length);
}
}
}
if (debug != null && Debug.isOn("handshake")) {
if (failoverException != null) {
System.out.println("Error decrypting premaster secret:");
failoverException.printStackTrace(System.out);
return generateDummySecret(clientHelloVersion);
}
}
System.out.println("Generating random secret");
if (debug != null && Debug.isOn("handshake") &&
failoverException != null) {
System.out.println("Error decrypting premaster secret:");
failoverException.printStackTrace(System.out);
}
return generateDummySecret(clientHelloVersion);
......@@ -243,6 +257,10 @@ final class RSAClientKeyExchange extends HandshakeMessage {
// generate a premaster secret with the specified version number
static SecretKey generateDummySecret(ProtocolVersion version) {
if (debug != null && Debug.isOn("handshake")) {
System.out.println("Generating a random fake premaster secret");
}
try {
String s = ((version.v >= ProtocolVersion.TLS12.v) ?
"SunTls12RsaPremasterSecret" : "SunTlsRsaPremasterSecret");
......
......@@ -145,7 +145,7 @@ keystore.type=jks
# passed to checkPackageAccess unless the
# corresponding RuntimePermission ("accessClassInPackage."+package) has
# been granted.
package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,jdk.internal.
package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
#
# List of comma-separated packages that start with or equal this string
......@@ -157,7 +157,7 @@ package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.
# by default, none of the class loaders supplied with the JDK call
# checkPackageDefinition.
#
package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,jdk.internal.
package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
#
# Determines whether this properties file can be appended to
......
......@@ -146,7 +146,7 @@ keystore.type=jks
# passed to checkPackageAccess unless the
# corresponding RuntimePermission ("accessClassInPackage."+package) has
# been granted.
package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,apple.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,jdk.internal.
package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,apple.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
#
# List of comma-separated packages that start with or equal this string
......@@ -158,7 +158,7 @@ package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.
# by default, none of the class loaders supplied with the JDK call
# checkPackageDefinition.
#
package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,apple.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,jdk.internal.
package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,apple.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
#
# Determines whether this properties file can be appended to
......
......@@ -147,7 +147,7 @@ keystore.type=jks
# passed to checkPackageAccess unless the
# corresponding RuntimePermission ("accessClassInPackage."+package) has
# been granted.
package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,jdk.internal.
package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
#
# List of comma-separated packages that start with or equal this string
......@@ -159,7 +159,7 @@ package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.
# by default, none of the class loaders supplied with the JDK call
# checkPackageDefinition.
#
package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,jdk.internal.
package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
#
# Determines whether this properties file can be appended to
......
......@@ -146,7 +146,7 @@ keystore.type=jks
# passed to checkPackageAccess unless the
# corresponding RuntimePermission ("accessClassInPackage."+package) has
# been granted.
package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,jdk.internal.
package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
#
# List of comma-separated packages that start with or equal this string
......@@ -158,7 +158,7 @@ package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.
# by default, none of the class loaders supplied with the JDK call
# checkPackageDefinition.
#
package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,jdk.internal.
package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
#
# Determines whether this properties file can be appended to
......
......@@ -253,6 +253,16 @@ JNIEXPORT jlong JNICALL Java_sun_java2d_cmm_lcms_LCMS_loadProfile
if (sProf.pf == NULL) {
JNU_ThrowIllegalArgumentException(env, "Invalid profile data");
} else {
/* Sanity check: try to save the profile in order
* to force basic validation.
*/
cmsUInt32Number pfSize = 0;
if (!cmsSaveProfileToMem(sProf.pf, NULL, &pfSize) ||
pfSize < sizeof(cmsICCHeader))
{
JNU_ThrowIllegalArgumentException(env, "Invalid profile data");
}
}
return sProf.j;
......
......@@ -379,6 +379,25 @@ public class XKeysym {
keysym2UCSHash.put( (long)0xFFB8, (char)0x0038); // XK_KP_8 --> DIGIT EIGHT
keysym2UCSHash.put( (long)0xFFB9, (char)0x0039); // XK_KP_9 --> DIGIT NINE
keysym2UCSHash.put( (long)0xFE20, (char)0x0009); // XK_ISO_Left_Tab --> <control>
keysym2UCSHash.put( (long)0xFE50, (char)0x02CB); // XK_dead_grave --> MODIFIER LETTER GRAVE ACCENT
keysym2UCSHash.put( (long)0xFE51, (char)0x02CA); // XK_dead_acute --> MODIFIER LETTER ACUTE ACCENT
keysym2UCSHash.put( (long)0xFE52, (char)0x02C6); // XK_dead_circumflex --> MODIFIER LETTER CIRCUMFLEX ACCENT
keysym2UCSHash.put( (long)0xFE53, (char)0x02DC); // XK_dead_tilde --> SMALL TILDE
keysym2UCSHash.put( (long)0xFE54, (char)0x02C9); // XK_dead_macron --> MODIFIER LETTER MACRON
keysym2UCSHash.put( (long)0xFE55, (char)0x02D8); // XK_dead_breve --> BREVE
keysym2UCSHash.put( (long)0xFE56, (char)0x02D9); // XK_dead_abovedot --> DOT ABOVE
keysym2UCSHash.put( (long)0xFE57, (char)0x00A8); // XK_dead_diaeresis --> DIAERESIS
keysym2UCSHash.put( (long)0xFE58, (char)0x02DA); // XK_dead_abovering --> RING ABOVE
keysym2UCSHash.put( (long)0xFE59, (char)0x02DD); // XK_dead_doubleacute --> DOUBLE ACUTE ACCENT
keysym2UCSHash.put( (long)0xFE5A, (char)0x02C7); // XK_dead_caron --> CARON
keysym2UCSHash.put( (long)0xFE5B, (char)0x00B8); // XK_dead_cedilla --> CEDILLA
keysym2UCSHash.put( (long)0xFE5C, (char)0x02DB); // XK_dead_ogonek --> OGONEK
keysym2UCSHash.put( (long)0xFE5D, (char)0x0269); // XK_dead_iota --> LATIN SMALL LETTER IOTA
keysym2UCSHash.put( (long)0xFE5E, (char)0x3099); // XK_dead_voiced_sound --> COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
keysym2UCSHash.put( (long)0xFE5F, (char)0x309A); // XK_dead_semivoiced_sound --> COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
keysym2UCSHash.put( (long)0xFE60, (char)0x0323); // XK_dead_belowdot --> COMBINING DOT BELOW
keysym2UCSHash.put( (long)0xFE61, (char)0x0321); // XK_dead_hook --> COMBINING PALATALIZED HOOK BELOW
keysym2UCSHash.put( (long)0xFE62, (char)0x031B); // XK_dead_horn --> COMBINING HORN
keysym2UCSHash.put( (long)0x1a1, (char)0x0104); // XK_Aogonek --> LATIN CAPITAL LETTER A WITH OGONEK
keysym2UCSHash.put( (long)0x1a2, (char)0x02d8); // XK_breve --> BREVE
keysym2UCSHash.put( (long)0x1a3, (char)0x0141); // XK_Lstroke --> LATIN CAPITAL LETTER L WITH STROKE
......
......@@ -1115,7 +1115,10 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer {
// (1) either XIM could not handle it or
// (2) it was Latin 1:1 mapping.
//
XKeysym.Keysym2JavaKeycode jkc = XKeysym.getJavaKeycode(ev);
// Preserve modifiers to get Java key code for dead keys
boolean isDeadKey = isDeadKey(keysym[0]);
XKeysym.Keysym2JavaKeycode jkc = isDeadKey ? XKeysym.getJavaKeycode(keysym[0])
: XKeysym.getJavaKeycode(ev);
if( jkc == null ) {
jkc = new XKeysym.Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_UNDEFINED, java.awt.event.KeyEvent.KEY_LOCATION_UNKNOWN);
}
......@@ -1141,7 +1144,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer {
jkc.getJavaKeycode();
postKeyEvent( java.awt.event.KeyEvent.KEY_PRESSED,
ev.get_time(),
jkeyToReturn,
isDeadKey ? jkeyExtended : jkeyToReturn,
(unicodeKey == 0 ? java.awt.event.KeyEvent.CHAR_UNDEFINED : unicodeKey),
jkc.getKeyLocation(),
ev.get_state(),ev.getPData(), XKeyEvent.getSize(), (long)(ev.get_keycode()),
......@@ -1149,7 +1152,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer {
jkeyExtended);
if( unicodeKey > 0 ) {
if (unicodeKey > 0 && !isDeadKey) {
keyEventLog.fine("fire _TYPED on "+unicodeKey);
postKeyEvent( java.awt.event.KeyEvent.KEY_TYPED,
ev.get_time(),
......@@ -1176,9 +1179,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer {
}
// un-private it if you need to call it from elsewhere
private void handleKeyRelease(XKeyEvent ev) {
long keysym[] = new long[2];
int unicodeKey = 0;
keysym[0] = XConstants.NoSymbol;
if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
logIncomingKeyEvent( ev );
......@@ -1187,7 +1188,11 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer {
// and Java KeyEvent keycode should be calculated.
// For release we should post released event.
//
XKeysym.Keysym2JavaKeycode jkc = XKeysym.getJavaKeycode(ev);
// Preserve modifiers to get Java key code for dead keys
long keysym = xkeycodeToKeysym(ev);
boolean isDeadKey = isDeadKey(keysym);
XKeysym.Keysym2JavaKeycode jkc = isDeadKey ? XKeysym.getJavaKeycode(keysym)
: XKeysym.getJavaKeycode(ev);
if( jkc == null ) {
jkc = new XKeysym.Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_UNDEFINED, java.awt.event.KeyEvent.KEY_LOCATION_UNKNOWN);
}
......@@ -1219,7 +1224,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer {
jkc.getJavaKeycode();
postKeyEvent( java.awt.event.KeyEvent.KEY_RELEASED,
ev.get_time(),
jkeyToReturn,
isDeadKey ? jkeyExtended : jkeyToReturn,
(unicodeKey == 0 ? java.awt.event.KeyEvent.CHAR_UNDEFINED : unicodeKey),
jkc.getKeyLocation(),
ev.get_state(),ev.getPData(), XKeyEvent.getSize(), (long)(ev.get_keycode()),
......@@ -1229,6 +1234,11 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer {
}
private boolean isDeadKey(long keysym){
return XKeySymConstants.XK_dead_grave <= keysym && keysym <= XKeySymConstants.XK_dead_semivoiced_sound;
}
/*
* XmNiconic and Map/UnmapNotify (that XmNiconic relies on) are
* unreliable, since mapping changes can happen for a virtual desktop
......
......@@ -695,25 +695,25 @@ SOFTWARE.
0x0000 #define XK_ISO_Center_Object 0xFE33
0x0000 #define XK_ISO_Enter 0xFE34
0x0000 #define XK_dead_grave 0xFE50
0x0000 #define XK_dead_acute 0xFE51
0x0000 #define XK_dead_circumflex 0xFE52
0x0000 #define XK_dead_tilde 0xFE53
0x0000 #define XK_dead_macron 0xFE54
0x0000 #define XK_dead_breve 0xFE55
0x0000 #define XK_dead_abovedot 0xFE56
0x0000 #define XK_dead_diaeresis 0xFE57
0x0000 #define XK_dead_abovering 0xFE58
0x0000 #define XK_dead_doubleacute 0xFE59
0x0000 #define XK_dead_caron 0xFE5A
0x0000 #define XK_dead_cedilla 0xFE5B
0x0000 #define XK_dead_ogonek 0xFE5C
0x0000 #define XK_dead_iota 0xFE5D
0x0000 #define XK_dead_voiced_sound 0xFE5E
0x0000 #define XK_dead_semivoiced_sound 0xFE5F
0x0000 #define XK_dead_belowdot 0xFE60
0x0000 #define XK_dead_hook 0xFE61
0x0000 #define XK_dead_horn 0xFE62
0x02CB #define XK_dead_grave 0xFE50
0x02CA #define XK_dead_acute 0xFE51
0x02C6 #define XK_dead_circumflex 0xFE52
0x02DC #define XK_dead_tilde 0xFE53
0x02C9 #define XK_dead_macron 0xFE54
0x02D8 #define XK_dead_breve 0xFE55
0x02D9 #define XK_dead_abovedot 0xFE56
0x00A8 #define XK_dead_diaeresis 0xFE57
0x02DA #define XK_dead_abovering 0xFE58
0x02DD #define XK_dead_doubleacute 0xFE59
0x02C7 #define XK_dead_caron 0xFE5A
0x00B8 #define XK_dead_cedilla 0xFE5B
0x02DB #define XK_dead_ogonek 0xFE5C
0x0269 #define XK_dead_iota 0xFE5D
0x3099 #define XK_dead_voiced_sound 0xFE5E
0x309A #define XK_dead_semivoiced_sound 0xFE5F
0x0323 #define XK_dead_belowdot 0xFE60
0x0321 #define XK_dead_hook 0xFE61
0x031B #define XK_dead_horn 0xFE62
0x0000 #define XK_First_Virtual_Screen 0xFED0
0x0000 #define XK_Prev_Virtual_Screen 0xFED1
......@@ -2466,6 +2466,7 @@ tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Alt_
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Meta_L), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_META, java.awt.event.KeyEvent.KEY_LOCATION_LEFT));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Meta_R), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_META, java.awt.event.KeyEvent.KEY_LOCATION_RIGHT));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Caps_Lock), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_CAPS_LOCK, java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Shift_Lock), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_CAPS_LOCK, java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava
tojava /* Misc Functions */
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Print), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_PRINTSCREEN, java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
......@@ -2640,6 +2641,21 @@ tojava /* Type 5c Japanese keyboard: henkan */
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Kanji), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_CONVERT, java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava /* Type 5c Japanese keyboard: nihongo */
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Henkan_Mode), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_INPUT_METHOD_ON_OFF, java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Eisu_Shift ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_ALPHANUMERIC , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Eisu_toggle ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_ALPHANUMERIC , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Zenkaku ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_FULL_WIDTH , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Hankaku ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_HALF_WIDTH , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Hiragana ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_HIRAGANA , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Katakana ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_KATAKANA , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Romaji ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_JAPANESE_ROMAN , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Kana_Shift ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_KANA , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Kana_Lock ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_KANA_LOCK , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Muhenkan ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_NONCONVERT , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Zen_Koho ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_ALL_CANDIDATES , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Kanji_Bangou ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_CODE_INPUT , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava keysym2JavaKeycodeHash.put( Long.valueOf(XKeySymConstants.XK_Mae_Koho ), new Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_PREVIOUS_CANDIDATE , java.awt.event.KeyEvent.KEY_LOCATION_STANDARD));
tojava
tojava
tojava /* VK_KANA_LOCK is handled separately because it generates the
tojava * same keysym as ALT_GRAPH in spite of its different behavior.
tojava */
......
/*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2012, 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
......@@ -753,7 +753,7 @@ awt_init_Display(JNIEnv *env, jobject this)
sizeof(errmsg),
"Can't connect to X11 window server using '%s' as the value of the DISPLAY variable.",
(getenv("DISPLAY") == NULL) ? ":0.0" : getenv("DISPLAY"));
JNU_ThrowInternalError(env, errmsg);
JNU_ThrowByName(env, "java/awt/AWTError", errmsg);
return NULL;
}
......
......@@ -1099,7 +1099,7 @@ final class Win32ShellFolder2 extends ShellFolder {
? SwingConstants.CENTER
: SwingConstants.LEADING);
column.setComparator(new ColumnComparator(getIShellFolder(), i));
column.setComparator(new ColumnComparator(Win32ShellFolder2.this, i));
notNullColumns.add(column);
}
......@@ -1135,7 +1135,7 @@ final class Win32ShellFolder2 extends ShellFolder {
// synchronize the whole code of the sort method once
invoke(new Callable<Void>() {
public Void call() {
Collections.sort(files, new ColumnComparator(getIShellFolder(), 0));
Collections.sort(files, new ColumnComparator(Win32ShellFolder2.this, 0));
return null;
}
......@@ -1143,12 +1143,12 @@ final class Win32ShellFolder2 extends ShellFolder {
}
private static class ColumnComparator implements Comparator<File> {
private final long parentIShellFolder;
private final Win32ShellFolder2 shellFolder;
private final int columnIdx;
public ColumnComparator(long parentIShellFolder, int columnIdx) {
this.parentIShellFolder = parentIShellFolder;
public ColumnComparator(Win32ShellFolder2 shellFolder, int columnIdx) {
this.shellFolder = shellFolder;
this.columnIdx = columnIdx;
}
......@@ -1159,7 +1159,7 @@ final class Win32ShellFolder2 extends ShellFolder {
if (o instanceof Win32ShellFolder2
&& o1 instanceof Win32ShellFolder2) {
// delegates comparison to native method
return compareIDsByColumn(parentIShellFolder,
return compareIDsByColumn(shellFolder.getIShellFolder(),
((Win32ShellFolder2) o).getRelativePIDL(),
((Win32ShellFolder2) o1).getRelativePIDL(),
columnIdx);
......
......@@ -1559,21 +1559,8 @@ void AwtWindow::SendWindowEvent(jint id, HWND opposite,
BOOL AwtWindow::AwtSetActiveWindow(BOOL isMouseEventCause, UINT hittest)
{
// Fix for 6458497.
// Retreat if current foreground window is out of both our and embedder process.
// The exception is when activation is requested due to a mouse event.
if (!isMouseEventCause) {
HWND fgWindow = ::GetForegroundWindow();
if (NULL != fgWindow) {
DWORD fgProcessID;
::GetWindowThreadProcessId(fgWindow, &fgProcessID);
if (fgProcessID != ::GetCurrentProcessId()
&& !AwtToolkit::GetInstance().IsEmbedderProcessId(fgProcessID))
{
return FALSE;
}
}
}
// We used to reject non mouse window activation if our app wasn't active.
// This code since has been removed as the fix for 7185280
HWND proxyContainerHWnd = GetProxyToplevelContainer();
HWND proxyHWnd = GetProxyFocusOwner();
......
......@@ -143,6 +143,11 @@ java/lang/management/MemoryMXBean/CollectionUsageThresholdSerialGC.sh generic-al
java/lang/management/MemoryMXBean/MemoryTest.java generic-all
java/lang/management/MemoryMXBean/MemoryTestAllGC.sh generic-all
# Exclude until hotspot/jdk repos are sync'd w.r.t. JAVA_MAX_SUPPORTED_VERSION
# Needed when hotspot fix 7054345 is present. Remove when the JDK source is
# updated accordingly.
java/lang/System/Versions.java generic-all
############################################################################
# jdk_management
......
......@@ -25,7 +25,7 @@
* @test
* @bug 7024749
* @summary JDK7 b131---a crash in: Java_sun_awt_windows_ThemeReader_isGetThemeTransitionDurationDefined+0x75
* @library ../../../regtesthelpers
* @library ../../regtesthelpers
* @build Util
* @author Oleg Pekhovskiy: area=awt.toplevel
@run main bug7024749
......
/*
* Copyright (c) 2012, 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 6373505
* @summary Tests that the result of Toolkit.getScreenResolution() is
* consistent with GraphicsConfiguration.getNormalizingTransform().
* @author Dmitri.Trembovetski@Sun.COM: area=GraphicsConfiguration
* @run main NormalizingTransformTest
*/
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
public class NormalizingTransformTest {
public static void main(String[] args) {
GraphicsConfiguration gc =
GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration();
AffineTransform normTransform = gc.getNormalizingTransform();
int dpiX = Toolkit.getDefaultToolkit().getScreenResolution();
int normDpiX = (int)(normTransform.getScaleX() * 72.0);
if (dpiX != normDpiX) {
throw new RuntimeException(
"Test FAILED. Toolkit.getScreenResolution()=" + dpiX +
" GraphicsConfiguration.getNormalizingTransform()="+normDpiX);
}
System.out.println("Test PASSED. DPI="+normDpiX);
}
}
/*
* Copyright (c) 1995, 2003, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
* 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
......@@ -23,78 +21,28 @@
* questions.
*/
package sun.net.www.protocol.gopher;
import java.io.*;
import java.util.*;
import sun.net.NetworkClient;
import java.net.URL;
import java.net.URLStreamHandler;
import java.net.Proxy;
import java.net.InetSocketAddress;
import java.net.SocketPermission;
import java.security.Permission;
import sun.net.www.protocol.http.HttpURLConnection;
/**
* A class to handle the gopher protocol.
/*
* @test
* @summary Test that Toolkit.getDefaultToolkit throws AWTError exception if bad DISPLAY variable was set
* @bug 6818083
*
* @run shell/timeout=240 BadDisplayTest.sh
*/
public class Handler extends java.net.URLStreamHandler {
import java.awt.*;
protected int getDefaultPort() {
return 70;
}
public java.net.URLConnection openConnection(URL u)
throws IOException {
return openConnection(u, null);
}
public class BadDisplayTest{
public static void main(String[] args) {
public java.net.URLConnection openConnection(URL u, Proxy p)
throws IOException {
/* if set for proxy usage then go through the http code to get */
/* the url connection. */
if (p == null && GopherClient.getUseGopherProxy()) {
String host = GopherClient.getGopherProxyHost();
if (host != null) {
InetSocketAddress saddr = InetSocketAddress.createUnresolved(host, GopherClient.getGopherProxyPort());
p = new Proxy(Proxy.Type.HTTP, saddr);
}
Throwable th = null;
try {
Toolkit.getDefaultToolkit();
} catch (Throwable x) {
th = x;
}
if (p != null) {
return new HttpURLConnection(u, p);
}
return new GopherURLConnection(u);
}
}
class GopherURLConnection extends sun.net.www.URLConnection {
Permission permission;
GopherURLConnection(URL u) {
super(u);
}
public void connect() throws IOException {
}
public InputStream getInputStream() throws IOException {
return new GopherClient(this).openStream(url);
}
public Permission getPermission() {
if (permission == null) {
int port = url.getPort();
port = port < 0 ? 70 : port;
String host = url.getHost() + ":" + url.getPort();
permission = new SocketPermission(host, "connect");
if ( !(th instanceof AWTError)) {
System.exit(1);
}
return permission;
}
}
# Copyright (c) 2012, 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.
${TESTJAVA}/bin/javac -cp ${TESTSRC} -d . ${TESTSRC}/BadDisplayTest.java
export DISPLAY=
OS=`uname -s`
case "$OS" in
SunOS )
${TESTJAVA}/bin/java BadDisplayTest
;;
Linux )
${TESTJAVA}/bin/java BadDisplayTest
;;
* )
echo "Unsupported System: ${OS}"
exit 0;
;;
esac
exit $?
/*
* Copyright (c) 2012, 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 7196190
* @summary Improve method of handling MethodHandles
*
* @run main/othervm ClassForNameTest
*/
import java.lang.invoke.*;
import java.lang.reflect.Method;
import java.util.Arrays;
public class ClassForNameTest {
final static String NAME = ClassForNameTest.class.getName();
public static void main(String[] args) throws Throwable {
{
final MethodType mt = MethodType.methodType(Class.class, String.class);
final MethodHandle mh = MethodHandles.lookup()
.findStatic(Class.class, "forName", mt);
Class.forName(NAME);
mh.invoke(NAME);
mh.bindTo(NAME).invoke();
mh.invokeWithArguments(Arrays.asList(NAME));
mh.invokeWithArguments(NAME);
Class cls = (Class) mh.invokeExact(NAME);
}
{
final Method fnMethod = Class.class.getMethod("forName", String.class);
final MethodType mt = MethodType.methodType(Object.class, Object.class, Object[].class);
final MethodHandle mh = MethodHandles.lookup()
.findVirtual(Method.class, "invoke", mt)
.bindTo(fnMethod);
fnMethod.invoke(null, NAME);
mh.bindTo(null).bindTo(new Object[]{NAME}).invoke();
mh.invoke(null, new Object[]{NAME});
mh.invokeWithArguments(null, new Object[]{NAME});
mh.invokeWithArguments(Arrays.asList(null, new Object[]{NAME}));
Object obj = mh.invokeExact((Object) null, new Object[]{NAME});
}
{
final Method fnMethod = Class.class.getMethod("forName", String.class);
final MethodType mt = MethodType.methodType(Object.class, Object.class, Object[].class);
final MethodHandle mh = MethodHandles.lookup()
.bind(fnMethod, "invoke", mt);
mh.bindTo(null).bindTo(new Object[]{NAME}).invoke();
mh.invoke(null, new Object[]{NAME});
mh.invokeWithArguments(null, NAME);
mh.invokeWithArguments(Arrays.asList(null, NAME));
Object obj = mh.invokeExact((Object) null, new Object[]{NAME});
}
{
final Method fnMethod = Class.class.getMethod("forName", String.class);
final MethodHandle mh = MethodHandles.lookup().unreflect(fnMethod);
mh.bindTo(NAME).invoke();
mh.invoke(NAME);
mh.invokeWithArguments(NAME);
mh.invokeWithArguments(Arrays.asList(NAME));
Class cls = (Class) mh.invokeExact(NAME);
}
System.out.println("TEST PASSED");
}
}
/*
* Copyright (c) 2012, 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 7196190
* @summary Improve method of handling MethodHandles
*
* @run main/othervm/policy=jtreg.security.policy/secure=java.lang.SecurityManager GetUnsafeTest
*/
import java.lang.invoke.*;
import java.lang.reflect.Method;
import java.util.Arrays;
public class GetUnsafeTest {
final static String NAME = "sun.misc.Unsafe";
private static boolean isTestFailed = false;
private static void fail() {
isTestFailed = true;
try { throw new Exception(); } catch (Throwable e) {
StackTraceElement frame = e.getStackTrace()[1];
System.out.printf("Failed at %s:%d\n", frame.getFileName(), frame.getLineNumber());
}
}
public static void main(String[] args) throws Throwable {
{
final MethodType mt = MethodType.methodType(Class.class, String.class);
final MethodHandle mh = MethodHandles.lookup()
.findStatic(Class.class, "forName", mt);
try { Class.forName(NAME); fail(); } catch (Throwable e) {}
try { mh.invoke(NAME); fail(); } catch (Throwable e) {}
try { mh.bindTo(NAME).invoke(); fail(); } catch (Throwable e) {}
try { mh.invokeWithArguments(Arrays.asList(NAME)); fail(); } catch (Throwable e) {}
try { mh.invokeWithArguments(NAME); fail(); } catch (Throwable e) {}
try { Class cls = (Class) mh.invokeExact(NAME); fail(); } catch (Throwable e) {}
}
{
final Method fnMethod = Class.class.getMethod("forName", String.class);
final MethodType mt = MethodType.methodType(Object.class, Object.class, Object[].class);
final MethodHandle mh = MethodHandles.lookup()
.findVirtual(Method.class, "invoke", mt)
.bindTo(fnMethod);
try { fnMethod.invoke(null, NAME); fail(); } catch (Throwable e) {}
try { mh.bindTo(null).bindTo(new Object[]{NAME}).invoke(); fail(); } catch (Throwable e) {}
try { mh.invoke(null, new Object[]{NAME}); fail(); } catch (Throwable e) {}
try { mh.invokeWithArguments(null, new Object[]{NAME}); fail(); } catch (Throwable e) {}
try { mh.invokeWithArguments(Arrays.asList(null, new Object[]{NAME})); fail(); } catch (Throwable e) {}
try { Object obj = mh.invokeExact((Object) null, new Object[]{NAME}); fail(); } catch (Throwable e) {}
}
{
final Method fnMethod = Class.class.getMethod("forName", String.class);
final MethodType mt = MethodType.methodType(Object.class, Object.class, Object[].class);
final MethodHandle mh = MethodHandles.lookup().bind(fnMethod, "invoke", mt);
try { mh.bindTo(null).bindTo(new Object[]{NAME}).invoke(); fail(); } catch (Throwable e) {}
try { mh.invoke(null, new Object[]{NAME}); fail(); } catch (Throwable e) {}
try { mh.invokeWithArguments(null, NAME); fail(); } catch (Throwable e) {}
try { mh.invokeWithArguments(Arrays.asList(null, NAME)); fail(); } catch (Throwable e) {}
try { Object obj = mh.invokeExact((Object) null, new Object[]{NAME}); fail(); } catch (Throwable e) {}
}
{
final Method fnMethod = Class.class.getMethod("forName", String.class);
final MethodHandle mh = MethodHandles.lookup().unreflect(fnMethod);
try { mh.bindTo(NAME).invoke(); fail(); } catch (Throwable e) {}
try { mh.invoke(NAME); fail(); } catch (Throwable e) {}
try { mh.invokeWithArguments(NAME); fail(); } catch (Throwable e) {}
try { mh.invokeWithArguments(Arrays.asList(NAME)); fail(); } catch (Throwable e) {}
try { Class cls = (Class) mh.invokeExact(NAME); fail(); } catch (Throwable e) {}
}
if (!isTestFailed) {
System.out.println("TEST PASSED");
} else {
System.out.println("TEST FAILED");
System.exit(1);
}
}
}
/*
* Copyright (c) 2012, 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 7196190
* @summary Improve method of handling MethodHandles
*
* @run main/othervm MHProxyTest
*/
import java.lang.invoke.*;
import java.security.*;
import static java.lang.invoke.MethodHandles.*;
import static java.lang.invoke.MethodType.*;
public class MHProxyTest {
private static final Class<?> C_Unsafe;
private static final MethodHandle MH_getUnsafe;
static {
// Do these before there is a SM installed.
C_Unsafe = sun.misc.Unsafe.class; // EXPECT A WARNING ON THIS LINE
Lookup lookup = lookup();
MethodHandle gumh = null;
try {
gumh = lookup.findStatic(C_Unsafe, "getUnsafe", methodType(C_Unsafe));
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex.toString());
}
MH_getUnsafe = gumh;
// Try some different lookups:
try {
lookup.in(Object.class).findStatic(C_Unsafe, "getUnsafe", methodType(C_Unsafe));
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex.toString());
}
lookup = lookup().in(C_Unsafe);
try {
lookup.in(C_Unsafe).findStatic(C_Unsafe, "getUnsafe", methodType(C_Unsafe));
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex.toString());
}
}
public static void main(String[] args) throws Throwable {
System.setSecurityManager(new SecurityManager());
Lookup lookup = lookup();
testBasic(lookup);
testDoPriv(lookup);
testSetVar();
Lookup l2 = lookup.in(Object.class);
System.out.println("=== "+l2);
testBasic(l2);
testDoPriv(l2);
Lookup l3 = lookup.in(C_Unsafe);
System.out.println("=== "+l3);
testBasic(l3);
testDoPriv(l3);
if (failure != null)
throw failure;
}
private static Throwable failure;
private static void fail(Throwable ex) {
if (failure == null)
failure = ex;
StackTraceElement frame = new Exception().getStackTrace()[1];
System.out.printf("Failed at %s:%d: %s\n", frame.getFileName(), frame.getLineNumber(), ex);
}
private static void ok(Throwable ex) {
StackTraceElement frame = new Exception().getStackTrace()[1];
System.out.printf("OK at %s:%d: %s\n", frame.getFileName(), frame.getLineNumber(), ex);
}
private static void testBasic(Lookup lookup) throws Throwable {
// Verify that we can't get to this guy under the SM:
try {
MethodHandle badmh = lookup.findStatic(C_Unsafe, "getUnsafe", methodType(C_Unsafe));
assert(badmh.type() == methodType(C_Unsafe));
badmh = badmh.asType(badmh.type().generic());
Object u = C_Unsafe.cast(badmh.invokeExact());
assert(C_Unsafe.isInstance(u));
fail(new AssertionError("got mh to getUnsafe!"));
} catch (SecurityException ex) {
ok(ex);
}
try {
Object u = MH_getUnsafe.invokeWithArguments();
assert(C_Unsafe.isInstance(u));
fail(new AssertionError("got the Unsafe object! (MH invoke)"));
} catch (SecurityException ex) {
ok(ex);
}
try {
MethodHandle mh = MH_getUnsafe;
mh = mh.asType(mh.type().generic());
mh = foldArguments(identity(Object.class), mh);
mh = filterReturnValue(mh, identity(Object.class));
Object u = mh.invokeExact();
assert(C_Unsafe.isInstance(u));
fail(new AssertionError("got the Unsafe object! (MH invokeWithArguments)"));
} catch (SecurityException ex) {
ok(ex);
}
}
private static void testDoPriv(Lookup lookup) throws Throwable {
PrivilegedAction privAct = MethodHandleProxies.asInterfaceInstance(PrivilegedAction.class, MH_getUnsafe);
try {
Object u = AccessController.doPrivileged(privAct);
assert(C_Unsafe.isInstance(u));
fail(new AssertionError("got the Unsafe object! (static doPriv)"));
} catch (SecurityException ex) {
ok(ex);
}
MethodHandle MH_doPriv = lookup.findStatic(AccessController.class, "doPrivileged",
methodType(Object.class, PrivilegedAction.class));
MH_doPriv = MH_doPriv.bindTo(privAct);
try {
Object u = MH_doPriv.invoke();
assert(C_Unsafe.isInstance(u));
fail(new AssertionError("got the Unsafe object! (MH + doPriv)"));
} catch (SecurityException ex) {
ok(ex);
}
// try one more layer of indirection:
Runnable rbl = MethodHandleProxies.asInterfaceInstance(Runnable.class, MH_doPriv);
try {
rbl.run();
fail(new AssertionError("got the Unsafe object! (Runnable + MH + doPriv)"));
} catch (SecurityException ex) {
ok(ex);
}
}
private static void testSetVar() throws Throwable {
{
// Test the box pattern:
Object[] box = new Object[1];
MethodHandle MH_getFoo = identity(Object.class).bindTo("foo");
MethodHandle MH_storeToBox = insertArguments(arrayElementSetter(Object[].class), 0, box, 0);
MethodHandle mh = filterReturnValue(MH_getFoo, MH_storeToBox);
mh.invokeExact();
assert(box[0] == "foo");
}
{
Object[] box = new Object[1];
MethodHandle MH_storeToBox = insertArguments(arrayElementSetter(Object[].class), 0, box, 0);
MethodHandle mh = filterReturnValue(MH_getUnsafe.asType(MH_getUnsafe.type().generic()), MH_storeToBox);
try {
mh.invokeExact();
Object u = box[0];
assert(C_Unsafe.isInstance(u));
fail(new AssertionError("got the Unsafe object! (MH + setElement)"));
} catch (SecurityException ex) {
ok(ex);
}
}
}
}
/*
* security policy used by the test process
* must allow file reads so that jtreg itself can run
*/
grant {
// standard test activation permissions
permission java.io.FilePermission "*", "read";
};
......@@ -70,7 +70,7 @@ public class BigArityTest {
MethodHandles.lookup().unreflect(
BigArityTest.class.getDeclaredMethod("hashArguments", Object[].class));
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw new Error(ex);
}
}
static MethodHandle MH_hashArguments(int arity) {
......
......@@ -145,21 +145,21 @@ public class PrivateInvokeTest {
MH_DEBUG_STRING = DIRECT_INVOKER_LOOKUP
.findVirtual(MethodHandle.class, "debugString", methodType(String.class));
} catch (ReflectiveOperationException ex) {
throw new InternalError(ex);
throw new Error(ex);
}
}
private Object internalMemberName(MethodHandle mh) {
try {
return MH_INTERNAL_MEMBER_NAME.invokeExact(mh);
} catch (Throwable ex) {
throw new InternalError(ex);
throw new Error(ex);
}
}
private String debugString(MethodHandle mh) {
try {
return (String) MH_DEBUG_STRING.invokeExact(mh);
} catch (Throwable ex) {
throw new InternalError(ex);
throw new Error(ex);
}
}
private static MethodHandle directInvoker(int refKind, MethodType mtype) {
......
......@@ -322,10 +322,6 @@ public class Test {
test("ftp://ftp.is.co.za/rfc/rfc1808.txt")
.s("ftp").h("ftp.is.co.za").p("/rfc/rfc1808.txt").z();
test("gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles")
.s("gopher").h("spinaltap.micro.umn.edu")
.p("/00/Weather/California/Los%20Angeles").z();
test("http://www.math.uio.no/faq/compression-faq/part1.html")
.s("http").h("www.math.uio.no").p("/faq/compression-faq/part1.html").z();
......
/*
* Copyright (c) 2012, 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 4654927
* @summary Clicking on Greyed Menuitems closes the Menubar Dropdown
* @author Alexander Potochkin
* @library ../../regtesthelpers
* @build Util
* @run main bug4654927
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.InputEvent;
import java.util.concurrent.Callable;
import sun.awt.SunToolkit;
public class bug4654927 {
private static volatile JMenu menu;
private static volatile JMenuItem menuItem;
public static void main(String[] args) throws Exception {
String systemLAF = UIManager.getSystemLookAndFeelClassName();
// the test is not applicable to Motif L&F
if(systemLAF.endsWith("MotifLookAndFeel")){
return;
}
UIManager.setLookAndFeel(systemLAF);
SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
Robot robot = new Robot();
robot.setAutoDelay(10);
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createAndShowUI();
}
});
toolkit.realSync();
// test mouse press
Point point = Util.getCenterPoint(menu);
robot.mouseMove(point.x, point.y);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
toolkit.realSync();
point = Util.getCenterPoint(menuItem);
robot.mouseMove(point.x, point.y);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
toolkit.realSync();
if (!isMenuItemShowing()) {
throw new RuntimeException("Popup is unexpectedly closed");
}
// test mouse drag
point = Util.getCenterPoint(menu);
robot.mouseMove(point.x, point.y);
Point menuLocation = Util.invokeOnEDT(new Callable<Point>() {
@Override
public Point call() throws Exception {
return menu.getLocationOnScreen();
}
});
Point itemLocation = Util.invokeOnEDT(new Callable<Point>() {
@Override
public Point call() throws Exception {
return menuItem.getLocationOnScreen();
}
});
int x0 = menuLocation.x + 10;
int y0 = menuLocation.y + 10;
int x1 = itemLocation.x + 10;
int y1 = itemLocation.y + 10;
// close menu
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
toolkit.realSync();
robot.mousePress(InputEvent.BUTTON1_MASK);
Util.glide(robot, x0, y0, x1, y1);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
toolkit.realSync();
if (!isMenuItemShowing()) {
throw new RuntimeException("Popup is unexpectedly closed");
}
}
private static boolean isMenuItemShowing() throws Exception {
return Util.invokeOnEDT(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return menuItem.isShowing();
}
});
}
private static void createAndShowUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu = new JMenu("Menu");
menu.add(new JMenuItem("menuItem"));
menuItem = new JMenuItem("menuItem");
menuItem.setEnabled(false);
menu.add(menuItem);
menu.add(new JMenuItem("menuItem"));
JMenuBar bar = new JMenuBar();
bar.add(menu);
frame.setJMenuBar(bar);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
......@@ -156,6 +156,36 @@ public class Util {
}
}
/**
* Moves mouse smoothly from (x0, y0) to (x1, y1).
*/
public static void glide(Robot robot, int x0, int y0, int x1, int y1) throws AWTException {
float dmax = (float) Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0));
float dx = (x1 - x0) / dmax;
float dy = (y1 - y0) / dmax;
for (int i = 0; i <= dmax; i += 10) {
robot.mouseMove((int) (x0 + dx * i), (int) (y0 + dy * i));
}
}
/**
* Gets component center point
*
* @return center point of the <code>component</code>
*/
public static Point getCenterPoint(final Component component) throws Exception {
return Util.invokeOnEDT(new Callable<Point>() {
@Override
public Point call() throws Exception {
Point p = component.getLocationOnScreen();
Dimension size = component.getSize();
return new Point(p.x + size.width / 2, p.y + size.height / 2);
}
});
}
/**
* Invokes the <code>task</code> on the EDT thread.
*
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册