diff --git a/.hgtags-top-repo b/.hgtags-top-repo index a6aef895743..3fbd35c6a22 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -263,3 +263,4 @@ cf22a728521f91a4692b433d39d730a0a1b23155 jdk9-b16 65abab59f783fcf02ff8e133431c252f9e5f07d5 jdk9-b18 75a08df650eb3126bab0c4d15241f5886162393c jdk9-b19 ee4fd72b2ec3d92497f37163352f294aa695c6fb jdk9-b20 +9052803f4d01feda28b3d65f2b64dd457d21c7b6 jdk9-b21 diff --git a/common/autoconf/basics.m4 b/common/autoconf/basics.m4 index 649f8ddfc29..00ee498ed82 100644 --- a/common/autoconf/basics.m4 +++ b/common/autoconf/basics.m4 @@ -512,7 +512,7 @@ AC_DEFUN_ONCE([BASIC_SETUP_DEVKIT], ) AC_ARG_WITH(sysroot, [AS_HELP_STRING([--with-sysroot], - [use this directory as sysroot)])], + [use this directory as sysroot])], [SYSROOT=$with_sysroot] ) @@ -531,6 +531,75 @@ AC_DEFUN_ONCE([BASIC_SETUP_DEVKIT], [BASIC_PREPEND_TO_PATH([EXTRA_PATH],$with_extra_path)] ) + if test "x$OPENJDK_BUILD_OS" = "xmacosx"; then + # detect if Xcode is installed by running xcodebuild -version + # if no Xcode installed, xcodebuild exits with 1 + # if Xcode is installed, even if xcode-select is misconfigured, then it exits with 0 + if /usr/bin/xcodebuild -version >/dev/null 2>&1; then + # We need to use xcodebuild in the toolchain dir provided by the user, this will + # fall back on the stub binary in /usr/bin/xcodebuild + AC_PATH_PROG([XCODEBUILD], [xcodebuild], [/usr/bin/xcodebuild], [$TOOLCHAIN_PATH]) + else + # this should result in SYSROOT being empty, unless --with-sysroot is provided + # when only the command line tools are installed there are no SDKs, so headers + # are copied into the system frameworks + XCODEBUILD= + AC_SUBST(XCODEBUILD) + fi + + AC_MSG_CHECKING([for sdk name]) + AC_ARG_WITH([sdk-name], [AS_HELP_STRING([--with-sdk-name], + [use the platform SDK of the given name. @<:@macosx@:>@])], + [SDKNAME=$with_sdk_name] + ) + AC_MSG_RESULT([$SDKNAME]) + + # if toolchain path is specified then don't rely on system headers, they may not compile + HAVE_SYSTEM_FRAMEWORK_HEADERS=0 + test -z "$TOOLCHAIN_PATH" && \ + HAVE_SYSTEM_FRAMEWORK_HEADERS=`test ! -f /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h; echo $?` + + if test -z "$SYSROOT"; then + if test -n "$XCODEBUILD"; then + # if we don't have system headers, use default SDK name (last resort) + if test -z "$SDKNAME" -a $HAVE_SYSTEM_FRAMEWORK_HEADERS -eq 0; then + SDKNAME=${SDKNAME:-macosx} + fi + + if test -n "$SDKNAME"; then + # Call xcodebuild to determine SYSROOT + SYSROOT=`"$XCODEBUILD" -sdk $SDKNAME -version | grep '^Path: ' | sed 's/Path: //'` + fi + else + if test $HAVE_SYSTEM_FRAMEWORK_HEADERS -eq 0; then + AC_MSG_ERROR([No xcodebuild tool and no system framework headers found, use --with-sysroot or --with-sdk-name to provide a path to a valid SDK]) + fi + fi + else + # warn user if --with-sdk-name was also set + if test -n "$with_sdk_name"; then + AC_MSG_WARN([Both SYSROOT and --with-sdk-name are set, only SYSROOT will be used]) + fi + fi + + if test $HAVE_SYSTEM_FRAMEWORK_HEADERS -eq 0 -a -z "$SYSROOT"; then + # If no system framework headers, then SYSROOT must be set, or we won't build + AC_MSG_ERROR([Unable to determine SYSROOT and no headers found in /System/Library/Frameworks. Check Xcode configuration, --with-sysroot or --with-sdk-name arguments.]) + fi + + # Perform a basic sanity test + if test ! -f "$SYSROOT/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h"; then + if test -z "$SYSROOT"; then + AC_MSG_ERROR([Unable to find required framework headers, provide a path to an SDK via --with-sysroot or --with-sdk-name and be sure Xcode is installed properly]) + else + AC_MSG_ERROR([Invalid SDK or SYSROOT path, dependent framework headers not found]) + fi + fi + + # set SDKROOT too, Xcode tools will pick it up + AC_SUBST(SDKROOT,$SYSROOT) + fi + # Prepend the extra path to the global path BASIC_PREPEND_TO_PATH([PATH],$EXTRA_PATH) diff --git a/common/autoconf/flags.m4 b/common/autoconf/flags.m4 index 95fa6521575..40f60a9c85d 100644 --- a/common/autoconf/flags.m4 +++ b/common/autoconf/flags.m4 @@ -131,6 +131,10 @@ AC_DEFUN_ONCE([FLAGS_SETUP_INIT_FLAGS], -L$SYSROOT/lib$OPENJDK_TARGET_CPU_ISADIR \ -L$SYSROOT/usr/ccs/lib$OPENJDK_TARGET_CPU_ISADIR" fi + elif test "x$OPENJDK_TARGET_OS" = xmacosx; then + # Apple only wants -isysroot , but we also need -iframework/System/Library/Frameworks + SYSROOT_CFLAGS="-isysroot \"$SYSROOT\" -iframework\"$SYSROOT/System/Library/Frameworks\"" + SYSROOT_LDFLAGS=$SYSROOT_CFLAGS elif test "x$TOOLCHAIN_TYPE" = xgcc; then SYSROOT_CFLAGS="--sysroot=\"$SYSROOT\"" SYSROOT_LDFLAGS="--sysroot=\"$SYSROOT\"" @@ -143,6 +147,14 @@ AC_DEFUN_ONCE([FLAGS_SETUP_INIT_FLAGS], LEGACY_EXTRA_CXXFLAGS="$LEGACY_EXTRA_CXXFLAGS $SYSROOT_CFLAGS" LEGACY_EXTRA_LDFLAGS="$LEGACY_EXTRA_LDFLAGS $SYSROOT_LDFLAGS" fi + + # These always need to be set, or we can't find the frameworks embedded in JavaVM.framework + # set this here so it doesn't have to be peppered throughout the forest + if test "x$OPENJDK_TARGET_OS" = xmacosx; then + SYSROOT_CFLAGS="$SYSROOT_CFLAGS -F\"$SYSROOT/System/Library/Frameworks/JavaVM.framework/Frameworks\"" + SYSROOT_LDFLAGS="$SYSROOT_LDFLAGS -F\"$SYSROOT/System/Library/Frameworks/JavaVM.framework/Frameworks\"" + fi + AC_SUBST(SYSROOT_CFLAGS) AC_SUBST(SYSROOT_LDFLAGS) ]) @@ -644,23 +656,18 @@ AC_DEFUN_ONCE([FLAGS_SETUP_COMPILER_FLAGS_FOR_JDK], # Additional macosx handling if test "x$OPENJDK_TARGET_OS" = xmacosx; then - if test "x$TOOLCHAIN_TYPE" = xgcc; then - # FIXME: This needs to be exported in spec.gmk due to closed legacy code. - # FIXME: clean this up, and/or move it elsewhere. + # Setting these parameters makes it an error to link to macosx APIs that are + # newer than the given OS version and makes the linked binaries compatible + # even if built on a newer version of the OS. + # The expected format is X.Y.Z + MACOSX_VERSION_MIN=10.7.0 + AC_SUBST(MACOSX_VERSION_MIN) - # Setting these parameters makes it an error to link to macosx APIs that are - # newer than the given OS version and makes the linked binaries compatible - # even if built on a newer version of the OS. - # The expected format is X.Y.Z - MACOSX_VERSION_MIN=10.7.0 - AC_SUBST(MACOSX_VERSION_MIN) - - # The macro takes the version with no dots, ex: 1070 - # Let the flags variables get resolved in make for easier override on make - # command line. - COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DMAC_OS_X_VERSION_MAX_ALLOWED=\$(subst .,,\$(MACOSX_VERSION_MIN)) -mmacosx-version-min=\$(MACOSX_VERSION_MIN)" - LDFLAGS_JDK="$LDFLAGS_JDK -mmacosx-version-min=\$(MACOSX_VERSION_MIN)" - fi + # The macro takes the version with no dots, ex: 1070 + # Let the flags variables get resolved in make for easier override on make + # command line. + COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DMAC_OS_X_VERSION_MAX_ALLOWED=\$(subst .,,\$(MACOSX_VERSION_MIN)) -mmacosx-version-min=\$(MACOSX_VERSION_MIN)" + LDFLAGS_JDK="$LDFLAGS_JDK -mmacosx-version-min=\$(MACOSX_VERSION_MIN)" fi # Setup some hard coded includes diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index 4d95f64e34d..2ec5ac45fb8 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -874,6 +874,8 @@ PKGHANDLER OUTPUT_ROOT CONF_NAME SPEC +SDKROOT +XCODEBUILD BUILD_VARIANT_RELEASE DEBUG_CLASSFILES FASTDEBUG @@ -1040,6 +1042,7 @@ with_sysroot with_tools_dir with_toolchain_path with_extra_path +with_sdk_name with_conf_name with_builddeps_conf with_builddeps_server @@ -1074,7 +1077,6 @@ with_extra_cxxflags with_extra_ldflags enable_debug_symbols enable_zip_debug_info -enable_macosx_runtime_support with_x with_cups with_cups_include @@ -1085,6 +1087,7 @@ enable_freetype_bundling with_alsa with_alsa_include with_alsa_lib +with_libjpeg with_giflib with_lcms with_libpng @@ -1841,9 +1844,6 @@ Optional Features: --disable-debug-symbols disable generation of debug symbols [enabled] --disable-zip-debug-info disable zipping of debug-info files [enabled] - --enable-macosx-runtime-support - Deprecated. Option is kept for backwards - compatibility and is ignored --disable-freetype-bundling disable bundling of the freetype library with the build result [enabled on Windows or when using @@ -1872,12 +1872,13 @@ Optional Packages: optimized (HotSpot build only)) [release] --with-devkit use this devkit for compilers, tools and resources --with-sys-root alias for --with-sysroot for backwards compatability - --with-sysroot use this directory as sysroot) + --with-sysroot use this directory as sysroot --with-tools-dir alias for --with-toolchain-path for backwards compatibility --with-toolchain-path prepend these directories when searching for toolchain binaries (compilers etc) --with-extra-path prepend these directories to the default path + --with-sdk-name use the platform SDK of the given name. [macosx] --with-conf-name use this as the name of the configuration [generated from important configuration options] --with-builddeps-conf use this configuration file for the builddeps @@ -1942,6 +1943,8 @@ Optional Packages: headers under PATH/include) --with-alsa-include specify directory for the alsa include files --with-alsa-lib specify directory for the alsa library + --with-libjpeg use libjpeg from build system or OpenJDK source + (system, bundled) [bundled] --with-giflib use giflib from build system or OpenJDK source (system, bundled) [bundled] --with-lcms use lcms2 from build system or OpenJDK source @@ -4308,7 +4311,7 @@ TOOLCHAIN_DESCRIPTION_xlc="IBM XL C/C++" #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1402614845 +DATE_WHEN_GENERATED=1403557683 ############################################################################### # @@ -13607,7 +13610,7 @@ test -n "$target_alias" && VAR_CPU_BITS=32 VAR_CPU_ENDIAN=big ;; - sparcv9) + sparcv9|sparc64) VAR_CPU=sparcv9 VAR_CPU_ARCH=sparc VAR_CPU_BITS=64 @@ -13738,7 +13741,7 @@ $as_echo "$OPENJDK_BUILD_OS-$OPENJDK_BUILD_CPU" >&6; } VAR_CPU_BITS=32 VAR_CPU_ENDIAN=big ;; - sparcv9) + sparcv9|sparc64) VAR_CPU=sparcv9 VAR_CPU_ARCH=sparc VAR_CPU_BITS=64 @@ -14968,6 +14971,122 @@ if test "${with_extra_path+set}" = set; then : fi + if test "x$OPENJDK_BUILD_OS" = "xmacosx"; then + # detect if Xcode is installed by running xcodebuild -version + # if no Xcode installed, xcodebuild exits with 1 + # if Xcode is installed, even if xcode-select is misconfigured, then it exits with 0 + if /usr/bin/xcodebuild -version >/dev/null 2>&1; then + # We need to use xcodebuild in the toolchain dir provided by the user, this will + # fall back on the stub binary in /usr/bin/xcodebuild + # Extract the first word of "xcodebuild", so it can be a program name with args. +set dummy xcodebuild; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_XCODEBUILD+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $XCODEBUILD in + [\\/]* | ?:[\\/]*) + ac_cv_path_XCODEBUILD="$XCODEBUILD" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $TOOLCHAIN_PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_XCODEBUILD="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + test -z "$ac_cv_path_XCODEBUILD" && ac_cv_path_XCODEBUILD="/usr/bin/xcodebuild" + ;; +esac +fi +XCODEBUILD=$ac_cv_path_XCODEBUILD +if test -n "$XCODEBUILD"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $XCODEBUILD" >&5 +$as_echo "$XCODEBUILD" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + else + # this should result in SYSROOT being empty, unless --with-sysroot is provided + # when only the command line tools are installed there are no SDKs, so headers + # are copied into the system frameworks + XCODEBUILD= + + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sdk name" >&5 +$as_echo_n "checking for sdk name... " >&6; } + +# Check whether --with-sdk-name was given. +if test "${with_sdk_name+set}" = set; then : + withval=$with_sdk_name; SDKNAME=$with_sdk_name + +fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SDKNAME" >&5 +$as_echo "$SDKNAME" >&6; } + + # if toolchain path is specified then don't rely on system headers, they may not compile + HAVE_SYSTEM_FRAMEWORK_HEADERS=0 + test -z "$TOOLCHAIN_PATH" && \ + HAVE_SYSTEM_FRAMEWORK_HEADERS=`test ! -f /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h; echo $?` + + if test -z "$SYSROOT"; then + if test -n "$XCODEBUILD"; then + # if we don't have system headers, use default SDK name (last resort) + if test -z "$SDKNAME" -a $HAVE_SYSTEM_FRAMEWORK_HEADERS -eq 0; then + SDKNAME=${SDKNAME:-macosx} + fi + + if test -n "$SDKNAME"; then + # Call xcodebuild to determine SYSROOT + SYSROOT=`"$XCODEBUILD" -sdk $SDKNAME -version | grep '^Path: ' | sed 's/Path: //'` + fi + else + if test $HAVE_SYSTEM_FRAMEWORK_HEADERS -eq 0; then + as_fn_error $? "No xcodebuild tool and no system framework headers found, use --with-sysroot or --with-sdk-name to provide a path to a valid SDK" "$LINENO" 5 + fi + fi + else + # warn user if --with-sdk-name was also set + if test -n "$with_sdk_name"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Both SYSROOT and --with-sdk-name are set, only SYSROOT will be used" >&5 +$as_echo "$as_me: WARNING: Both SYSROOT and --with-sdk-name are set, only SYSROOT will be used" >&2;} + fi + fi + + if test $HAVE_SYSTEM_FRAMEWORK_HEADERS -eq 0 -a -z "$SYSROOT"; then + # If no system framework headers, then SYSROOT must be set, or we won't build + as_fn_error $? "Unable to determine SYSROOT and no headers found in /System/Library/Frameworks. Check Xcode configuration, --with-sysroot or --with-sdk-name arguments." "$LINENO" 5 + fi + + # Perform a basic sanity test + if test ! -f "$SYSROOT/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h"; then + if test -z "$SYSROOT"; then + as_fn_error $? "Unable to find required framework headers, provide a path to an SDK via --with-sysroot or --with-sdk-name and be sure Xcode is installed properly" "$LINENO" 5 + else + as_fn_error $? "Invalid SDK or SYSROOT path, dependent framework headers not found" "$LINENO" 5 + fi + fi + + # set SDKROOT too, Xcode tools will pick it up + SDKROOT=$SYSROOT + + fi + # Prepend the extra path to the global path if test "x$EXTRA_PATH" != x; then @@ -26596,21 +26715,28 @@ fi VALID_TOOLCHAINS=${!toolchain_var_name} if test "x$OPENJDK_TARGET_OS" = xmacosx; then - # On Mac OS X, default toolchain to clang after Xcode 5 - XCODE_VERSION_OUTPUT=`xcodebuild -version 2>&1 | $HEAD -n 1` - $ECHO "$XCODE_VERSION_OUTPUT" | $GREP "Xcode " > /dev/null - if test $? -ne 0; then - as_fn_error $? "Failed to determine Xcode version." "$LINENO" 5 - fi - XCODE_MAJOR_VERSION=`$ECHO $XCODE_VERSION_OUTPUT | \ - $SED -e 's/^Xcode \([1-9][0-9.]*\)/\1/' | \ - $CUT -f 1 -d .` - { $as_echo "$as_me:${as_lineno-$LINENO}: Xcode major version: $XCODE_MAJOR_VERSION" >&5 + if test -n "$XCODEBUILD"; then + # On Mac OS X, default toolchain to clang after Xcode 5 + XCODE_VERSION_OUTPUT=`"$XCODEBUILD" -version 2>&1 | $HEAD -n 1` + $ECHO "$XCODE_VERSION_OUTPUT" | $GREP "Xcode " > /dev/null + if test $? -ne 0; then + as_fn_error $? "Failed to determine Xcode version." "$LINENO" 5 + fi + XCODE_MAJOR_VERSION=`$ECHO $XCODE_VERSION_OUTPUT | \ + $SED -e 's/^Xcode \([1-9][0-9.]*\)/\1/' | \ + $CUT -f 1 -d .` + { $as_echo "$as_me:${as_lineno-$LINENO}: Xcode major version: $XCODE_MAJOR_VERSION" >&5 $as_echo "$as_me: Xcode major version: $XCODE_MAJOR_VERSION" >&6;} - if test $XCODE_MAJOR_VERSION -ge 5; then - DEFAULT_TOOLCHAIN="clang" + if test $XCODE_MAJOR_VERSION -ge 5; then + DEFAULT_TOOLCHAIN="clang" + else + DEFAULT_TOOLCHAIN="gcc" + fi else - DEFAULT_TOOLCHAIN="gcc" + # If Xcode is not installed, but the command line tools are + # then we can't run xcodebuild. On these systems we should + # default to clang + DEFAULT_TOOLCHAIN="clang" fi else # First toolchain type in the list is the default @@ -41076,6 +41202,10 @@ $as_echo "$tool_specified" >&6; } -L$SYSROOT/lib$OPENJDK_TARGET_CPU_ISADIR \ -L$SYSROOT/usr/ccs/lib$OPENJDK_TARGET_CPU_ISADIR" fi + elif test "x$OPENJDK_TARGET_OS" = xmacosx; then + # Apple only wants -isysroot , but we also need -iframework/System/Library/Frameworks + SYSROOT_CFLAGS="-isysroot \"$SYSROOT\" -iframework\"$SYSROOT/System/Library/Frameworks\"" + SYSROOT_LDFLAGS=$SYSROOT_CFLAGS elif test "x$TOOLCHAIN_TYPE" = xgcc; then SYSROOT_CFLAGS="--sysroot=\"$SYSROOT\"" SYSROOT_LDFLAGS="--sysroot=\"$SYSROOT\"" @@ -41089,6 +41219,14 @@ $as_echo "$tool_specified" >&6; } LEGACY_EXTRA_LDFLAGS="$LEGACY_EXTRA_LDFLAGS $SYSROOT_LDFLAGS" fi + # These always need to be set, or we can't find the frameworks embedded in JavaVM.framework + # set this here so it doesn't have to be peppered throughout the forest + if test "x$OPENJDK_TARGET_OS" = xmacosx; then + SYSROOT_CFLAGS="$SYSROOT_CFLAGS -F\"$SYSROOT/System/Library/Frameworks/JavaVM.framework/Frameworks\"" + SYSROOT_LDFLAGS="$SYSROOT_LDFLAGS -F\"$SYSROOT/System/Library/Frameworks/JavaVM.framework/Frameworks\"" + fi + + @@ -42135,23 +42273,18 @@ fi # Additional macosx handling if test "x$OPENJDK_TARGET_OS" = xmacosx; then - if test "x$TOOLCHAIN_TYPE" = xgcc; then - # FIXME: This needs to be exported in spec.gmk due to closed legacy code. - # FIXME: clean this up, and/or move it elsewhere. - - # Setting these parameters makes it an error to link to macosx APIs that are - # newer than the given OS version and makes the linked binaries compatible - # even if built on a newer version of the OS. - # The expected format is X.Y.Z - MACOSX_VERSION_MIN=10.7.0 + # Setting these parameters makes it an error to link to macosx APIs that are + # newer than the given OS version and makes the linked binaries compatible + # even if built on a newer version of the OS. + # The expected format is X.Y.Z + MACOSX_VERSION_MIN=10.7.0 - # The macro takes the version with no dots, ex: 1070 - # Let the flags variables get resolved in make for easier override on make - # command line. - COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DMAC_OS_X_VERSION_MAX_ALLOWED=\$(subst .,,\$(MACOSX_VERSION_MIN)) -mmacosx-version-min=\$(MACOSX_VERSION_MIN)" - LDFLAGS_JDK="$LDFLAGS_JDK -mmacosx-version-min=\$(MACOSX_VERSION_MIN)" - fi + # The macro takes the version with no dots, ex: 1070 + # Let the flags variables get resolved in make for easier override on make + # command line. + COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DMAC_OS_X_VERSION_MAX_ALLOWED=\$(subst .,,\$(MACOSX_VERSION_MIN)) -mmacosx-version-min=\$(MACOSX_VERSION_MIN)" + LDFLAGS_JDK="$LDFLAGS_JDK -mmacosx-version-min=\$(MACOSX_VERSION_MIN)" fi # Setup some hard coded includes @@ -42654,8 +42787,6 @@ $as_echo_n "checking what is not needed on MacOSX?... " >&6; } ALSA_NOT_NEEDED=yes PULSE_NOT_NEEDED=yes X11_NOT_NEEDED=yes - # If the java runtime framework is disabled, then we need X11. - # This will be adjusted below. { $as_echo "$as_me:${as_lineno-$LINENO}: result: alsa pulse x11" >&5 $as_echo "alsa pulse x11" >&6; } fi @@ -42676,33 +42807,6 @@ $as_echo "alsa" >&6; } X11_NOT_NEEDED=yes fi - ############################################################################### - # - # Check for MacOSX support for OpenJDK. - # - - - # Check whether --enable-macosx-runtime-support was given. -if test "${enable_macosx_runtime_support+set}" = set; then : - enableval=$enable_macosx_runtime_support; -fi - - if test "x$enable_macosx_runtime_support" != x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Option --enable-macosx-runtime-support is deprecated and will be ignored." >&5 -$as_echo "$as_me: WARNING: Option --enable-macosx-runtime-support is deprecated and will be ignored." >&2;} - fi - - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Mac OS X Java Framework" >&5 -$as_echo_n "checking for Mac OS X Java Framework... " >&6; } - if test -f /System/Library/Frameworks/JavaVM.framework/Frameworks/JavaRuntimeSupport.framework/Headers/JavaRuntimeSupport.h; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: /System/Library/Frameworks/JavaVM.framework" >&5 -$as_echo "/System/Library/Frameworks/JavaVM.framework" >&6; } - else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } - fi - ############################################################################### @@ -47573,10 +47677,43 @@ done # Check for the jpeg library # - USE_EXTERNAL_LIBJPEG=true - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ljpeg" >&5 -$as_echo_n "checking for main in -ljpeg... " >&6; } -if ${ac_cv_lib_jpeg_main+:} false; then : + +# Check whether --with-libjpeg was given. +if test "${with_libjpeg+set}" = set; then : + withval=$with_libjpeg; +fi + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for which libjpeg to use" >&5 +$as_echo_n "checking for which libjpeg to use... " >&6; } + + # default is bundled + DEFAULT_LIBJPEG=bundled + + # + # if user didn't specify, use DEFAULT_LIBJPEG + # + if test "x${with_libjpeg}" = "x"; then + with_libjpeg=${DEFAULT_LIBJPEG} + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${with_libjpeg}" >&5 +$as_echo "${with_libjpeg}" >&6; } + + if test "x${with_libjpeg}" = "xbundled"; then + USE_EXTERNAL_LIBJPEG=false + elif test "x${with_libjpeg}" = "xsystem"; then + ac_fn_cxx_check_header_mongrel "$LINENO" "jpeglib.h" "ac_cv_header_jpeglib_h" "$ac_includes_default" +if test "x$ac_cv_header_jpeglib_h" = xyes; then : + +else + as_fn_error $? "--with-libjpeg=system specified, but jpeglib.h not found!" "$LINENO" 5 +fi + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for jpeg_CreateDecompress in -ljpeg" >&5 +$as_echo_n "checking for jpeg_CreateDecompress in -ljpeg... " >&6; } +if ${ac_cv_lib_jpeg_jpeg_CreateDecompress+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -47584,27 +47721,33 @@ LIBS="-ljpeg $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char jpeg_CreateDecompress (); int main () { -return main (); +return jpeg_CreateDecompress (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : - ac_cv_lib_jpeg_main=yes + ac_cv_lib_jpeg_jpeg_CreateDecompress=yes else - ac_cv_lib_jpeg_main=no + ac_cv_lib_jpeg_jpeg_CreateDecompress=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_jpeg_main" >&5 -$as_echo "$ac_cv_lib_jpeg_main" >&6; } -if test "x$ac_cv_lib_jpeg_main" = xyes; then : +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_jpeg_jpeg_CreateDecompress" >&5 +$as_echo "$ac_cv_lib_jpeg_jpeg_CreateDecompress" >&6; } +if test "x$ac_cv_lib_jpeg_jpeg_CreateDecompress" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBJPEG 1 _ACEOF @@ -47612,13 +47755,16 @@ _ACEOF LIBS="-ljpeg $LIBS" else - USE_EXTERNAL_LIBJPEG=false - { $as_echo "$as_me:${as_lineno-$LINENO}: Will use jpeg decoder bundled with the OpenJDK source" >&5 -$as_echo "$as_me: Will use jpeg decoder bundled with the OpenJDK source" >&6;} - + as_fn_error $? "--with-libjpeg=system specified, but no libjpeg found" "$LINENO" 5 fi + USE_EXTERNAL_LIBJPEG=true + else + as_fn_error $? "Invalid use of --with-libjpeg: ${with_libjpeg}, use 'system' or 'bundled'" "$LINENO" 5 + fi + + ############################################################################### # diff --git a/common/autoconf/libraries.m4 b/common/autoconf/libraries.m4 index 6ee3221ad96..3a689ef62ee 100644 --- a/common/autoconf/libraries.m4 +++ b/common/autoconf/libraries.m4 @@ -65,8 +65,6 @@ AC_DEFUN_ONCE([LIB_SETUP_INIT], ALSA_NOT_NEEDED=yes PULSE_NOT_NEEDED=yes X11_NOT_NEEDED=yes - # If the java runtime framework is disabled, then we need X11. - # This will be adjusted below. AC_MSG_RESULT([alsa pulse x11]) fi @@ -83,20 +81,6 @@ AC_DEFUN_ONCE([LIB_SETUP_INIT], if test "x$SUPPORT_HEADFUL" = xno; then X11_NOT_NEEDED=yes fi - - ############################################################################### - # - # Check for MacOSX support for OpenJDK. - # - - BASIC_DEPRECATED_ARG_ENABLE(macosx-runtime-support, macosx_runtime_support) - - AC_MSG_CHECKING([for Mac OS X Java Framework]) - if test -f /System/Library/Frameworks/JavaVM.framework/Frameworks/JavaRuntimeSupport.framework/Headers/JavaRuntimeSupport.h; then - AC_MSG_RESULT([/System/Library/Frameworks/JavaVM.framework]) - else - AC_MSG_RESULT([no]) - fi ]) AC_DEFUN_ONCE([LIB_SETUP_X11], @@ -620,11 +604,36 @@ AC_DEFUN_ONCE([LIB_SETUP_MISC_LIBS], # Check for the jpeg library # - USE_EXTERNAL_LIBJPEG=true - AC_CHECK_LIB(jpeg, main, [], - [ USE_EXTERNAL_LIBJPEG=false - AC_MSG_NOTICE([Will use jpeg decoder bundled with the OpenJDK source]) - ]) + AC_ARG_WITH(libjpeg, [AS_HELP_STRING([--with-libjpeg], + [use libjpeg from build system or OpenJDK source (system, bundled) @<:@bundled@:>@])]) + + AC_MSG_CHECKING([for which libjpeg to use]) + + # default is bundled + DEFAULT_LIBJPEG=bundled + + # + # if user didn't specify, use DEFAULT_LIBJPEG + # + if test "x${with_libjpeg}" = "x"; then + with_libjpeg=${DEFAULT_LIBJPEG} + fi + + AC_MSG_RESULT(${with_libjpeg}) + + if test "x${with_libjpeg}" = "xbundled"; then + USE_EXTERNAL_LIBJPEG=false + elif test "x${with_libjpeg}" = "xsystem"; then + AC_CHECK_HEADER(jpeglib.h, [], + [ AC_MSG_ERROR([--with-libjpeg=system specified, but jpeglib.h not found!])]) + AC_CHECK_LIB(jpeg, jpeg_CreateDecompress, [], + [ AC_MSG_ERROR([--with-libjpeg=system specified, but no libjpeg found])]) + + USE_EXTERNAL_LIBJPEG=true + else + AC_MSG_ERROR([Invalid use of --with-libjpeg: ${with_libjpeg}, use 'system' or 'bundled']) + fi + AC_SUBST(USE_EXTERNAL_LIBJPEG) ############################################################################### diff --git a/common/autoconf/platform.m4 b/common/autoconf/platform.m4 index 1f06f0ce7d5..54838a3e72c 100644 --- a/common/autoconf/platform.m4 +++ b/common/autoconf/platform.m4 @@ -84,7 +84,7 @@ AC_DEFUN([PLATFORM_EXTRACT_VARS_FROM_CPU], VAR_CPU_BITS=32 VAR_CPU_ENDIAN=big ;; - sparcv9) + sparcv9|sparc64) VAR_CPU=sparcv9 VAR_CPU_ARCH=sparc VAR_CPU_BITS=64 diff --git a/common/autoconf/spec.gmk.in b/common/autoconf/spec.gmk.in index 2f6d7bd3746..bc916f636c3 100644 --- a/common/autoconf/spec.gmk.in +++ b/common/autoconf/spec.gmk.in @@ -347,6 +347,9 @@ CPP:=@FIXPATH@ @CPP@ # The linker can be gcc or ld on posix systems, or link.exe on windows systems. LD:=@FIXPATH@ @LD@ +# Xcode SDK path +SDKROOT:=@SDKROOT@ + # The linker on older SuSE distros (e.g. on SLES 10) complains with: # "Invalid version tag `SUNWprivate_1.1'. Only anonymous version tag is allowed in executable." # if feeded with a version script which contains named tags. @@ -544,7 +547,7 @@ SETFILE:=@SETFILE@ XATTR:=@XATTR@ JT_HOME:=@JT_HOME@ JTREGEXE:=@JTREGEXE@ - +XCODEBUILD=@XCODEBUILD@ FIXPATH:=@FIXPATH@ # Where the build output is stored for your convenience. diff --git a/common/autoconf/toolchain.m4 b/common/autoconf/toolchain.m4 index 4686517151b..f380bf446ad 100644 --- a/common/autoconf/toolchain.m4 +++ b/common/autoconf/toolchain.m4 @@ -98,20 +98,27 @@ AC_DEFUN_ONCE([TOOLCHAIN_DETERMINE_TOOLCHAIN_TYPE], VALID_TOOLCHAINS=${!toolchain_var_name} if test "x$OPENJDK_TARGET_OS" = xmacosx; then - # On Mac OS X, default toolchain to clang after Xcode 5 - XCODE_VERSION_OUTPUT=`xcodebuild -version 2>&1 | $HEAD -n 1` - $ECHO "$XCODE_VERSION_OUTPUT" | $GREP "Xcode " > /dev/null - if test $? -ne 0; then - AC_MSG_ERROR([Failed to determine Xcode version.]) - fi - XCODE_MAJOR_VERSION=`$ECHO $XCODE_VERSION_OUTPUT | \ - $SED -e 's/^Xcode \(@<:@1-9@:>@@<:@0-9.@:>@*\)/\1/' | \ - $CUT -f 1 -d .` - AC_MSG_NOTICE([Xcode major version: $XCODE_MAJOR_VERSION]) - if test $XCODE_MAJOR_VERSION -ge 5; then - DEFAULT_TOOLCHAIN="clang" + if test -n "$XCODEBUILD"; then + # On Mac OS X, default toolchain to clang after Xcode 5 + XCODE_VERSION_OUTPUT=`"$XCODEBUILD" -version 2>&1 | $HEAD -n 1` + $ECHO "$XCODE_VERSION_OUTPUT" | $GREP "Xcode " > /dev/null + if test $? -ne 0; then + AC_MSG_ERROR([Failed to determine Xcode version.]) + fi + XCODE_MAJOR_VERSION=`$ECHO $XCODE_VERSION_OUTPUT | \ + $SED -e 's/^Xcode \(@<:@1-9@:>@@<:@0-9.@:>@*\)/\1/' | \ + $CUT -f 1 -d .` + AC_MSG_NOTICE([Xcode major version: $XCODE_MAJOR_VERSION]) + if test $XCODE_MAJOR_VERSION -ge 5; then + DEFAULT_TOOLCHAIN="clang" + else + DEFAULT_TOOLCHAIN="gcc" + fi else - DEFAULT_TOOLCHAIN="gcc" + # If Xcode is not installed, but the command line tools are + # then we can't run xcodebuild. On these systems we should + # default to clang + DEFAULT_TOOLCHAIN="clang" fi else # First toolchain type in the list is the default diff --git a/corba/.hgtags b/corba/.hgtags index f9ed22e0c47..cdc0dbb61f7 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -263,3 +263,4 @@ e54022d0dd92106fff7f7fe670010cd7e6517ee3 jdk9-b15 77565aaaa2bb814e94817e92d680168052a25395 jdk9-b18 eecc1b6adc7e193d00a0641eb0963add5a4c06e8 jdk9-b19 87f36eecb1665012d01c5cf102494e591c943ea6 jdk9-b20 +3615a4e7f0542ca7552ad6454b742c73ee211d8e jdk9-b21 diff --git a/corba/src/share/classes/com/sun/corba/se/impl/io/OutputStreamHook.java b/corba/src/share/classes/com/sun/corba/se/impl/io/OutputStreamHook.java index 1748397d065..6908cad9a83 100644 --- a/corba/src/share/classes/com/sun/corba/se/impl/io/OutputStreamHook.java +++ b/corba/src/share/classes/com/sun/corba/se/impl/io/OutputStreamHook.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,7 +35,8 @@ import java.io.IOException; import java.io.OutputStream; import java.io.ObjectOutputStream; import java.io.ObjectOutput; -import java.util.Hashtable; +import java.util.Map; +import java.util.HashMap; import org.omg.CORBA.INTERNAL; @@ -49,7 +50,7 @@ public abstract class OutputStreamHook extends ObjectOutputStream */ private class HookPutFields extends ObjectOutputStream.PutField { - private Hashtable fields = new Hashtable(); + private Map fields = new HashMap<>(); /** * Put the value of the named boolean field into the persistent field. @@ -140,7 +141,6 @@ public abstract class OutputStreamHook extends ObjectOutputStream public OutputStreamHook() throws java.io.IOException { super(); - } public void defaultWriteObject() throws IOException { diff --git a/get_source.sh b/get_source.sh index f83a3766c12..21bafe05609 100644 --- a/get_source.sh +++ b/get_source.sh @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -25,9 +25,48 @@ # questions. # -# Get clones of all nested repositories -sh ./common/bin/hgforest.sh clone "$@" || exit 1 +# Version check + +# required +reqdmajor=1 +reqdminor=5 +reqdrev=0 + +# requested +rqstmajor=2 +rqstminor=6 +rqstrev=3 + +# installed +hgwhere="`which hg 2> /dev/null | grep -v '^no hg in '`" +if [ "x$hgwhere" = "x" ]; then + echo "ERROR: Could not locate Mercurial command" >&2 + exit 126 +fi + +hgversion="`hg --version 2> /dev/null | sed -n -e 's@^Mercurial Distributed SCM (version \(.*\))\$@\1@p'`" +if [ "x${hgversion}" = "x" ] ; then + echo "ERROR: Could not determine Mercurial version" >&2 + exit 126 +fi + +hgmajor="`echo $hgversion | cut -f 1 -d .`" +hgminor="`echo $hgversion | cut -f 2 -d .`" +hgrev="`echo $hgversion.0 | cut -f 3 -d .`" # rev is omitted for minor and major releases + +# Require +if [ $hgmajor -lt $reqdmajor -o \( $hgmajor -eq $reqdmajor -a $hgminor -lt $reqdminor \) -o \( $hgmajor -eq $reqdmajor -a $hgminor -eq $reqdminor -a $hgrev -lt $reqdrev \) ] ; then + echo "ERROR: Mercurial version $reqdmajor.$reqdminor.$reqdrev or later is required. $hgwhere is version $hgversion" >&2 + exit 126 +fi + +# Request +if [ $hgmajor -lt $rqstmajor -o \( $hgmajor -eq $rqstmajor -a $hgminor -lt $rqstminor \) -o \( $hgmajor -eq $rqstmajor -a $hgminor -eq $rqstminor -a $hgrev -lt $rqstrev \) ] ; then + echo "WARNING: Mercurial version $rqstmajor.$rqstminor.$rqstrev or later is recommended. $hgwhere is version $hgversion" >&2 +fi + +# Get clones of all absent nested repositories (harmless if already exist) +sh ./common/bin/hgforest.sh clone "$@" || exit $? # Update all existing repositories to the latest sources sh ./common/bin/hgforest.sh pull -u - diff --git a/hotspot/.hgtags b/hotspot/.hgtags index b4c3b90e4c2..bc44b8bd401 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -423,3 +423,4 @@ b14e7c0b7d3ec04127f565cda1d84122e205680c jdk9-b16 871fd128548480095e0dc3fc34c422666baeec75 jdk9-b18 d4cffb3ae6213c66c7522ebffe0349360a45f0ef jdk9-b19 c1af79d122ec9f715fa29312b5e91763f3a4dfc4 jdk9-b20 +17b4a5e831b398738feedb0afe75245744510153 jdk9-b21 diff --git a/hotspot/agent/src/os/bsd/MacosxDebuggerLocal.m b/hotspot/agent/src/os/bsd/MacosxDebuggerLocal.m index 0f0ff4e5da4..044340aa511 100644 --- a/hotspot/agent/src/os/bsd/MacosxDebuggerLocal.m +++ b/hotspot/agent/src/os/bsd/MacosxDebuggerLocal.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,7 @@ #import #import -#include +#include #import #import diff --git a/hotspot/agent/src/os/bsd/Makefile b/hotspot/agent/src/os/bsd/Makefile index ce3e2c4c32c..eabe1f7730d 100644 --- a/hotspot/agent/src/os/bsd/Makefile +++ b/hotspot/agent/src/os/bsd/Makefile @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -50,9 +50,9 @@ SOURCES = symtab.c \ ps_core.c OBJS = $(SOURCES:.c=.o) OBJSPLUS = MacosxDebuggerLocal.o sadis.o $(OBJS) -EXTINCLUDE = -I/System/Library/Frameworks/JavaVM.framework/Headers -I. +EXTINCLUDE = -I. EXTCFLAGS = -m64 -D__APPLE__ -framework JavaNativeFoundation -FOUNDATIONFLAGS = -framework Foundation -F/System/Library/Frameworks/JavaVM.framework/Frameworks -framework JavaNativeFoundation -framework Security -framework CoreFoundation +FOUNDATIONFLAGS = -framework Foundation -framework JavaNativeFoundation -framework Security -framework CoreFoundation LIBSA = $(ARCH)/libsaproc.dylib endif # Darwin diff --git a/hotspot/agent/src/os/linux/libproc.h b/hotspot/agent/src/os/linux/libproc.h index c917a938c5a..b07c090bfec 100644 --- a/hotspot/agent/src/os/linux/libproc.h +++ b/hotspot/agent/src/os/linux/libproc.h @@ -34,7 +34,7 @@ #include "libproc_md.h" #endif -#include +#include /************************************************************************************ diff --git a/hotspot/agent/src/os/linux/ps_proc.c b/hotspot/agent/src/os/linux/ps_proc.c index 61923a25529..a3c18c9e0de 100644 --- a/hotspot/agent/src/os/linux/ps_proc.c +++ b/hotspot/agent/src/os/linux/ps_proc.c @@ -263,7 +263,7 @@ static bool add_new_thread(struct ps_prochandle* ph, pthread_t pthread_id, lwpid static bool read_lib_info(struct ps_prochandle* ph) { char fname[32]; - char buf[256]; + char buf[PATH_MAX]; FILE *fp = NULL; sprintf(fname, "/proc/%d/maps", ph->pid); @@ -273,10 +273,41 @@ static bool read_lib_info(struct ps_prochandle* ph) { return false; } - while(fgets_no_cr(buf, 256, fp)){ - char * word[6]; - int nwords = split_n_str(buf, 6, word, ' ', '\0'); - if (nwords > 5 && find_lib(ph, word[5]) == false) { + while(fgets_no_cr(buf, PATH_MAX, fp)){ + char * word[7]; + int nwords = split_n_str(buf, 7, word, ' ', '\0'); + + if (nwords < 6) { + // not a shared library entry. ignore. + continue; + } + + // SA does not handle the lines with patterns: + // "[stack]", "[heap]", "[vdso]", "[vsyscall]", etc. + if (word[5][0] == '[') { + // not a shared library entry. ignore. + continue; + } + + if (nwords > 6) { + // prelink altered mapfile when the program is running. + // Entries like one below have to be skipped + // /lib64/libc-2.15.so (deleted) + // SO name in entries like one below have to be stripped. + // /lib64/libpthread-2.15.so.#prelink#.EECVts + char *s = strstr(word[5],".#prelink#"); + if (s == NULL) { + // No prelink keyword. skip deleted library + print_debug("skip shared object %s deleted by prelink\n", word[5]); + continue; + } + + // Fall through + print_debug("rectifying shared object name %s changed by prelink\n", word[5]); + *s = 0; + } + + if (find_lib(ph, word[5]) == false) { intptr_t base; lib_info* lib; #ifdef _LP64 diff --git a/hotspot/make/bsd/makefiles/saproc.make b/hotspot/make/bsd/makefiles/saproc.make index a147325979f..1b0d5d603e8 100644 --- a/hotspot/make/bsd/makefiles/saproc.make +++ b/hotspot/make/bsd/makefiles/saproc.make @@ -64,9 +64,23 @@ ifeq ($(OS_VENDOR), FreeBSD) else ifeq ($(OS_VENDOR), Darwin) SASRCFILES = $(DARWIN_NON_STUB_SASRCFILES) - SALIBS = -g -framework Foundation -F/System/Library/Frameworks/JavaVM.framework/Frameworks -framework JavaNativeFoundation -framework Security -framework CoreFoundation + SALIBS = -g \ + -framework Foundation \ + -framework JavaNativeFoundation \ + -framework Security \ + -framework CoreFoundation #objc compiler blows up on -march=i586, perhaps it should not be included in the macosx intel 32-bit C++ compiles? SAARCH = $(subst -march=i586,,$(ARCHFLAG)) + + # This is needed to locate JavaNativeFoundation.framework + ifeq ($(SYSROOT_CFLAGS),) + # this will happen when building without spec.gmk, set SDKROOT to a valid SDK + # path if your system does not have headers installed in the system frameworks + SA_SYSROOT_FLAGS = -F"$(SDKROOT)/System/Library/Frameworks/JavaVM.framework/Frameworks" + else + # Just use SYSROOT_CFLAGS + SA_SYSROOT_FLAGS=$(SYSROOT_CFLAGS) + endif else SASRCFILES = $(SASRCDIR)/StubDebuggerLocal.c SALIBS = @@ -100,14 +114,8 @@ SA_LFLAGS = $(MAPFLAG:FILENAME=$(SAMAPFILE)) endif SA_LFLAGS += $(LDFLAGS_HASH_STYLE) -ifeq ($(OS_VENDOR), Darwin) - BOOT_JAVA_INCLUDES = -I$(BOOT_JAVA_HOME)/include \ - -I$(BOOT_JAVA_HOME)/include/$(shell uname -s | tr "[:upper:]" "[:lower:]") \ - -I/System/Library/Frameworks/JavaVM.framework/Headers -else - BOOT_JAVA_INCLUDES = -I$(BOOT_JAVA_HOME)/include \ - -I$(BOOT_JAVA_HOME)/include/$(shell uname -s | tr "[:upper:]" "[:lower:]") -endif +BOOT_JAVA_INCLUDES = -I$(BOOT_JAVA_HOME)/include \ + -I$(BOOT_JAVA_HOME)/include/$(shell uname -s | tr "[:upper:]" "[:lower:]") $(LIBSAPROC): $(SASRCFILES) $(SAMAPFILE) $(QUIETLY) if [ "$(BOOT_JAVA_HOME)" = "" ]; then \ @@ -116,6 +124,7 @@ $(LIBSAPROC): $(SASRCFILES) $(SAMAPFILE) fi @echo Making SA debugger back-end... $(QUIETLY) $(CC) -D$(BUILDARCH) -D_GNU_SOURCE \ + $(SA_SYSROOT_FLAGS) \ $(SYMFLAG) $(SAARCH) $(SHARED_FLAG) $(PICFLAG) \ -I$(SASRCDIR) \ -I$(GENERATED) \ diff --git a/hotspot/make/bsd/makefiles/vm.make b/hotspot/make/bsd/makefiles/vm.make index 77dde8bc930..56beb6c6ba5 100644 --- a/hotspot/make/bsd/makefiles/vm.make +++ b/hotspot/make/bsd/makefiles/vm.make @@ -295,6 +295,7 @@ endif $(PRECOMPILED_HEADER): $(QUIETLY) echo Generating precompiled header $@ $(QUIETLY) mkdir -p $(PRECOMPILED_HEADER_DIR) + $(QUIETLY) rm -f $@ $(QUIETLY) $(COMPILE.CXX) $(DEPFLAGS) -x c++-header $(PRECOMPILED_HEADER_SRC) -o $@ $(COMPILE_DONE) # making the library: diff --git a/hotspot/make/linux/makefiles/vm.make b/hotspot/make/linux/makefiles/vm.make index bcf87c043ec..c91463aae13 100644 --- a/hotspot/make/linux/makefiles/vm.make +++ b/hotspot/make/linux/makefiles/vm.make @@ -290,6 +290,7 @@ LINK_VM = $(LINK_LIB.CC) $(PRECOMPILED_HEADER): $(QUIETLY) echo Generating precompiled header $@ $(QUIETLY) mkdir -p $(PRECOMPILED_HEADER_DIR) + $(QUIETLY) rm -f $@ $(QUIETLY) $(COMPILE.CXX) $(DEPFLAGS) -x c++-header $(PRECOMPILED_HEADER_SRC) -o $@ $(COMPILE_DONE) # making the library: diff --git a/hotspot/make/windows/create.bat b/hotspot/make/windows/create.bat index a9a8acea6d2..fb0d450187a 100644 --- a/hotspot/make/windows/create.bat +++ b/hotspot/make/windows/create.bat @@ -1,6 +1,6 @@ @echo off REM -REM Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. +REM Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. REM DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. REM REM This code is free software; you can redistribute it and/or modify it @@ -81,33 +81,8 @@ REM figure out MSC version for /F %%i in ('sh %HotSpotWorkSpace%/make/windows/get_msc_ver.sh') do set %%i echo ************************************************************** -set ProjectFile=%HotSpotBuildSpace%\jvm.vcproj echo MSC_VER = "%MSC_VER%" -if "%MSC_VER%" == "1200" ( -set ProjectFile=%HotSpotBuildSpace%\jvm.dsp -echo Will generate VC6 project {unsupported} -) else ( -if "%MSC_VER%" == "1400" ( -echo Will generate VC8 {Visual Studio 2005} -) else ( -if "%MSC_VER%" == "1500" ( -echo Will generate VC9 {Visual Studio 2008} -) else ( -if "%MSC_VER%" == "1600" ( -echo Will generate VC10 {Visual Studio 2010} set ProjectFile=%HotSpotBuildSpace%\jvm.vcxproj -) else ( -if "%MSC_VER%" == "1700" ( -echo Will generate VC10 {compatible with Visual Studio 2012} -echo After opening in VS 2012, click "Update" when prompted. -set ProjectFile=%HotSpotBuildSpace%\jvm.vcxproj -) else ( -echo Will generate VC7 project {Visual Studio 2003 .NET} -) -) -) -) -) echo %ProjectFile% echo ************************************************************** diff --git a/hotspot/make/windows/makefiles/compile.make b/hotspot/make/windows/makefiles/compile.make index 9da2742335e..a4d1c0d4c3e 100644 --- a/hotspot/make/windows/makefiles/compile.make +++ b/hotspot/make/windows/makefiles/compile.make @@ -1,5 +1,5 @@ # -# Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -63,28 +63,20 @@ CXX_FLAGS=$(CXX_FLAGS) /Zi # Based on BUILDARCH we add some flags and select the default compiler name !if "$(BUILDARCH)" == "ia64" MACHINE=IA64 -DEFAULT_COMPILER_NAME=VS2003 CXX_FLAGS=$(CXX_FLAGS) /D "CC_INTERP" /D "_LP64" /D "IA64" !endif !if "$(BUILDARCH)" == "amd64" MACHINE=AMD64 -DEFAULT_COMPILER_NAME=VS2005 CXX_FLAGS=$(CXX_FLAGS) /D "_LP64" /D "AMD64" LP64=1 !endif !if "$(BUILDARCH)" == "i486" MACHINE=I386 -DEFAULT_COMPILER_NAME=VS2003 CXX_FLAGS=$(CXX_FLAGS) /D "IA32" !endif -# Sanity check, this is the default if not amd64, ia64, or i486 -!ifndef DEFAULT_COMPILER_NAME -CXX=ARCH_ERROR -!endif - CXX_FLAGS=$(CXX_FLAGS) /D "WIN32" /D "_WINDOWS" # Must specify this for sharedRuntimeTrig.cpp CXX_FLAGS=$(CXX_FLAGS) /D "VM_LITTLE_ENDIAN" @@ -112,6 +104,7 @@ CXX_FLAGS=$(CXX_FLAGS) /D TARGET_COMPILER_visCPP # 1500 is for VS2008 # 1600 is for VS2010 # 1700 is for VS2012 +# 1800 is for VS2013 # Do not confuse this MSC_VER with the predefined macro _MSC_VER that the # compiler provides, when MSC_VER==1399, _MSC_VER will be 1400. # Normally they are the same, but a pre-release of the VS2005 compilers @@ -119,35 +112,6 @@ CXX_FLAGS=$(CXX_FLAGS) /D TARGET_COMPILER_visCPP # closer to VS2003 in terms of option spellings, so we use 1399 for that # 1400 version that really isn't 1400. # See the file get_msc_ver.sh for more info. -!if "x$(MSC_VER)" == "x" -COMPILER_NAME=$(DEFAULT_COMPILER_NAME) -!else -!if "$(MSC_VER)" == "1200" -COMPILER_NAME=VC6 -!endif -!if "$(MSC_VER)" == "1300" -COMPILER_NAME=VS2003 -!endif -!if "$(MSC_VER)" == "1310" -COMPILER_NAME=VS2003 -!endif -!if "$(MSC_VER)" == "1399" -# Compiler might say 1400, but if it's 14.00.30701, it isn't really VS2005 -COMPILER_NAME=VS2003 -!endif -!if "$(MSC_VER)" == "1400" -COMPILER_NAME=VS2005 -!endif -!if "$(MSC_VER)" == "1500" -COMPILER_NAME=VS2008 -!endif -!if "$(MSC_VER)" == "1600" -COMPILER_NAME=VS2010 -!endif -!if "$(MSC_VER)" == "1700" -COMPILER_NAME=VS2012 -!endif -!endif # By default, we do not want to use the debug version of the msvcrt.dll file # but if MFC_DEBUG is defined in the environment it will be used. @@ -165,60 +129,6 @@ MS_RUNTIME_OPTION = $(MS_RUNTIME_OPTION) $(STATIC_CPPLIB_OPTION) !endif CXX_FLAGS=$(CXX_FLAGS) $(MS_RUNTIME_OPTION) -# How /GX option is spelled -GX_OPTION = /GX - -# Optimization settings for various versions of the compilers and types of -# builds. Three basic sets of settings: product, fastdebug, and debug. -# These get added into CXX_FLAGS as needed by other makefiles. -!if "$(COMPILER_NAME)" == "VC6" -PRODUCT_OPT_OPTION = /Ox /Os /Gy /GF -FASTDEBUG_OPT_OPTION = /Ox /Os /Gy /GF -DEBUG_OPT_OPTION = /Od -!endif - -!if "$(COMPILER_NAME)" == "VS2003" -PRODUCT_OPT_OPTION = /O2 /Oy- -FASTDEBUG_OPT_OPTION = /O2 /Oy- -DEBUG_OPT_OPTION = /Od -SAFESEH_FLAG = /SAFESEH -!endif - -!if "$(COMPILER_NAME)" == "VS2005" -PRODUCT_OPT_OPTION = /O2 /Oy- -FASTDEBUG_OPT_OPTION = /O2 /Oy- -DEBUG_OPT_OPTION = /Od -GX_OPTION = /EHsc -# This VS2005 compiler has /GS as a default and requires bufferoverflowU.lib -# on the link command line, otherwise we get missing __security_check_cookie -# externals at link time. Even with /GS-, you need bufferoverflowU.lib. -# NOTE: Currently we decided to not use /GS- -BUFFEROVERFLOWLIB = bufferoverflowU.lib -LD_FLAGS = /manifest $(LD_FLAGS) $(BUFFEROVERFLOWLIB) -# Manifest Tool - used in VS2005 and later to adjust manifests stored -# as resources inside build artifacts. -!if "x$(MT)" == "x" -MT=mt.exe -!endif -SAFESEH_FLAG = /SAFESEH -!endif - -!if "$(COMPILER_NAME)" == "VS2008" -PRODUCT_OPT_OPTION = /O2 /Oy- -FASTDEBUG_OPT_OPTION = /O2 /Oy- -DEBUG_OPT_OPTION = /Od -GX_OPTION = /EHsc -LD_FLAGS = /manifest $(LD_FLAGS) -MP_FLAG = /MP -# Manifest Tool - used in VS2005 and later to adjust manifests stored -# as resources inside build artifacts. -!if "x$(MT)" == "x" -MT=mt.exe -!endif -SAFESEH_FLAG = /SAFESEH -!endif - -!if "$(COMPILER_NAME)" == "VS2010" PRODUCT_OPT_OPTION = /O2 /Oy- FASTDEBUG_OPT_OPTION = /O2 /Oy- DEBUG_OPT_OPTION = /Od @@ -233,26 +143,6 @@ MT=mt.exe !if "$(BUILDARCH)" == "i486" LD_FLAGS = /SAFESEH $(LD_FLAGS) !endif -!endif - -!if "$(COMPILER_NAME)" == "VS2012" -PRODUCT_OPT_OPTION = /O2 /Oy- -FASTDEBUG_OPT_OPTION = /O2 /Oy- -DEBUG_OPT_OPTION = /Od -GX_OPTION = /EHsc -LD_FLAGS = /manifest $(LD_FLAGS) -MP_FLAG = /MP -# Manifest Tool - used in VS2005 and later to adjust manifests stored -# as resources inside build artifacts. -!if "x$(MT)" == "x" -MT=mt.exe -!endif -SAFESEH_FLAG = /SAFESEH -!endif - -!if "$(BUILDARCH)" == "i486" -LD_FLAGS = $(SAFESEH_FLAG) $(LD_FLAGS) -!endif CXX_FLAGS = $(CXX_FLAGS) $(MP_FLAG) diff --git a/hotspot/make/windows/makefiles/rules.make b/hotspot/make/windows/makefiles/rules.make index c5d565a2880..08a6a85e101 100644 --- a/hotspot/make/windows/makefiles/rules.make +++ b/hotspot/make/windows/makefiles/rules.make @@ -1,5 +1,5 @@ # -# Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -49,35 +49,8 @@ BOOT_TARGET_CLASS_VERSION=6 JAVAC_FLAGS=-g -encoding ascii BOOTSTRAP_JAVAC_FLAGS=$(JAVAC_FLAGS) -source $(BOOT_SOURCE_LANGUAGE_VERSION) -target $(BOOT_TARGET_CLASS_VERSION) -ProjectFile=jvm.vcproj - -!if "$(MSC_VER)" == "1200" - -VcVersion=VC6 -ProjectFile=jvm.dsp - -!elseif "$(MSC_VER)" == "1400" - -VcVersion=VC8 - -!elseif "$(MSC_VER)" == "1500" - -VcVersion=VC9 - -!elseif "$(MSC_VER)" == "1600" - -VcVersion=VC10 -ProjectFile=jvm.vcxproj - -!elseif "$(MSC_VER)" == "1700" -# This is VS2012, but it loads VS10 projects just fine (and will +# VS2012 and VS2013 loads VS10 projects just fine (and will # upgrade them automatically to VS2012 format). - VcVersion=VC10 ProjectFile=jvm.vcxproj -!else - -VcVersion=VC7 - -!endif diff --git a/hotspot/make/windows/makefiles/sa.make b/hotspot/make/windows/makefiles/sa.make index 2208da9e3d8..13bb8130ef4 100644 --- a/hotspot/make/windows/makefiles/sa.make +++ b/hotspot/make/windows/makefiles/sa.make @@ -1,5 +1,5 @@ # -# Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -85,14 +85,9 @@ checkAndBuildSA:: $(SAWINDBG) # will be useful to have the assertion checks in place !if "$(BUILDARCH)" == "ia64" -SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "WIN64" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -YX -FD -c +SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "WIN64" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -FD -c !elseif "$(BUILDARCH)" == "amd64" -SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "WIN64" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -YX -FD -c -!if "$(COMPILER_NAME)" == "VS2005" -# On amd64, VS2005 compiler requires bufferoverflowU.lib on the link command line, -# otherwise we get missing __security_check_cookie externals at link time. -SA_LD_FLAGS = bufferoverflowU.lib -!endif +SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "WIN64" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -FD -c !else SA_CFLAGS = -nologo $(MS_RUNTIME_OPTION) -W3 $(GX_OPTION) -Od -D "WIN32" -D "_WINDOWS" -D "_DEBUG" -D "_CONSOLE" -D "_MBCS" -FD -RTC1 -c !if "$(ENABLE_FULL_DEBUG_SYMBOLS)" == "1" diff --git a/hotspot/make/windows/makefiles/sanity.make b/hotspot/make/windows/makefiles/sanity.make index b502cfaa65f..515b0bb1b50 100644 --- a/hotspot/make/windows/makefiles/sanity.make +++ b/hotspot/make/windows/makefiles/sanity.make @@ -1,5 +1,5 @@ # -# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -27,9 +27,9 @@ all: checkCL checkLink checkCL: - @ if "$(MSC_VER)" NEQ "1310" if "$(MSC_VER)" NEQ "1399" if "$(MSC_VER)" NEQ "1400" if "$(MSC_VER)" NEQ "1500" if "$(MSC_VER)" NEQ "1600" if "$(MSC_VER)" NEQ "1700" \ - echo *** WARNING *** unrecognized cl.exe version $(MSC_VER) ($(RAW_MSC_VER)). Use FORCE_MSC_VER to override automatic detection. + @ if "$(MSC_VER)" NEQ "1600" if "$(MSC_VER)" NEQ "1700" if "$(MSC_VER)" NEQ "1800" \ + echo *** WARNING *** Unsupported cl.exe version detected: $(MSC_VER) ($(RAW_MSC_VER)), only 1600/1700/1800 (Visual Studio 2010/2012/2013) are supported. checkLink: - @ if "$(LD_VER)" NEQ "710" if "$(LD_VER)" NEQ "800" if "$(LD_VER)" NEQ "900" if "$(LD_VER)" NEQ "1000" if "$(LD_VER)" NEQ "1100" \ - echo *** WARNING *** unrecognized link.exe version $(LD_VER) ($(RAW_LD_VER)). Use FORCE_LD_VER to override automatic detection. + @ if "$(LD_VER)" NEQ "1000" if "$(LD_VER)" NEQ "1100" if "$(LD_VER)" NEQ "1200" \ + echo *** WARNING *** Unsupported link.exe version detected: $(LD_VER) ($(RAW_LD_VER)), only 1000/1100/1200 (Visual Studio 2010/2012/2013) are supported. diff --git a/hotspot/make/windows/makefiles/vm.make b/hotspot/make/windows/makefiles/vm.make index e4caa13dea2..d8040f89ed8 100644 --- a/hotspot/make/windows/makefiles/vm.make +++ b/hotspot/make/windows/makefiles/vm.make @@ -1,5 +1,5 @@ # -# Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -132,7 +132,7 @@ CXX_DONT_USE_PCH=/D DONT_USE_PRECOMPILED_HEADER !if "$(USE_PRECOMPILED_HEADER)" != "0" CXX_USE_PCH=/Fp"vm.pch" /Yu"precompiled.hpp" -!if "$(COMPILER_NAME)" == "VS2012" +!if "$(MSC_VER)" > "1600" # VS2012 requires this object file to be listed: LD_FLAGS=$(LD_FLAGS) _build_pch_file.obj !endif diff --git a/hotspot/make/windows/projectfiles/common/Makefile b/hotspot/make/windows/projectfiles/common/Makefile index 51d4e6f1f11..1fc1350706e 100644 --- a/hotspot/make/windows/projectfiles/common/Makefile +++ b/hotspot/make/windows/projectfiles/common/Makefile @@ -1,5 +1,5 @@ # -# Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -120,7 +120,6 @@ ReleaseOptions = -define HOTSPOT_RELEASE_VERSION=$(HOTSPOT_RELEASE_VERSION) -def ProjectCreatorIDEOptions = $(ProjectCreatorIDEOptions) $(ReleaseOptions) $(HOTSPOTBUILDSPACE)/$(ProjectFile): $(HOTSPOTBUILDSPACE)/classes/ProjectCreator.class - @if "$(MSC_VER)"=="1500" echo Make sure you have VS2008 SP1 or later, or you may see 'expanded command line too long' @$(RUN_JAVA) -Djava.class.path="$(HOTSPOTBUILDSPACE)/classes" ProjectCreator WinGammaPlatform$(VcVersion) $(ProjectCreatorIDEOptions) clean: diff --git a/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp b/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp index b9702a35e41..62bb56fe97f 100644 --- a/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp +++ b/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp @@ -625,6 +625,7 @@ int LIR_Assembler::safepoint_poll(LIR_Opr tmp, CodeEmitInfo* info) { __ lea(rscratch1, polling_page); offset = __ offset(); add_debug_info_for_branch(info); + __ relocate(relocInfo::poll_type); __ testl(rax, Address(rscratch1, 0)); } else { add_debug_info_for_branch(info); diff --git a/hotspot/src/os/bsd/vm/os_bsd.cpp b/hotspot/src/os/bsd/vm/os_bsd.cpp index 9d817380e3e..7facffe684d 100644 --- a/hotspot/src/os/bsd/vm/os_bsd.cpp +++ b/hotspot/src/os/bsd/vm/os_bsd.cpp @@ -786,7 +786,7 @@ bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { case os::java_thread: // Java threads use ThreadStackSize which default value can be // changed with the flag -Xss - assert (JavaThread::stack_size_at_create() > 0, "this should be set"); + assert(JavaThread::stack_size_at_create() > 0, "this should be set"); stack_size = JavaThread::stack_size_at_create(); break; case os::compiler_thread: @@ -1303,7 +1303,7 @@ bool os::dll_build_name(char* buffer, size_t buflen, if (pelements == NULL) { return false; } - for (int i = 0 ; i < n ; i++) { + for (int i = 0; i < n; i++) { // Really shouldn't be NULL, but check can't hurt if (pelements[i] == NULL || strlen(pelements[i]) == 0) { continue; // skip the empty path values @@ -1316,7 +1316,7 @@ bool os::dll_build_name(char* buffer, size_t buflen, } } // release the storage - for (int i = 0 ; i < n ; i++) { + for (int i = 0; i < n; i++) { if (pelements[i] != NULL) { FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal); } @@ -1467,7 +1467,7 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) bool failed_to_read_elf_head= (sizeof(elf_head)!= - (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ; + (::read(file_descriptor, &elf_head,sizeof(elf_head)))); ::close(file_descriptor); if (failed_to_read_elf_head) { @@ -1565,7 +1565,7 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; int running_arch_index=-1; - for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) { + for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) { if (running_arch_code == arch_array[i].code) { running_arch_index = i; } @@ -1596,7 +1596,7 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) #endif // !S390 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { - if ( lib_arch.name!=NULL ) { + if (lib_arch.name!=NULL) { ::snprintf(diag_msg_buf, diag_msg_max_length-1, " (Possible cause: can't load %s-bit .so on a %s-bit platform)", lib_arch.name, arch_array[running_arch_index].name); @@ -2598,7 +2598,7 @@ void os::yield() { sched_yield(); } -os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;} +os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN; } void os::yield_all() { // Yields to all threads, including threads with lower priorities @@ -2686,7 +2686,7 @@ static int prio_init() { } OSReturn os::set_native_priority(Thread* thread, int newpri) { - if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK; + if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK; #ifdef __OpenBSD__ // OpenBSD pthread_setprio starves low priority threads @@ -2713,7 +2713,7 @@ OSReturn os::set_native_priority(Thread* thread, int newpri) { } OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) { - if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) { + if (!UseThreadPriorities || ThreadPriorityPolicy == 0) { *priority_ptr = java_to_os_priority[NormPriority]; return OS_OK; } @@ -3079,7 +3079,7 @@ bool os::Bsd::chained_handler(int sig, siginfo_t* siginfo, void* context) { } struct sigaction* os::Bsd::get_preinstalled_handler(int sig) { - if ((( (unsigned int)1 << sig ) & sigs) != 0) { + if ((((unsigned int)1 << sig) & sigs) != 0) { return &sigact[sig]; } return NULL; @@ -3300,7 +3300,7 @@ static void print_signal_handler(outputStream* st, int sig, address rh = VMError::get_resetted_sighandler(sig); // May be, handler was resetted by VMError? - if(rh != NULL) { + if (rh != NULL) { handler = rh; sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK; } @@ -3309,11 +3309,11 @@ static void print_signal_handler(outputStream* st, int sig, os::Posix::print_sa_flags(st, sa.sa_flags); // Check: is it our handler? - if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) || + if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) || handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) { // It is our signal handler // check for flags, reset system-used one! - if((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) { + if ((int)sa.sa_flags != os::Bsd::get_our_sigflags(sig)) { st->print( ", flags was changed from " PTR32_FORMAT ", consider using jsig library", os::Bsd::get_our_sigflags(sig)); @@ -3382,10 +3382,10 @@ void os::Bsd::check_signal_handler(int sig) { address thisHandler = (act.sa_flags & SA_SIGINFO) ? CAST_FROM_FN_PTR(address, act.sa_sigaction) - : CAST_FROM_FN_PTR(address, act.sa_handler) ; + : CAST_FROM_FN_PTR(address, act.sa_handler); - switch(sig) { + switch (sig) { case SIGSEGV: case SIGBUS: case SIGFPE: @@ -3515,22 +3515,22 @@ jint os::init_2(void) { // Allocate a single page and mark it as readable for safepoint polling address polling_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); - guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" ); + guarantee(polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page"); - os::set_polling_page( polling_page ); + os::set_polling_page(polling_page); #ifndef PRODUCT - if(Verbose && PrintMiscellaneous) + if (Verbose && PrintMiscellaneous) tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page); #endif if (!UseMembar) { address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); - guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page"); - os::set_memory_serialize_page( mem_serialize_page ); + guarantee(mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page"); + os::set_memory_serialize_page(mem_serialize_page); #ifndef PRODUCT - if(Verbose && PrintMiscellaneous) + if (Verbose && PrintMiscellaneous) tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); #endif } @@ -3631,13 +3631,13 @@ void os::init_3(void) { } // Mark the polling page as unreadable void os::make_polling_page_unreadable(void) { - if( !guard_memory((char*)_polling_page, Bsd::page_size()) ) + if (!guard_memory((char*)_polling_page, Bsd::page_size())) fatal("Could not disable polling page"); }; // Mark the polling page as readable void os::make_polling_page_readable(void) { - if( !bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) { + if (!bsd_mprotect((char *)_polling_page, Bsd::page_size(), PROT_READ)) { fatal("Could not enable polling page"); } }; @@ -4229,9 +4229,9 @@ static struct timespec* compute_abstime(struct timespec* abstime, jlong millis) int os::PlatformEvent::TryPark() { for (;;) { - const int v = _Event ; - guarantee ((v == 0) || (v == 1), "invariant") ; - if (Atomic::cmpxchg (0, &_Event, v) == v) return v ; + const int v = _Event; + guarantee((v == 0) || (v == 1), "invariant"); + if (Atomic::cmpxchg(0, &_Event, v) == v) return v; } } @@ -4239,18 +4239,18 @@ void os::PlatformEvent::park() { // AKA "down()" // Invariant: Only the thread associated with the Event/PlatformEvent // may call park(). // TODO: assert that _Assoc != NULL or _Assoc == Self - int v ; + int v; for (;;) { - v = _Event ; - if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; + v = _Event; + if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; } - guarantee (v >= 0, "invariant") ; + guarantee(v >= 0, "invariant"); if (v == 0) { // Do this the hard way by blocking ... int status = pthread_mutex_lock(_mutex); assert_status(status == 0, status, "mutex_lock"); - guarantee (_nParked == 0, "invariant") ; - ++ _nParked ; + guarantee(_nParked == 0, "invariant"); + ++_nParked; while (_Event < 0) { status = pthread_cond_wait(_cond, _mutex); // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... @@ -4258,28 +4258,28 @@ void os::PlatformEvent::park() { // AKA "down()" if (status == ETIMEDOUT) { status = EINTR; } assert_status(status == 0 || status == EINTR, status, "cond_wait"); } - -- _nParked ; + --_nParked; - _Event = 0 ; + _Event = 0; status = pthread_mutex_unlock(_mutex); assert_status(status == 0, status, "mutex_unlock"); // Paranoia to ensure our locked and lock-free paths interact // correctly with each other. OrderAccess::fence(); } - guarantee (_Event >= 0, "invariant") ; + guarantee(_Event >= 0, "invariant"); } int os::PlatformEvent::park(jlong millis) { - guarantee (_nParked == 0, "invariant") ; + guarantee(_nParked == 0, "invariant"); - int v ; + int v; for (;;) { - v = _Event ; - if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; + v = _Event; + if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; } - guarantee (v >= 0, "invariant") ; - if (v != 0) return OS_OK ; + guarantee(v >= 0, "invariant"); + if (v != 0) return OS_OK; // We do this the hard way, by blocking the thread. // Consider enforcing a minimum timeout value. @@ -4289,8 +4289,8 @@ int os::PlatformEvent::park(jlong millis) { int ret = OS_TIMEOUT; int status = pthread_mutex_lock(_mutex); assert_status(status == 0, status, "mutex_lock"); - guarantee (_nParked == 0, "invariant") ; - ++_nParked ; + guarantee(_nParked == 0, "invariant"); + ++_nParked; // Object.wait(timo) will return because of // (a) notification @@ -4308,24 +4308,24 @@ int os::PlatformEvent::park(jlong millis) { while (_Event < 0) { status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &abst); if (status != 0 && WorkAroundNPTLTimedWaitHang) { - pthread_cond_destroy (_cond); - pthread_cond_init (_cond, NULL) ; + pthread_cond_destroy(_cond); + pthread_cond_init(_cond, NULL); } assert_status(status == 0 || status == EINTR || status == ETIMEDOUT, status, "cond_timedwait"); - if (!FilterSpuriousWakeups) break ; // previous semantics - if (status == ETIMEDOUT) break ; + if (!FilterSpuriousWakeups) break; // previous semantics + if (status == ETIMEDOUT) break; // We consume and ignore EINTR and spurious wakeups. } - --_nParked ; + --_nParked; if (_Event >= 0) { ret = OS_OK; } - _Event = 0 ; + _Event = 0; status = pthread_mutex_unlock(_mutex); assert_status(status == 0, status, "mutex_unlock"); - assert (_nParked == 0, "invariant") ; + assert(_nParked == 0, "invariant"); // Paranoia to ensure our locked and lock-free paths interact // correctly with each other. OrderAccess::fence(); @@ -4409,7 +4409,7 @@ void os::PlatformEvent::unpark() { */ static void unpackTime(struct timespec* absTime, bool isAbsolute, jlong time) { - assert (time > 0, "convertTime"); + assert(time > 0, "convertTime"); struct timeval now; int status = gettimeofday(&now, NULL); @@ -4470,7 +4470,7 @@ void Parker::park(bool isAbsolute, jlong time) { // Next, demultiplex/decode time arguments struct timespec absTime; - if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all + if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all return; } if (time > 0) { @@ -4492,11 +4492,11 @@ void Parker::park(bool isAbsolute, jlong time) { return; } - int status ; + int status; if (_counter > 0) { // no wait needed _counter = 0; status = pthread_mutex_unlock(_mutex); - assert (status == 0, "invariant") ; + assert(status == 0, "invariant"); // Paranoia to ensure our locked and lock-free paths interact // correctly with each other and Java-level accesses. OrderAccess::fence(); @@ -4516,12 +4516,12 @@ void Parker::park(bool isAbsolute, jlong time) { // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() if (time == 0) { - status = pthread_cond_wait (_cond, _mutex) ; + status = pthread_cond_wait(_cond, _mutex); } else { - status = os::Bsd::safe_cond_timedwait (_cond, _mutex, &absTime) ; + status = os::Bsd::safe_cond_timedwait(_cond, _mutex, &absTime); if (status != 0 && WorkAroundNPTLTimedWaitHang) { - pthread_cond_destroy (_cond) ; - pthread_cond_init (_cond, NULL); + pthread_cond_destroy(_cond); + pthread_cond_init(_cond, NULL); } } assert_status(status == 0 || status == EINTR || @@ -4532,9 +4532,9 @@ void Parker::park(bool isAbsolute, jlong time) { pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); #endif - _counter = 0 ; - status = pthread_mutex_unlock(_mutex) ; - assert_status(status == 0, status, "invariant") ; + _counter = 0; + status = pthread_mutex_unlock(_mutex); + assert_status(status == 0, status, "invariant"); // Paranoia to ensure our locked and lock-free paths interact // correctly with each other and Java-level accesses. OrderAccess::fence(); @@ -4546,26 +4546,26 @@ void Parker::park(bool isAbsolute, jlong time) { } void Parker::unpark() { - int s, status ; + int s, status; status = pthread_mutex_lock(_mutex); - assert (status == 0, "invariant") ; + assert(status == 0, "invariant"); s = _counter; _counter = 1; if (s < 1) { if (WorkAroundNPTLTimedWaitHang) { - status = pthread_cond_signal (_cond) ; - assert (status == 0, "invariant") ; + status = pthread_cond_signal(_cond); + assert(status == 0, "invariant"); status = pthread_mutex_unlock(_mutex); - assert (status == 0, "invariant") ; + assert(status == 0, "invariant"); } else { status = pthread_mutex_unlock(_mutex); - assert (status == 0, "invariant") ; - status = pthread_cond_signal (_cond) ; - assert (status == 0, "invariant") ; + assert(status == 0, "invariant"); + status = pthread_cond_signal(_cond); + assert(status == 0, "invariant"); } } else { pthread_mutex_unlock(_mutex); - assert (status == 0, "invariant") ; + assert(status == 0, "invariant"); } } diff --git a/hotspot/src/os/bsd/vm/os_bsd.hpp b/hotspot/src/os/bsd/vm/os_bsd.hpp index 25a16562dee..36fb913f38a 100644 --- a/hotspot/src/os/bsd/vm/os_bsd.hpp +++ b/hotspot/src/os/bsd/vm/os_bsd.hpp @@ -191,16 +191,16 @@ public: class PlatformEvent : public CHeapObj { private: - double CachePad [4] ; // increase odds that _mutex is sole occupant of cache line - volatile int _Event ; - volatile int _nParked ; - pthread_mutex_t _mutex [1] ; - pthread_cond_t _cond [1] ; - double PostPad [2] ; - Thread * _Assoc ; + double CachePad[4]; // increase odds that _mutex is sole occupant of cache line + volatile int _Event; + volatile int _nParked; + pthread_mutex_t _mutex[1]; + pthread_cond_t _cond[1]; + double PostPad[2]; + Thread * _Assoc; public: // TODO-FIXME: make dtor private - ~PlatformEvent() { guarantee (0, "invariant") ; } + ~PlatformEvent() { guarantee(0, "invariant"); } public: PlatformEvent() { @@ -209,28 +209,28 @@ class PlatformEvent : public CHeapObj { assert_status(status == 0, status, "cond_init"); status = pthread_mutex_init (_mutex, NULL); assert_status(status == 0, status, "mutex_init"); - _Event = 0 ; - _nParked = 0 ; - _Assoc = NULL ; + _Event = 0; + _nParked = 0; + _Assoc = NULL; } // Use caution with reset() and fired() -- they may require MEMBARs - void reset() { _Event = 0 ; } + void reset() { _Event = 0; } int fired() { return _Event; } - void park () ; - void unpark () ; - int TryPark () ; - int park (jlong millis) ; - void SetAssociation (Thread * a) { _Assoc = a ; } + void park(); + void unpark(); + int TryPark(); + int park(jlong millis); + void SetAssociation(Thread * a) { _Assoc = a; } }; class PlatformParker : public CHeapObj { protected: - pthread_mutex_t _mutex [1] ; - pthread_cond_t _cond [1] ; + pthread_mutex_t _mutex[1]; + pthread_cond_t _cond[1]; public: // TODO-FIXME: make dtor private - ~PlatformParker() { guarantee (0, "invariant") ; } + ~PlatformParker() { guarantee(0, "invariant"); } public: PlatformParker() { diff --git a/hotspot/src/os/linux/vm/os_linux.cpp b/hotspot/src/os/linux/vm/os_linux.cpp index 89ffc72d972..7057bcd557b 100644 --- a/hotspot/src/os/linux/vm/os_linux.cpp +++ b/hotspot/src/os/linux/vm/os_linux.cpp @@ -862,7 +862,7 @@ bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { case os::java_thread: // Java threads use ThreadStackSize which default value can be // changed with the flag -Xss - assert (JavaThread::stack_size_at_create() > 0, "this should be set"); + assert(JavaThread::stack_size_at_create() > 0, "this should be set"); stack_size = JavaThread::stack_size_at_create(); break; case os::compiler_thread: @@ -1097,7 +1097,7 @@ static bool find_vma(address addr, address* vma_low, address* vma_high) { if (low <= addr && addr < high) { if (vma_low) *vma_low = low; if (vma_high) *vma_high = high; - fclose (fp); + fclose(fp); return true; } } @@ -1420,7 +1420,7 @@ void os::Linux::fast_thread_clock_init() { // must return at least tp.tv_sec == 0 which means a resolution // better than 1 sec. This is extra check for reliability. - if(pthread_getcpuclockid_func && + if (pthread_getcpuclockid_func && pthread_getcpuclockid_func(_main_thread, &clockid) == 0 && sys_clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) { @@ -1630,7 +1630,7 @@ bool os::dll_build_name(char* buffer, size_t buflen, if (pelements == NULL) { return false; } - for (int i = 0 ; i < n ; i++) { + for (int i = 0; i < n; i++) { // Really shouldn't be NULL, but check can't hurt if (pelements[i] == NULL || strlen(pelements[i]) == 0) { continue; // skip the empty path values @@ -1642,7 +1642,7 @@ bool os::dll_build_name(char* buffer, size_t buflen, } } // release the storage - for (int i = 0 ; i < n ; i++) { + for (int i = 0; i < n; i++) { if (pelements[i] != NULL) { FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal); } @@ -1906,7 +1906,7 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) bool failed_to_read_elf_head= (sizeof(elf_head)!= - (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ; + (::read(file_descriptor, &elf_head,sizeof(elf_head)))); ::close(file_descriptor); if (failed_to_read_elf_head) { @@ -1988,7 +1988,7 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; int running_arch_index=-1; - for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) { + for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) { if (running_arch_code == arch_array[i].code) { running_arch_index = i; } @@ -2019,7 +2019,7 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) #endif // !S390 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { - if ( lib_arch.name!=NULL ) { + if (lib_arch.name!=NULL) { ::snprintf(diag_msg_buf, diag_msg_max_length-1, " (Possible cause: can't load %s-bit .so on a %s-bit platform)", lib_arch.name, arch_array[running_arch_index].name); @@ -3793,7 +3793,7 @@ void os::yield() { sched_yield(); } -os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;} +os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN; } void os::yield_all() { // Yields to all threads, including threads with lower priorities @@ -3858,14 +3858,14 @@ static int prio_init() { } OSReturn os::set_native_priority(Thread* thread, int newpri) { - if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK; + if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK; int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri); return (ret == 0) ? OS_OK : OS_ERR; } OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) { - if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) { + if (!UseThreadPriorities || ThreadPriorityPolicy == 0) { *priority_ptr = java_to_os_priority[NormPriority]; return OS_OK; } @@ -4219,7 +4219,7 @@ bool os::Linux::chained_handler(int sig, siginfo_t* siginfo, void* context) { } struct sigaction* os::Linux::get_preinstalled_handler(int sig) { - if ((( (unsigned int)1 << sig ) & sigs) != 0) { + if ((((unsigned int)1 << sig) & sigs) != 0) { return &sigact[sig]; } return NULL; @@ -4423,7 +4423,7 @@ static void print_signal_handler(outputStream* st, int sig, address rh = VMError::get_resetted_sighandler(sig); // May be, handler was resetted by VMError? - if(rh != NULL) { + if (rh != NULL) { handler = rh; sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK; } @@ -4432,11 +4432,11 @@ static void print_signal_handler(outputStream* st, int sig, os::Posix::print_sa_flags(st, sa.sa_flags); // Check: is it our handler? - if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) || + if (handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) || handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) { // It is our signal handler // check for flags, reset system-used one! - if((int)sa.sa_flags != os::Linux::get_our_sigflags(sig)) { + if ((int)sa.sa_flags != os::Linux::get_our_sigflags(sig)) { st->print( ", flags was changed from " PTR32_FORMAT ", consider using jsig library", os::Linux::get_our_sigflags(sig)); @@ -4507,10 +4507,10 @@ void os::Linux::check_signal_handler(int sig) { address thisHandler = (act.sa_flags & SA_SIGINFO) ? CAST_FROM_FN_PTR(address, act.sa_sigaction) - : CAST_FROM_FN_PTR(address, act.sa_handler) ; + : CAST_FROM_FN_PTR(address, act.sa_handler); - switch(sig) { + switch (sig) { case SIGSEGV: case SIGBUS: case SIGFPE: @@ -4662,22 +4662,22 @@ jint os::init_2(void) // Allocate a single page and mark it as readable for safepoint polling address polling_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); - guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" ); + guarantee(polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page"); - os::set_polling_page( polling_page ); + os::set_polling_page(polling_page); #ifndef PRODUCT - if(Verbose && PrintMiscellaneous) + if (Verbose && PrintMiscellaneous) tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page); #endif if (!UseMembar) { address mem_serialize_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); - guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page"); - os::set_memory_serialize_page( mem_serialize_page ); + guarantee(mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page"); + os::set_memory_serialize_page(mem_serialize_page); #ifndef PRODUCT - if(Verbose && PrintMiscellaneous) + if (Verbose && PrintMiscellaneous) tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); #endif } @@ -4819,13 +4819,13 @@ void os::init_3(void) { // Mark the polling page as unreadable void os::make_polling_page_unreadable(void) { - if( !guard_memory((char*)_polling_page, Linux::page_size()) ) + if (!guard_memory((char*)_polling_page, Linux::page_size())) fatal("Could not disable polling page"); }; // Mark the polling page as readable void os::make_polling_page_readable(void) { - if( !linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) { + if (!linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) { fatal("Could not enable polling page"); } }; @@ -5288,7 +5288,7 @@ static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { snprintf(proc_name, 64, "/proc/self/task/%d/stat", tid); fp = fopen(proc_name, "r"); - if ( fp == NULL ) return -1; + if (fp == NULL) return -1; statlen = fread(stat, 1, 2047, fp); stat[statlen] = '\0'; fclose(fp); @@ -5300,7 +5300,7 @@ static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { // We don't really need to know the command string, just find the last // occurrence of ")" and then start parsing from there. See bug 4726580. s = strrchr(stat, ')'); - if (s == NULL ) return -1; + if (s == NULL) return -1; // Skip blank chars do s++; while (isspace(*s)); @@ -5309,7 +5309,7 @@ static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy, &ldummy, &ldummy, &ldummy, &ldummy, &ldummy, &user_time, &sys_time); - if ( count != 13 ) return -1; + if (count != 13) return -1; if (user_sys_cpu_time) { return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec); } else { @@ -5468,9 +5468,9 @@ static struct timespec* compute_abstime(timespec* abstime, jlong millis) { int os::PlatformEvent::TryPark() { for (;;) { - const int v = _Event ; - guarantee ((v == 0) || (v == 1), "invariant") ; - if (Atomic::cmpxchg (0, &_Event, v) == v) return v ; + const int v = _Event; + guarantee((v == 0) || (v == 1), "invariant"); + if (Atomic::cmpxchg(0, &_Event, v) == v) return v; } } @@ -5478,18 +5478,18 @@ void os::PlatformEvent::park() { // AKA "down()" // Invariant: Only the thread associated with the Event/PlatformEvent // may call park(). // TODO: assert that _Assoc != NULL or _Assoc == Self - int v ; + int v; for (;;) { - v = _Event ; - if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; + v = _Event; + if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; } - guarantee (v >= 0, "invariant") ; + guarantee(v >= 0, "invariant"); if (v == 0) { // Do this the hard way by blocking ... int status = pthread_mutex_lock(_mutex); assert_status(status == 0, status, "mutex_lock"); - guarantee (_nParked == 0, "invariant") ; - ++ _nParked ; + guarantee(_nParked == 0, "invariant"); + ++_nParked; while (_Event < 0) { status = pthread_cond_wait(_cond, _mutex); // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... @@ -5497,28 +5497,28 @@ void os::PlatformEvent::park() { // AKA "down()" if (status == ETIME) { status = EINTR; } assert_status(status == 0 || status == EINTR, status, "cond_wait"); } - -- _nParked ; + --_nParked; - _Event = 0 ; + _Event = 0; status = pthread_mutex_unlock(_mutex); assert_status(status == 0, status, "mutex_unlock"); // Paranoia to ensure our locked and lock-free paths interact // correctly with each other. OrderAccess::fence(); } - guarantee (_Event >= 0, "invariant") ; + guarantee(_Event >= 0, "invariant"); } int os::PlatformEvent::park(jlong millis) { - guarantee (_nParked == 0, "invariant") ; + guarantee(_nParked == 0, "invariant"); - int v ; + int v; for (;;) { - v = _Event ; - if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; + v = _Event; + if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; } - guarantee (v >= 0, "invariant") ; - if (v != 0) return OS_OK ; + guarantee(v >= 0, "invariant"); + if (v != 0) return OS_OK; // We do this the hard way, by blocking the thread. // Consider enforcing a minimum timeout value. @@ -5528,8 +5528,8 @@ int os::PlatformEvent::park(jlong millis) { int ret = OS_TIMEOUT; int status = pthread_mutex_lock(_mutex); assert_status(status == 0, status, "mutex_lock"); - guarantee (_nParked == 0, "invariant") ; - ++_nParked ; + guarantee(_nParked == 0, "invariant"); + ++_nParked; // Object.wait(timo) will return because of // (a) notification @@ -5547,24 +5547,24 @@ int os::PlatformEvent::park(jlong millis) { while (_Event < 0) { status = os::Linux::safe_cond_timedwait(_cond, _mutex, &abst); if (status != 0 && WorkAroundNPTLTimedWaitHang) { - pthread_cond_destroy (_cond); - pthread_cond_init (_cond, os::Linux::condAttr()) ; + pthread_cond_destroy(_cond); + pthread_cond_init(_cond, os::Linux::condAttr()); } assert_status(status == 0 || status == EINTR || status == ETIME || status == ETIMEDOUT, status, "cond_timedwait"); - if (!FilterSpuriousWakeups) break ; // previous semantics - if (status == ETIME || status == ETIMEDOUT) break ; + if (!FilterSpuriousWakeups) break; // previous semantics + if (status == ETIME || status == ETIMEDOUT) break; // We consume and ignore EINTR and spurious wakeups. } - --_nParked ; + --_nParked; if (_Event >= 0) { ret = OS_OK; } - _Event = 0 ; + _Event = 0; status = pthread_mutex_unlock(_mutex); assert_status(status == 0, status, "mutex_unlock"); - assert (_nParked == 0, "invariant") ; + assert(_nParked == 0, "invariant"); // Paranoia to ensure our locked and lock-free paths interact // correctly with each other. OrderAccess::fence(); @@ -5647,7 +5647,7 @@ void os::PlatformEvent::unpark() { */ static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) { - assert (time > 0, "convertTime"); + assert(time > 0, "convertTime"); time_t max_secs = 0; if (!os::supports_monotonic_clock() || isAbsolute) { @@ -5726,7 +5726,7 @@ void Parker::park(bool isAbsolute, jlong time) { // Next, demultiplex/decode time arguments timespec absTime; - if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all + if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all return; } if (time > 0) { @@ -5748,11 +5748,11 @@ void Parker::park(bool isAbsolute, jlong time) { return; } - int status ; + int status; if (_counter > 0) { // no wait needed _counter = 0; status = pthread_mutex_unlock(_mutex); - assert (status == 0, "invariant") ; + assert(status == 0, "invariant"); // Paranoia to ensure our locked and lock-free paths interact // correctly with each other and Java-level accesses. OrderAccess::fence(); @@ -5774,13 +5774,13 @@ void Parker::park(bool isAbsolute, jlong time) { assert(_cur_index == -1, "invariant"); if (time == 0) { _cur_index = REL_INDEX; // arbitrary choice when not timed - status = pthread_cond_wait (&_cond[_cur_index], _mutex) ; + status = pthread_cond_wait(&_cond[_cur_index], _mutex); } else { _cur_index = isAbsolute ? ABS_INDEX : REL_INDEX; - status = os::Linux::safe_cond_timedwait (&_cond[_cur_index], _mutex, &absTime) ; + status = os::Linux::safe_cond_timedwait(&_cond[_cur_index], _mutex, &absTime); if (status != 0 && WorkAroundNPTLTimedWaitHang) { - pthread_cond_destroy (&_cond[_cur_index]) ; - pthread_cond_init (&_cond[_cur_index], isAbsolute ? NULL : os::Linux::condAttr()); + pthread_cond_destroy(&_cond[_cur_index]); + pthread_cond_init(&_cond[_cur_index], isAbsolute ? NULL : os::Linux::condAttr()); } } _cur_index = -1; @@ -5792,9 +5792,9 @@ void Parker::park(bool isAbsolute, jlong time) { pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); #endif - _counter = 0 ; - status = pthread_mutex_unlock(_mutex) ; - assert_status(status == 0, status, "invariant") ; + _counter = 0; + status = pthread_mutex_unlock(_mutex); + assert_status(status == 0, status, "invariant"); // Paranoia to ensure our locked and lock-free paths interact // correctly with each other and Java-level accesses. OrderAccess::fence(); @@ -5806,9 +5806,9 @@ void Parker::park(bool isAbsolute, jlong time) { } void Parker::unpark() { - int s, status ; + int s, status; status = pthread_mutex_lock(_mutex); - assert (status == 0, "invariant") ; + assert(status == 0, "invariant"); s = _counter; _counter = 1; if (s < 1) { @@ -5817,22 +5817,22 @@ void Parker::unpark() { // thread is definitely parked if (WorkAroundNPTLTimedWaitHang) { status = pthread_cond_signal (&_cond[_cur_index]); - assert (status == 0, "invariant"); + assert(status == 0, "invariant"); status = pthread_mutex_unlock(_mutex); - assert (status == 0, "invariant"); + assert(status == 0, "invariant"); } else { status = pthread_mutex_unlock(_mutex); - assert (status == 0, "invariant"); + assert(status == 0, "invariant"); status = pthread_cond_signal (&_cond[_cur_index]); - assert (status == 0, "invariant"); + assert(status == 0, "invariant"); } } else { pthread_mutex_unlock(_mutex); - assert (status == 0, "invariant") ; + assert(status == 0, "invariant"); } } else { pthread_mutex_unlock(_mutex); - assert (status == 0, "invariant") ; + assert(status == 0, "invariant"); } } diff --git a/hotspot/src/os/linux/vm/os_linux.hpp b/hotspot/src/os/linux/vm/os_linux.hpp index 2dfda6be0cf..3e287387b05 100644 --- a/hotspot/src/os/linux/vm/os_linux.hpp +++ b/hotspot/src/os/linux/vm/os_linux.hpp @@ -287,16 +287,16 @@ public: class PlatformEvent : public CHeapObj { private: - double CachePad [4] ; // increase odds that _mutex is sole occupant of cache line - volatile int _Event ; - volatile int _nParked ; - pthread_mutex_t _mutex [1] ; - pthread_cond_t _cond [1] ; - double PostPad [2] ; - Thread * _Assoc ; + double CachePad[4]; // increase odds that _mutex is sole occupant of cache line + volatile int _Event; + volatile int _nParked; + pthread_mutex_t _mutex[1]; + pthread_cond_t _cond[1]; + double PostPad[2]; + Thread * _Assoc; public: // TODO-FIXME: make dtor private - ~PlatformEvent() { guarantee (0, "invariant") ; } + ~PlatformEvent() { guarantee(0, "invariant"); } public: PlatformEvent() { @@ -305,20 +305,20 @@ class PlatformEvent : public CHeapObj { assert_status(status == 0, status, "cond_init"); status = pthread_mutex_init (_mutex, NULL); assert_status(status == 0, status, "mutex_init"); - _Event = 0 ; - _nParked = 0 ; - _Assoc = NULL ; + _Event = 0; + _nParked = 0; + _Assoc = NULL; } // Use caution with reset() and fired() -- they may require MEMBARs - void reset() { _Event = 0 ; } + void reset() { _Event = 0; } int fired() { return _Event; } - void park () ; - void unpark () ; - int TryPark () ; - int park (jlong millis) ; // relative timed-wait only - void SetAssociation (Thread * a) { _Assoc = a ; } -} ; + void park(); + void unpark(); + int TryPark(); + int park(jlong millis); // relative timed-wait only + void SetAssociation(Thread * a) { _Assoc = a; } +}; class PlatformParker : public CHeapObj { protected: @@ -327,11 +327,11 @@ class PlatformParker : public CHeapObj { ABS_INDEX = 1 }; int _cur_index; // which cond is in use: -1, 0, 1 - pthread_mutex_t _mutex [1] ; - pthread_cond_t _cond [2] ; // one for relative times and one for abs. + pthread_mutex_t _mutex[1]; + pthread_cond_t _cond[2]; // one for relative times and one for abs. public: // TODO-FIXME: make dtor private - ~PlatformParker() { guarantee (0, "invariant") ; } + ~PlatformParker() { guarantee(0, "invariant"); } public: PlatformParker() { diff --git a/hotspot/src/os/solaris/vm/os_solaris.cpp b/hotspot/src/os/solaris/vm/os_solaris.cpp index 5272029561b..77cc8abb192 100644 --- a/hotspot/src/os/solaris/vm/os_solaris.cpp +++ b/hotspot/src/os/solaris/vm/os_solaris.cpp @@ -212,13 +212,13 @@ Thread* ThreadLocalStorage::get_thread_via_cache_slowly(uintptr_t raw_id, "sp must be inside of selected thread stack"); thread->set_self_raw_id(raw_id); // mark for quick retrieval - _get_thread_cache[ index ] = thread; + _get_thread_cache[index] = thread; } return thread; } -static const double all_zero[ sizeof(Thread) / sizeof(double) + 1 ] = {0}; +static const double all_zero[sizeof(Thread) / sizeof(double) + 1] = {0}; #define NO_CACHED_THREAD ((Thread*)all_zero) void ThreadLocalStorage::pd_set_thread(Thread* thread) { @@ -270,8 +270,8 @@ static inline stack_t get_stack_info() { } address os::current_stack_base() { - int r = thr_main() ; - guarantee (r == 0 || r == 1, "CR6501650 or CR6493689") ; + int r = thr_main(); + guarantee(r == 0 || r == 1, "CR6501650 or CR6493689"); bool is_primordial_thread = r; // Workaround 4352906, avoid calls to thr_stksegment by @@ -293,9 +293,9 @@ address os::current_stack_base() { size_t os::current_stack_size() { size_t size; - int r = thr_main() ; - guarantee (r == 0 || r == 1, "CR6501650 or CR6493689") ; - if(!r) { + int r = thr_main(); + guarantee(r == 0 || r == 1, "CR6501650 or CR6493689"); + if (!r) { size = get_stack_info().ss_size; } else { struct rlimit limits; @@ -409,7 +409,7 @@ static bool find_processors_in_pset(psetid_t pset, static bool find_processors_online(processorid_t** id_array, uint* id_length) { - const processorid_t MAX_PROCESSOR_ID = 100000 ; + const processorid_t MAX_PROCESSOR_ID = 100000; // Find the number of processors online. *id_length = sysconf(_SC_NPROCESSORS_ONLN); // Make up an array to hold their ids. @@ -436,7 +436,7 @@ static bool find_processors_online(processorid_t** id_array, // we've got. Note that in the worst case find_processors_online() could // return an empty set. (As a fall-back in the case of the empty set we // could just return the ID of the current processor). - *id_length = found ; + *id_length = found; } return true; @@ -552,13 +552,13 @@ bool os::bind_to_processor(uint processor_id) { } bool os::getenv(const char* name, char* buffer, int len) { - char* val = ::getenv( name ); - if ( val == NULL + char* val = ::getenv(name); + if (val == NULL || strlen(val) + 1 > len ) { if (len > 0) buffer[0] = 0; // return a null string return false; } - strcpy( buffer, val ); + strcpy(buffer, val); return true; } @@ -672,7 +672,7 @@ void os::init_system_properties_values() { // Determine search path count and required buffer size. if (dlinfo(RTLD_SELF, RTLD_DI_SERINFOSIZE, (void *)info) == -1) { - FREE_C_HEAP_ARRAY(char, buf, mtInternal); + FREE_C_HEAP_ARRAY(char, buf, mtInternal); vm_exit_during_initialization("dlinfo SERINFOSIZE request", dlerror()); } @@ -683,7 +683,7 @@ void os::init_system_properties_values() { // Obtain search path information. if (dlinfo(RTLD_SELF, RTLD_DI_SERINFO, (void *)info) == -1) { - FREE_C_HEAP_ARRAY(char, buf, mtInternal); + FREE_C_HEAP_ARRAY(char, buf, mtInternal); FREE_C_HEAP_ARRAY(char, info, mtInternal); vm_exit_during_initialization("dlinfo SERINFO request", dlerror()); } @@ -794,7 +794,7 @@ bool os::obsolete_option(const JavaVMOption *option) bool os::Solaris::valid_stack_address(Thread* thread, address sp) { address stackStart = (address)thread->stack_base(); address stackEnd = (address)(stackStart - (address)thread->stack_size()); - if (sp < stackStart && sp >= stackEnd ) return true; + if (sp < stackStart && sp >= stackEnd) return true; return false; } @@ -819,8 +819,8 @@ extern "C" void* java_start(void* thread_addr) { Thread* thread = (Thread*)thread_addr; OSThread* osthr = thread->osthread(); - osthr->set_lwp_id( _lwp_self() ); // Store lwp in case we are bound - thread->_schedctl = (void *) schedctl_init () ; + osthr->set_lwp_id(_lwp_self()); // Store lwp in case we are bound + thread->_schedctl = (void *) schedctl_init(); if (UseNUMA) { int lgrp_id = os::numa_get_group_id(); @@ -839,8 +839,8 @@ extern "C" void* java_start(void* thread_addr) { // in java_to_os_priority. So we save the native priority // in the osThread and recall it here. - if ( osthr->thread_id() != -1 ) { - if ( UseThreadPriorities ) { + if (osthr->thread_id() != -1) { + if (UseThreadPriorities) { int prio = osthr->native_priority(); if (ThreadPriorityVerbose) { tty->print_cr("Starting Thread " INTPTR_FORMAT ", LWP is " @@ -882,7 +882,7 @@ static OSThread* create_os_thread(Thread* thread, thread_t thread_id) { // Store info on the Solaris thread into the OSThread osthread->set_thread_id(thread_id); osthread->set_lwp_id(_lwp_self()); - thread->_schedctl = (void *) schedctl_init () ; + thread->_schedctl = (void *) schedctl_init(); if (UseNUMA) { int lgrp_id = os::numa_get_group_id(); @@ -891,9 +891,9 @@ static OSThread* create_os_thread(Thread* thread, thread_t thread_id) { } } - if ( ThreadPriorityVerbose ) { + if (ThreadPriorityVerbose) { tty->print_cr("In create_os_thread, Thread " INTPTR_FORMAT ", LWP is " INTPTR_FORMAT "\n", - osthread->thread_id(), osthread->lwp_id() ); + osthread->thread_id(), osthread->lwp_id()); } // Initial thread state is INITIALIZED, not SUSPENDED @@ -974,9 +974,9 @@ bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { return false; } - if ( ThreadPriorityVerbose ) { + if (ThreadPriorityVerbose) { char *thrtyp; - switch ( thr_type ) { + switch (thr_type) { case vm_thread: thrtyp = (char *)"vm"; break; @@ -1207,11 +1207,11 @@ void _handle_uncaught_cxx_exception() { // First crack at OS-specific initialization, from inside the new thread. void os::initialize_thread(Thread* thr) { - int r = thr_main() ; - guarantee (r == 0 || r == 1, "CR6501650 or CR6493689") ; + int r = thr_main(); + guarantee(r == 0 || r == 1, "CR6501650 or CR6493689"); if (r) { JavaThread* jt = (JavaThread *)thr; - assert(jt != NULL,"Sanity check"); + assert(jt != NULL, "Sanity check"); size_t stack_size; address base = jt->stack_base(); if (Arguments::created_by_java_launcher()) { @@ -1322,7 +1322,7 @@ int os::allocate_thread_local_storage() { // JavaThread in Java code, and have stubs simply // treat %g2 as a caller-save register, preserving it in a %lN. thread_key_t tk; - if (thr_keycreate( &tk, NULL ) ) + if (thr_keycreate( &tk, NULL)) fatal(err_msg("os::allocate_thread_local_storage: thr_keycreate failed " "(%s)", strerror(errno))); return int(tk); @@ -1347,7 +1347,7 @@ void os::thread_local_storage_at_put(int index, void* value) { "(%s)", strerror(errno))); } } else { - ThreadLocalStorage::set_thread_in_slot ((Thread *) value) ; + ThreadLocalStorage::set_thread_in_slot((Thread *) value); } } @@ -1579,7 +1579,7 @@ bool os::dll_build_name(char* buffer, size_t buflen, if (pelements == NULL) { return false; } - for (int i = 0 ; i < n ; i++) { + for (int i = 0; i < n; i++) { // really shouldn't be NULL but what the heck, check can't hurt if (pelements[i] == NULL || strlen(pelements[i]) == 0) { continue; // skip the empty path values @@ -1591,7 +1591,7 @@ bool os::dll_build_name(char* buffer, size_t buflen, } } // release the storage - for (int i = 0 ; i < n ; i++) { + for (int i = 0; i < n; i++) { if (pelements[i] != NULL) { FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal); } @@ -1795,7 +1795,7 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) bool failed_to_read_elf_head= (sizeof(elf_head)!= - (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ; + (::read(file_descriptor, &elf_head,sizeof(elf_head)))); ::close(file_descriptor); if (failed_to_read_elf_head) { @@ -1851,7 +1851,7 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; int running_arch_index=-1; - for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) { + for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) { if (running_arch_code == arch_array[i].code) { running_arch_index = i; } @@ -1880,7 +1880,7 @@ void * os::dll_load(const char *filename, char *ebuf, int ebuflen) } if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { - if ( lib_arch.name!=NULL ) { + if (lib_arch.name!=NULL) { ::snprintf(diag_msg_buf, diag_msg_max_length-1, " (Possible cause: can't load %s-bit .so on a %s-bit platform)", lib_arch.name, arch_array[running_arch_index].name); @@ -1969,7 +1969,7 @@ static bool check_addr0(outputStream* st) { int fd = ::open("/proc/self/map",O_RDONLY); if (fd >= 0) { prmap_t p; - while(::read(fd, &p, sizeof(p)) > 0) { + while (::read(fd, &p, sizeof(p)) > 0) { if (p.pr_vaddr == 0x0) { st->print("Warning: Address: 0x%x, Size: %dK, ",p.pr_vaddr, p.pr_size/1024, p.pr_mapname); st->print("Mapped file: %s, ", p.pr_mapname[0] == '\0' ? "None" : p.pr_mapname); @@ -2079,7 +2079,7 @@ static void print_signal_handler(outputStream* st, int sig, address rh = VMError::get_resetted_sighandler(sig); // May be, handler was resetted by VMError? - if(rh != NULL) { + if (rh != NULL) { handler = rh; sa.sa_flags = VMError::get_resetted_sigflags(sig); } @@ -2088,11 +2088,11 @@ static void print_signal_handler(outputStream* st, int sig, os::Posix::print_sa_flags(st, sa.sa_flags); // Check: is it our handler? - if(handler == CAST_FROM_FN_PTR(address, signalHandler) || + if (handler == CAST_FROM_FN_PTR(address, signalHandler) || handler == CAST_FROM_FN_PTR(address, sigINTRHandler)) { // It is our signal handler // check for flags - if(sa.sa_flags != os::Solaris::get_our_sigflags(sig)) { + if (sa.sa_flags != os::Solaris::get_our_sigflags(sig)) { st->print( ", flags was changed from " PTR32_FORMAT ", consider using jsig library", os::Solaris::get_our_sigflags(sig)); @@ -2403,7 +2403,7 @@ static int check_pending_signals(bool wait_for_signal) { do { thread->set_suspend_equivalent(); // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() - while((ret = ::sema_wait(&sig_sem)) == EINTR) + while ((ret = ::sema_wait(&sig_sem)) == EINTR) ; assert(ret == 0, "sema_wait() failed"); @@ -2635,7 +2635,7 @@ size_t os::numa_get_leaf_groups(int *ids, size_t size) { } if (!r) { // That's a leaf node. - assert (bottom <= cur, "Sanity check"); + assert(bottom <= cur, "Sanity check"); // Check if the node has memory if (Solaris::lgrp_resources(Solaris::lgrp_cookie(), ids[cur], NULL, 0, LGRP_RSRC_MEM) > 0) { @@ -3051,7 +3051,7 @@ bool os::Solaris::mpss_sanity_check(bool warn, size_t* page_size) { const size_t size_limit = FLAG_IS_DEFAULT(LargePageSizeInBytes) ? 4 * M : LargePageSizeInBytes; int beg; - for (beg = 0; beg < n && _page_sizes[beg] > size_limit; ++beg) /* empty */ ; + for (beg = 0; beg < n && _page_sizes[beg] > size_limit; ++beg) /* empty */; const int end = MIN2((int)usable_count, n) - 1; for (int cur = 0; cur < end; ++cur, ++beg) { _page_sizes[cur] = _page_sizes[beg]; @@ -3264,7 +3264,7 @@ static int java_MaxPriority_to_os_priority = 0; // Saved mapping // // Return errno or 0 if OK. // -static int lwp_priocntl_init () { +static int lwp_priocntl_init() { int rslt; pcinfo_t ClassInfo; pcparms_t ParmInfo; @@ -3274,7 +3274,7 @@ static int lwp_priocntl_init () { // If ThreadPriorityPolicy is 1, switch tables if (ThreadPriorityPolicy == 1) { - for (i = 0 ; i < CriticalPriority+1; i++) + for (i = 0; i < CriticalPriority+1; i++) os::java_to_os_priority[i] = prio_policy1[i]; } if (UseCriticalJavaThreadPriority) { @@ -3373,12 +3373,12 @@ static int lwp_priocntl_init () { } else { // No clue - punt if (ThreadPriorityVerbose) - tty->print_cr ("Unknown scheduling class: %s ... \n", ClassInfo.pc_clname); + tty->print_cr("Unknown scheduling class: %s ... \n", ClassInfo.pc_clname); return EINVAL; // no clue, punt } if (ThreadPriorityVerbose) { - tty->print_cr ("Thread priority Range: [%d..%d]\n", myMin, myMax); + tty->print_cr("Thread priority Range: [%d..%d]\n", myMin, myMax); } priocntl_enable = true; // Enable changing priorities @@ -3424,7 +3424,7 @@ int set_lwp_class_and_priority(int ThreadID, int lwpid, // TODO: elide set-to-same-value // If something went wrong on init, don't change priorities. - if ( !priocntl_enable ) { + if (!priocntl_enable) { if (ThreadPriorityVerbose) tty->print_cr("Trying to set priority but init failed, ignoring"); return EINVAL; @@ -3432,9 +3432,9 @@ int set_lwp_class_and_priority(int ThreadID, int lwpid, // If lwp hasn't started yet, just return // the _start routine will call us again. - if ( lwpid <= 0 ) { + if (lwpid <= 0) { if (ThreadPriorityVerbose) { - tty->print_cr ("deferring the set_lwp_class_and_priority of thread " + tty->print_cr("deferring the set_lwp_class_and_priority of thread " INTPTR_FORMAT " to %d, lwpid not set", ThreadID, newPrio); } @@ -3653,7 +3653,7 @@ OSReturn os::set_native_priority(Thread* thread, int newpri) { OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) { int p; - if ( !UseThreadPriorities ) { + if (!UseThreadPriorities) { *priority_ptr = NormalPriority; return OS_OK; } @@ -4099,7 +4099,7 @@ void os::Solaris::set_signal_handler(int sig, bool set_installed, bool oktochain void os::run_periodic_checks() { // A big source of grief is hijacking virt. addr 0x0 on Solaris, // thereby preventing a NULL checks. - if(!check_addr0_done) check_addr0_done = check_addr0(tty); + if (!check_addr0_done) check_addr0_done = check_addr0(tty); if (check_signals == false) return; @@ -4148,10 +4148,10 @@ void os::Solaris::check_signal_handler(int sig) { address thisHandler = (act.sa_flags & SA_SIGINFO) ? CAST_FROM_FN_PTR(address, act.sa_sigaction) - : CAST_FROM_FN_PTR(address, act.sa_handler) ; + : CAST_FROM_FN_PTR(address, act.sa_handler); - switch(sig) { + switch (sig) { case SIGSEGV: case SIGBUS: case SIGFPE: @@ -4332,7 +4332,7 @@ os::Solaris::meminfo_func_t os::Solaris::_meminfo = 0; static address resolve_symbol_lazy(const char* name) { address addr = (address) dlsym(RTLD_DEFAULT, name); - if(addr == NULL) { + if (addr == NULL) { // RTLD_DEFAULT was not defined on some early versions of 2.5.1 addr = (address) dlsym(RTLD_NEXT, name); } @@ -4341,7 +4341,7 @@ static address resolve_symbol_lazy(const char* name) { static address resolve_symbol(const char* name) { address addr = resolve_symbol_lazy(name); - if(addr == NULL) { + if (addr == NULL) { fatal(dlerror()); } return addr; @@ -4353,7 +4353,7 @@ void os::Solaris::libthread_init() { lwp_priocntl_init(); // RTLD_DEFAULT was not defined on some early versions of 5.5.1 - if(func == NULL) { + if (func == NULL) { func = (address) dlsym(RTLD_NEXT, "_thr_suspend_allmutators"); // Guarantee that this VM is running on an new enough OS (5.6 or // later) that it will have a new enough libthread.so. @@ -4384,7 +4384,7 @@ int_fnP_cond_tP os::Solaris::_cond_destroy; int os::Solaris::_cond_scope = USYNC_THREAD; void os::Solaris::synchronization_init() { - if(UseLWPSynchronization) { + if (UseLWPSynchronization) { os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_lock"))); os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_trylock"))); os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_unlock"))); @@ -4404,7 +4404,7 @@ void os::Solaris::synchronization_init() { os::Solaris::set_mutex_scope(USYNC_THREAD); os::Solaris::set_cond_scope(USYNC_THREAD); - if(UsePthreads) { + if (UsePthreads) { os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_lock"))); os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_trylock"))); os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_unlock"))); @@ -4576,17 +4576,17 @@ jint os::init_2(void) { os::set_polling_page(polling_page); #ifndef PRODUCT - if( Verbose && PrintMiscellaneous ) + if (Verbose && PrintMiscellaneous) tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page); #endif if (!UseMembar) { - address mem_serialize_page = (address)Solaris::mmap_chunk( NULL, page_size, MAP_PRIVATE, PROT_READ | PROT_WRITE ); - guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page"); - os::set_memory_serialize_page( mem_serialize_page ); + address mem_serialize_page = (address)Solaris::mmap_chunk(NULL, page_size, MAP_PRIVATE, PROT_READ | PROT_WRITE); + guarantee(mem_serialize_page != NULL, "mmap Failed for memory serialize page"); + os::set_memory_serialize_page(mem_serialize_page); #ifndef PRODUCT - if(Verbose && PrintMiscellaneous) + if (Verbose && PrintMiscellaneous) tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); #endif } @@ -4725,13 +4725,13 @@ void os::init_3(void) { // Mark the polling page as unreadable void os::make_polling_page_unreadable(void) { - if( mprotect((char *)_polling_page, page_size, PROT_NONE) != 0 ) + if (mprotect((char *)_polling_page, page_size, PROT_NONE) != 0) fatal("Could not disable polling page"); }; // Mark the polling page as readable void os::make_polling_page_readable(void) { - if( mprotect((char *)_polling_page, page_size, PROT_READ) != 0 ) + if (mprotect((char *)_polling_page, page_size, PROT_READ) != 0) fatal("Could not enable polling page"); }; @@ -5221,7 +5221,7 @@ jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { getpid(), thread->osthread()->lwp_id()); fd = ::open(proc_name, O_RDONLY); - if ( fd == -1 ) return -1; + if (fd == -1) return -1; do { count = ::pread(fd, @@ -5230,7 +5230,7 @@ jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { thr_time_off); } while (count < 0 && errno == EINTR); ::close(fd); - if ( count < 0 ) return -1; + if (count < 0) return -1; if (user_sys_cpu_time) { // user + system CPU time @@ -5244,7 +5244,7 @@ jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { (jlong)prusage.pr_utime.tv_nsec; } - return(lwp_time); + return (lwp_time); } void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { @@ -5448,43 +5448,43 @@ static timestruc_t* compute_abstime(timestruc_t* abstime, jlong millis) { int os::PlatformEvent::TryPark() { for (;;) { - const int v = _Event ; - guarantee ((v == 0) || (v == 1), "invariant") ; - if (Atomic::cmpxchg (0, &_Event, v) == v) return v ; + const int v = _Event; + guarantee((v == 0) || (v == 1), "invariant"); + if (Atomic::cmpxchg(0, &_Event, v) == v) return v; } } void os::PlatformEvent::park() { // AKA: down() // Invariant: Only the thread associated with the Event/PlatformEvent // may call park(). - int v ; + int v; for (;;) { - v = _Event ; - if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; + v = _Event; + if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; } - guarantee (v >= 0, "invariant") ; + guarantee(v >= 0, "invariant"); if (v == 0) { // Do this the hard way by blocking ... // See http://monaco.sfbay/detail.jsf?cr=5094058. // TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking. // Only for SPARC >= V8PlusA #if defined(__sparc) && defined(COMPILER2) - if (ClearFPUAtPark) { _mark_fpu_nosave() ; } + if (ClearFPUAtPark) { _mark_fpu_nosave(); } #endif int status = os::Solaris::mutex_lock(_mutex); - assert_status(status == 0, status, "mutex_lock"); - guarantee (_nParked == 0, "invariant") ; - ++ _nParked ; + assert_status(status == 0, status, "mutex_lock"); + guarantee(_nParked == 0, "invariant"); + ++_nParked; while (_Event < 0) { // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... // Treat this the same as if the wait was interrupted // With usr/lib/lwp going to kernel, always handle ETIME status = os::Solaris::cond_wait(_cond, _mutex); - if (status == ETIME) status = EINTR ; + if (status == ETIME) status = EINTR; assert_status(status == 0 || status == EINTR, status, "cond_wait"); } - -- _nParked ; - _Event = 0 ; + --_nParked; + _Event = 0; status = os::Solaris::mutex_unlock(_mutex); assert_status(status == 0, status, "mutex_unlock"); // Paranoia to ensure our locked and lock-free paths interact @@ -5494,41 +5494,41 @@ void os::PlatformEvent::park() { // AKA: down() } int os::PlatformEvent::park(jlong millis) { - guarantee (_nParked == 0, "invariant") ; - int v ; + guarantee(_nParked == 0, "invariant"); + int v; for (;;) { - v = _Event ; - if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; + v = _Event; + if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; } - guarantee (v >= 0, "invariant") ; - if (v != 0) return OS_OK ; + guarantee(v >= 0, "invariant"); + if (v != 0) return OS_OK; int ret = OS_TIMEOUT; timestruc_t abst; - compute_abstime (&abst, millis); + compute_abstime(&abst, millis); // See http://monaco.sfbay/detail.jsf?cr=5094058. // For Solaris SPARC set fprs.FEF=0 prior to parking. // Only for SPARC >= V8PlusA #if defined(__sparc) && defined(COMPILER2) - if (ClearFPUAtPark) { _mark_fpu_nosave() ; } + if (ClearFPUAtPark) { _mark_fpu_nosave(); } #endif int status = os::Solaris::mutex_lock(_mutex); assert_status(status == 0, status, "mutex_lock"); - guarantee (_nParked == 0, "invariant") ; - ++ _nParked ; + guarantee(_nParked == 0, "invariant"); + ++_nParked; while (_Event < 0) { int status = os::Solaris::cond_timedwait(_cond, _mutex, &abst); assert_status(status == 0 || status == EINTR || status == ETIME || status == ETIMEDOUT, status, "cond_timedwait"); - if (!FilterSpuriousWakeups) break ; // previous semantics - if (status == ETIME || status == ETIMEDOUT) break ; + if (!FilterSpuriousWakeups) break; // previous semantics + if (status == ETIME || status == ETIMEDOUT) break; // We consume and ignore EINTR and spurious wakeups. } - -- _nParked ; - if (_Event >= 0) ret = OS_OK ; - _Event = 0 ; + --_nParked; + if (_Event >= 0) ret = OS_OK; + _Event = 0; status = os::Solaris::mutex_unlock(_mutex); assert_status(status == 0, status, "mutex_unlock"); // Paranoia to ensure our locked and lock-free paths interact @@ -5605,7 +5605,7 @@ void os::PlatformEvent::unpark() { * years from "now". */ static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) { - assert (time > 0, "convertTime"); + assert(time > 0, "convertTime"); struct timeval now; int status = gettimeofday(&now, NULL); @@ -5664,7 +5664,7 @@ void Parker::park(bool isAbsolute, jlong time) { // First, demultiplex/decode time arguments timespec absTime; - if (time < 0 || (isAbsolute && time == 0) ) { // don't wait at all + if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all return; } if (time > 0) { @@ -5688,12 +5688,12 @@ void Parker::park(bool isAbsolute, jlong time) { return; } - int status ; + int status; if (_counter > 0) { // no wait needed _counter = 0; status = os::Solaris::mutex_unlock(_mutex); - assert (status == 0, "invariant") ; + assert(status == 0, "invariant"); // Paranoia to ensure our locked and lock-free paths interact // correctly with each other and Java-level accesses. OrderAccess::fence(); @@ -5717,11 +5717,11 @@ void Parker::park(bool isAbsolute, jlong time) { // TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking. // Only for SPARC >= V8PlusA #if defined(__sparc) && defined(COMPILER2) - if (ClearFPUAtPark) { _mark_fpu_nosave() ; } + if (ClearFPUAtPark) { _mark_fpu_nosave(); } #endif if (time == 0) { - status = os::Solaris::cond_wait (_cond, _mutex) ; + status = os::Solaris::cond_wait(_cond, _mutex); } else { status = os::Solaris::cond_timedwait (_cond, _mutex, &absTime); } @@ -5734,9 +5734,9 @@ void Parker::park(bool isAbsolute, jlong time) { #ifdef ASSERT thr_sigsetmask(SIG_SETMASK, &oldsigs, NULL); #endif - _counter = 0 ; + _counter = 0; status = os::Solaris::mutex_unlock(_mutex); - assert_status(status == 0, status, "mutex_unlock") ; + assert_status(status == 0, status, "mutex_unlock"); // Paranoia to ensure our locked and lock-free paths interact // correctly with each other and Java-level accesses. OrderAccess::fence(); @@ -5748,17 +5748,17 @@ void Parker::park(bool isAbsolute, jlong time) { } void Parker::unpark() { - int s, status ; - status = os::Solaris::mutex_lock (_mutex) ; - assert (status == 0, "invariant") ; + int s, status; + status = os::Solaris::mutex_lock(_mutex); + assert(status == 0, "invariant"); s = _counter; _counter = 1; - status = os::Solaris::mutex_unlock (_mutex) ; - assert (status == 0, "invariant") ; + status = os::Solaris::mutex_unlock(_mutex); + assert(status == 0, "invariant"); if (s < 1) { - status = os::Solaris::cond_signal (_cond) ; - assert (status == 0, "invariant") ; + status = os::Solaris::cond_signal(_cond); + assert(status == 0, "invariant"); } } @@ -5925,14 +5925,14 @@ int os::timeout(int fd, long timeout) { gettimeofday(&t, &aNull); prevtime = ((julong)t.tv_sec * 1000) + t.tv_usec / 1000; - for(;;) { + for (;;) { res = ::poll(&pfd, 1, timeout); - if(res == OS_ERR && errno == EINTR) { - if(timeout != -1) { + if (res == OS_ERR && errno == EINTR) { + if (timeout != -1) { gettimeofday(&t, &aNull); newtime = ((julong)t.tv_sec * 1000) + t.tv_usec /1000; timeout -= newtime - prevtime; - if(timeout <= 0) + if (timeout <= 0) return OS_OK; prevtime = newtime; } diff --git a/hotspot/src/os/solaris/vm/os_solaris.hpp b/hotspot/src/os/solaris/vm/os_solaris.hpp index 7c5bedb4d41..28d1700ca62 100644 --- a/hotspot/src/os/solaris/vm/os_solaris.hpp +++ b/hotspot/src/os/solaris/vm/os_solaris.hpp @@ -301,48 +301,48 @@ class Solaris { class PlatformEvent : public CHeapObj { private: - double CachePad [4] ; // increase odds that _mutex is sole occupant of cache line - volatile int _Event ; - int _nParked ; - int _pipev [2] ; - mutex_t _mutex [1] ; - cond_t _cond [1] ; - double PostPad [2] ; + double CachePad[4]; // increase odds that _mutex is sole occupant of cache line + volatile int _Event; + int _nParked; + int _pipev[2]; + mutex_t _mutex[1]; + cond_t _cond[1]; + double PostPad[2]; protected: // Defining a protected ctor effectively gives us an abstract base class. // That is, a PlatformEvent can never be instantiated "naked" but only // as a part of a ParkEvent (recall that ParkEvent extends PlatformEvent). // TODO-FIXME: make dtor private - ~PlatformEvent() { guarantee (0, "invariant") ; } + ~PlatformEvent() { guarantee(0, "invariant"); } PlatformEvent() { int status; status = os::Solaris::cond_init(_cond); assert_status(status == 0, status, "cond_init"); status = os::Solaris::mutex_init(_mutex); assert_status(status == 0, status, "mutex_init"); - _Event = 0 ; - _nParked = 0 ; - _pipev[0] = _pipev[1] = -1 ; + _Event = 0; + _nParked = 0; + _pipev[0] = _pipev[1] = -1; } public: // Exercise caution using reset() and fired() -- they may require MEMBARs - void reset() { _Event = 0 ; } + void reset() { _Event = 0; } int fired() { return _Event; } - void park () ; - int park (jlong millis) ; - int TryPark () ; - void unpark () ; -} ; + void park(); + int park(jlong millis); + int TryPark(); + void unpark(); +}; class PlatformParker : public CHeapObj { protected: - mutex_t _mutex [1] ; - cond_t _cond [1] ; + mutex_t _mutex[1]; + cond_t _cond[1]; public: // TODO-FIXME: make dtor private - ~PlatformParker() { guarantee (0, "invariant") ; } + ~PlatformParker() { guarantee(0, "invariant"); } public: PlatformParker() { @@ -352,6 +352,6 @@ class PlatformParker : public CHeapObj { status = os::Solaris::mutex_init(_mutex); assert_status(status == 0, status, "mutex_init"); } -} ; +}; #endif // OS_SOLARIS_VM_OS_SOLARIS_HPP diff --git a/hotspot/src/os/windows/vm/os_windows.cpp b/hotspot/src/os/windows/vm/os_windows.cpp index 04b72a9d37d..e3ca08a747e 100644 --- a/hotspot/src/os/windows/vm/os_windows.cpp +++ b/hotspot/src/os/windows/vm/os_windows.cpp @@ -125,11 +125,11 @@ BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID reserved) { switch (reason) { case DLL_PROCESS_ATTACH: vm_lib_handle = hinst; - if(ForceTimeHighResolution) + if (ForceTimeHighResolution) timeBeginPeriod(1L); break; case DLL_PROCESS_DETACH: - if(ForceTimeHighResolution) + if (ForceTimeHighResolution) timeEndPeriod(1L); // Workaround for issue when a custom launcher doesn't call @@ -318,7 +318,7 @@ extern "C" void breakpoint() { */ address os::get_caller_pc(int n) { #ifdef _NMT_NOINLINE_ - n ++; + n++; #endif address pc; if (os::Kernel32Dll::RtlCaptureStackBackTrace(n + 1, 1, (PVOID*)&pc, NULL) == 1) { @@ -345,10 +345,10 @@ address os::current_stack_base() { // Add up the sizes of all the regions with the same // AllocationBase. - while( 1 ) + while (1) { VirtualQuery(stack_bottom+stack_size, &minfo, sizeof(minfo)); - if ( stack_bottom == (address)minfo.AllocationBase ) + if (stack_bottom == (address)minfo.AllocationBase) stack_size += minfo.RegionSize; else break; @@ -644,7 +644,7 @@ static jlong performance_frequency; jlong as_long(LARGE_INTEGER x) { jlong result = 0; // initialization to avoid warning set_high(&result, x.HighPart); - set_low(&result, x.LowPart); + set_low(&result, x.LowPart); return result; } @@ -999,7 +999,7 @@ void os::check_or_create_dump(void* exceptionRecord, void* contextRecord, char* #endif cwd = get_current_directory(NULL, 0); - jio_snprintf(buffer, bufferSize, "%s\\hs_err_pid%u.mdmp",cwd, current_process_id()); + jio_snprintf(buffer, bufferSize, "%s\\hs_err_pid%u.mdmp", cwd, current_process_id()); dumpFile = CreateFile(buffer, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (dumpFile == INVALID_HANDLE_VALUE) { @@ -1217,7 +1217,7 @@ bool os::dll_build_name(char *buffer, size_t buflen, if (pelements == NULL) { return false; } - for (int i = 0 ; i < n ; i++) { + for (int i = 0; i < n; i++) { char* path = pelements[i]; // Really shouldn't be NULL, but check can't hurt size_t plen = (path == NULL) ? 0 : strlen(path); @@ -1236,7 +1236,7 @@ bool os::dll_build_name(char *buffer, size_t buflen, } } // release the storage - for (int i = 0 ; i < n ; i++) { + for (int i = 0; i < n; i++) { if (pelements[i] != NULL) { FREE_C_HEAP_ARRAY(char, pelements[i], mtInternal); } @@ -1271,12 +1271,12 @@ static bool _addr_in_ntdll( address addr ) MODULEINFO minfo; hmod = GetModuleHandle("NTDLL.DLL"); - if ( hmod == NULL ) return false; - if ( !os::PSApiDll::GetModuleInformation( GetCurrentProcess(), hmod, + if (hmod == NULL) return false; + if (!os::PSApiDll::GetModuleInformation( GetCurrentProcess(), hmod, &minfo, sizeof(MODULEINFO)) ) return false; - if ( (addr >= minfo.lpBaseOfDll) && + if ((addr >= minfo.lpBaseOfDll) && (addr < (address)((uintptr_t)minfo.lpBaseOfDll + (uintptr_t)minfo.SizeOfImage))) return true; else @@ -1304,11 +1304,11 @@ typedef int (*EnumModulesCallbackFunc)(int, char *, address, unsigned, void *); // enumerate_modules for Windows NT, using PSAPI static int _enumerate_modules_winnt( int pid, EnumModulesCallbackFunc func, void * param) { - HANDLE hProcess ; + HANDLE hProcess; # define MAX_NUM_MODULES 128 HMODULE modules[MAX_NUM_MODULES]; - static char filename[ MAX_PATH ]; + static char filename[MAX_PATH]; int result = 0; if (!os::PSApiDll::PSApiAvailable()) { @@ -1316,13 +1316,13 @@ static int _enumerate_modules_winnt( int pid, EnumModulesCallbackFunc func, void } hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, - FALSE, pid ) ; + FALSE, pid); if (hProcess == NULL) return 0; DWORD size_needed; if (!os::PSApiDll::EnumProcessModules(hProcess, modules, sizeof(modules), &size_needed)) { - CloseHandle( hProcess ); + CloseHandle(hProcess); return 0; } @@ -1331,7 +1331,7 @@ static int _enumerate_modules_winnt( int pid, EnumModulesCallbackFunc func, void for (int i = 0; i < MIN2(num_modules, MAX_NUM_MODULES); i++) { // Get Full pathname: - if(!os::PSApiDll::GetModuleFileNameEx(hProcess, modules[i], + if (!os::PSApiDll::GetModuleFileNameEx(hProcess, modules[i], filename, sizeof(filename))) { filename[0] = '\0'; } @@ -1349,7 +1349,7 @@ static int _enumerate_modules_winnt( int pid, EnumModulesCallbackFunc func, void if (result) break; } - CloseHandle( hProcess ) ; + CloseHandle(hProcess); return result; } @@ -1357,8 +1357,8 @@ static int _enumerate_modules_winnt( int pid, EnumModulesCallbackFunc func, void // enumerate_modules for Windows 95/98/ME, using TOOLHELP static int _enumerate_modules_windows( int pid, EnumModulesCallbackFunc func, void *param) { - HANDLE hSnapShot ; - static MODULEENTRY32 modentry ; + HANDLE hSnapShot; + static MODULEENTRY32 modentry; int result = 0; if (!os::Kernel32Dll::HelpToolsAvailable()) { @@ -1366,22 +1366,22 @@ static int _enumerate_modules_windows( int pid, EnumModulesCallbackFunc func, vo } // Get a handle to a Toolhelp snapshot of the system - hSnapShot = os::Kernel32Dll::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid ) ; - if( hSnapShot == INVALID_HANDLE_VALUE ) { - return FALSE ; + hSnapShot = os::Kernel32Dll::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid); + if (hSnapShot == INVALID_HANDLE_VALUE) { + return FALSE; } // iterate through all modules - modentry.dwSize = sizeof(MODULEENTRY32) ; + modentry.dwSize = sizeof(MODULEENTRY32); bool not_done = os::Kernel32Dll::Module32First( hSnapShot, &modentry ) != 0; - while( not_done ) { + while (not_done) { // invoke the callback result=func(pid, modentry.szExePath, (address)modentry.modBaseAddr, modentry.modBaseSize, param); if (result) break; - modentry.dwSize = sizeof(MODULEENTRY32) ; + modentry.dwSize = sizeof(MODULEENTRY32); not_done = os::Kernel32Dll::Module32Next( hSnapShot, &modentry ) != 0; } @@ -1941,7 +1941,7 @@ void os::signal_raise(int signal_number) { // that raises SIGTERM for the latter cases. // static BOOL WINAPI consoleHandler(DWORD event) { - switch(event) { + switch (event) { case CTRL_C_EVENT: if (is_error_reported()) { // Ctrl-C is pressed during error reporting, likely because the error @@ -1965,7 +1965,7 @@ static BOOL WINAPI consoleHandler(DWORD event) { HANDLE handle = GetProcessWindowStation(); if (handle != NULL && GetUserObjectInformation(handle, UOI_FLAGS, &flags, - sizeof( USEROBJECTFLAGS), NULL)) { + sizeof(USEROBJECTFLAGS), NULL)) { // If it is a non-interactive session, let next handler to deal // with it. if ((flags.dwFlags & WSF_VISIBLE) == 0) { @@ -1991,7 +1991,7 @@ static BOOL WINAPI consoleHandler(DWORD event) { // Return maximum OS signal used + 1 for internal use only // Used as exit signal for signal_thread -int os::sigexitnum_pd(){ +int os::sigexitnum_pd() { return NSIG; } @@ -2422,11 +2422,11 @@ LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) { // process of write protecting the memory serialization page. // It write enables the page immediately after protecting it // so just return. - if ( exception_code == EXCEPTION_ACCESS_VIOLATION ) { + if (exception_code == EXCEPTION_ACCESS_VIOLATION) { JavaThread* thread = (JavaThread*) t; PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord; address addr = (address) exceptionRecord->ExceptionInformation[1]; - if ( os::is_memory_serialize_page(thread, addr) ) { + if (os::is_memory_serialize_page(thread, addr)) { // Block current thread until the memory serialize page permission restored. os::block_on_serialize_page_trap(); return EXCEPTION_CONTINUE_EXECUTION; @@ -2543,7 +2543,7 @@ LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) { // PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord; address addr = (address) exceptionRecord->ExceptionInformation[1]; - if (addr > thread->stack_yellow_zone_base() && addr < thread->stack_base() ) { + if (addr > thread->stack_yellow_zone_base() && addr < thread->stack_base()) { addr = (address)((uintptr_t)addr & (~((uintptr_t)os::vm_page_size() - (uintptr_t)1))); os::commit_memory((char *)addr, thread->stack_base() - addr, @@ -2623,7 +2623,7 @@ LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) { // Compiled method patched to be non entrant? Following conditions must apply: // 1. must be first instruction in bundle // 2. must be a break instruction with appropriate code - if((((uint64_t) pc & 0x0F) == 0) && + if ((((uint64_t) pc & 0x0F) == 0) && (((IPF_Bundle*) pc)->get_slot0() == handle_wrong_method_break.bits())) { return Handle_Exception(exceptionInfo, (address)SharedRuntime::get_handle_wrong_method_stub()); @@ -2794,7 +2794,7 @@ public: return (_numa_used_node_count > 1); } - int get_count() {return _numa_used_node_count;} + int get_count() { return _numa_used_node_count; } int get_node_list_entry(int n) { // for indexes out of range, returns -1 return (n < _numa_used_node_count ? _numa_used_node_list[n] : -1); @@ -3112,14 +3112,14 @@ char* os::pd_reserve_memory(size_t bytes, char* addr, size_t alignment_hint) { res = (char*)VirtualAlloc(addr, bytes, MEM_RESERVE, PAGE_READWRITE); } else { elapsedTimer reserveTimer; - if( Verbose && PrintMiscellaneous ) reserveTimer.start(); + if (Verbose && PrintMiscellaneous) reserveTimer.start(); // in numa interleaving, we have to allocate pages individually // (well really chunks of NUMAInterleaveGranularity size) res = allocate_pages_individually(bytes, addr, MEM_RESERVE, PAGE_READWRITE); if (res == NULL) { warning("NUMA page allocation failed"); } - if( Verbose && PrintMiscellaneous ) { + if (Verbose && PrintMiscellaneous) { reserveTimer.stop(); tty->print_cr("reserve_memory of %Ix bytes took " JLONG_FORMAT " ms (" JLONG_FORMAT " ticks)", bytes, reserveTimer.milliseconds(), reserveTimer.ticks()); @@ -3450,14 +3450,14 @@ public: int os::sleep(Thread* thread, jlong ms, bool interruptable) { jlong limit = (jlong) MAXDWORD; - while(ms > limit) { + while (ms > limit) { int res; if ((res = sleep(thread, limit, interruptable)) != OS_TIMEOUT) return res; ms -= limit; } - assert(thread == Thread::current(), "thread consistency check"); + assert(thread == Thread::current(), "thread consistency check"); OSThread* osthread = thread->osthread(); OSThreadWaitState osts(osthread, false /* not Object.wait() */); int result; @@ -3473,8 +3473,8 @@ int os::sleep(Thread* thread, jlong ms, bool interruptable) { HANDLE events[1]; events[0] = osthread->interrupt_event(); HighResolutionInterval *phri=NULL; - if(!ForceTimeHighResolution) - phri = new HighResolutionInterval( ms ); + if (!ForceTimeHighResolution) + phri = new HighResolutionInterval(ms); if (WaitForMultipleObjects(1, events, FALSE, (DWORD)ms) == WAIT_TIMEOUT) { result = OS_TIMEOUT; } else { @@ -3511,17 +3511,17 @@ void os::infinite_sleep() { } } -typedef BOOL (WINAPI * STTSignature)(void) ; +typedef BOOL (WINAPI * STTSignature)(void); os::YieldResult os::NakedYield() { // Use either SwitchToThread() or Sleep(0) // Consider passing back the return value from SwitchToThread(). if (os::Kernel32Dll::SwitchToThreadAvailable()) { - return SwitchToThread() ? os::YIELD_SWITCHED : os::YIELD_NONEREADY ; + return SwitchToThread() ? os::YIELD_SWITCHED : os::YIELD_NONEREADY; } else { Sleep(0); } - return os::YIELD_UNKNOWN ; + return os::YIELD_UNKNOWN; } void os::yield() { os::NakedYield(); } @@ -3574,7 +3574,7 @@ static int prio_init() { } } if (UseCriticalJavaThreadPriority) { - os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority] ; + os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority]; } return 0; } @@ -3586,7 +3586,7 @@ OSReturn os::set_native_priority(Thread* thread, int priority) { } OSReturn os::get_native_priority(const Thread* const thread, int* priority_ptr) { - if ( !UseThreadPriorities ) { + if (!UseThreadPriorities) { *priority_ptr = java_to_os_priority[NormPriority]; return OS_OK; } @@ -3620,8 +3620,8 @@ void os::interrupt(Thread* thread) { if (thread->is_Java_thread()) ((JavaThread*)thread)->parker()->unpark(); - ParkEvent * ev = thread->_ParkEvent ; - if (ev != NULL) ev->unpark() ; + ParkEvent * ev = thread->_ParkEvent; + if (ev != NULL) ev->unpark(); } @@ -3715,7 +3715,7 @@ void os::win32::initialize_system_info() { OSVERSIONINFOEX oi; oi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); GetVersionEx((OSVERSIONINFO*)&oi); - switch(oi.dwPlatformId) { + switch (oi.dwPlatformId) { case VER_PLATFORM_WIN32_WINDOWS: _is_nt = false; break; case VER_PLATFORM_WIN32_NT: _is_nt = true; @@ -3898,29 +3898,29 @@ static jint initSock(); jint os::init_2(void) { // Allocate a single page and mark it as readable for safepoint polling address polling_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READONLY); - guarantee( polling_page != NULL, "Reserve Failed for polling page"); + guarantee(polling_page != NULL, "Reserve Failed for polling page"); address return_page = (address)VirtualAlloc(polling_page, os::vm_page_size(), MEM_COMMIT, PAGE_READONLY); - guarantee( return_page != NULL, "Commit Failed for polling page"); + guarantee(return_page != NULL, "Commit Failed for polling page"); - os::set_polling_page( polling_page ); + os::set_polling_page(polling_page); #ifndef PRODUCT - if( Verbose && PrintMiscellaneous ) + if (Verbose && PrintMiscellaneous) tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page); #endif if (!UseMembar) { address mem_serialize_page = (address)VirtualAlloc(NULL, os::vm_page_size(), MEM_RESERVE, PAGE_READWRITE); - guarantee( mem_serialize_page != NULL, "Reserve Failed for memory serialize page"); + guarantee(mem_serialize_page != NULL, "Reserve Failed for memory serialize page"); return_page = (address)VirtualAlloc(mem_serialize_page, os::vm_page_size(), MEM_COMMIT, PAGE_READWRITE); - guarantee( return_page != NULL, "Commit Failed for memory serialize page"); + guarantee(return_page != NULL, "Commit Failed for memory serialize page"); - os::set_memory_serialize_page( mem_serialize_page ); + os::set_memory_serialize_page(mem_serialize_page); #ifndef PRODUCT - if(Verbose && PrintMiscellaneous) + if (Verbose && PrintMiscellaneous) tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); #endif } @@ -4036,14 +4036,14 @@ void os::init_3(void) { // Mark the polling page as unreadable void os::make_polling_page_unreadable(void) { DWORD old_status; - if( !VirtualProtect((char *)_polling_page, os::vm_page_size(), PAGE_NOACCESS, &old_status) ) + if (!VirtualProtect((char *)_polling_page, os::vm_page_size(), PAGE_NOACCESS, &old_status)) fatal("Could not disable polling page"); }; // Mark the polling page as readable void os::make_polling_page_readable(void) { DWORD old_status; - if( !VirtualProtect((char *)_polling_page, os::vm_page_size(), PAGE_READONLY, &old_status) ) + if (!VirtualProtect((char *)_polling_page, os::vm_page_size(), PAGE_READONLY, &old_status)) fatal("Could not enable polling page"); }; @@ -4121,7 +4121,7 @@ jlong os::thread_cpu_time(Thread* thread, bool user_sys_cpu_time) { FILETIME KernelTime; FILETIME UserTime; - if ( GetThreadTimes(thread->osthread()->thread_handle(), + if (GetThreadTimes(thread->osthread()->thread_handle(), &CreationTime, &ExitTime, &KernelTime, &UserTime) == 0) return -1; else @@ -4157,7 +4157,7 @@ bool os::is_thread_cpu_time_supported() { FILETIME KernelTime; FILETIME UserTime; - if ( GetThreadTimes(GetCurrentThread(), + if (GetThreadTimes(GetCurrentThread(), &CreationTime, &ExitTime, &KernelTime, &UserTime) == 0) return false; else @@ -4391,7 +4391,7 @@ int os::ftruncate(int fd, jlong length) { int os::fsync(int fd) { HANDLE handle = (HANDLE)::_get_osfhandle(fd); - if ( (!::FlushFileBuffers(handle)) && + if ((!::FlushFileBuffers(handle)) && (GetLastError() != ERROR_ACCESS_DENIED) ) { /* from winerror.h */ return -1; @@ -4512,7 +4512,7 @@ static int stdinAvailable(int fd, long *pbytes) { } /* Examine input records for the number of bytes available */ - for(i=0; i 0 , "Invariant") ; - int v ; + guarantee(_ParkHandle != NULL , "Invariant"); + guarantee(Millis > 0 , "Invariant"); + int v; // CONSIDER: defer assigning a CreateEvent() handle to the Event until // the initial park() operation. for (;;) { - v = _Event ; - if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; + v = _Event; + if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; } - guarantee ((v == 0) || (v == 1), "invariant") ; - if (v != 0) return OS_OK ; + guarantee((v == 0) || (v == 1), "invariant"); + if (v != 0) return OS_OK; // Do this the hard way by blocking ... // TODO: consider a brief spin here, gated on the success of recent @@ -4820,59 +4820,59 @@ int os::PlatformEvent::park (jlong Millis) { // In the future, however, we might want to track the accumulated wait time and // adjust Millis accordingly if we encounter a spurious wakeup. - const int MAXTIMEOUT = 0x10000000 ; - DWORD rv = WAIT_TIMEOUT ; + const int MAXTIMEOUT = 0x10000000; + DWORD rv = WAIT_TIMEOUT; while (_Event < 0 && Millis > 0) { - DWORD prd = Millis ; // set prd = MAX (Millis, MAXTIMEOUT) + DWORD prd = Millis; // set prd = MAX (Millis, MAXTIMEOUT) if (Millis > MAXTIMEOUT) { - prd = MAXTIMEOUT ; + prd = MAXTIMEOUT; } - rv = ::WaitForSingleObject (_ParkHandle, prd) ; - assert (rv == WAIT_OBJECT_0 || rv == WAIT_TIMEOUT, "WaitForSingleObject failed") ; + rv = ::WaitForSingleObject(_ParkHandle, prd); + assert(rv == WAIT_OBJECT_0 || rv == WAIT_TIMEOUT, "WaitForSingleObject failed"); if (rv == WAIT_TIMEOUT) { - Millis -= prd ; + Millis -= prd; } } - v = _Event ; - _Event = 0 ; + v = _Event; + _Event = 0; // see comment at end of os::PlatformEvent::park() below: - OrderAccess::fence() ; + OrderAccess::fence(); // If we encounter a nearly simultanous timeout expiry and unpark() // we return OS_OK indicating we awoke via unpark(). // Implementor's license -- returning OS_TIMEOUT would be equally valid, however. - return (v >= 0) ? OS_OK : OS_TIMEOUT ; + return (v >= 0) ? OS_OK : OS_TIMEOUT; } -void os::PlatformEvent::park () { - guarantee (_ParkHandle != NULL, "Invariant") ; +void os::PlatformEvent::park() { + guarantee(_ParkHandle != NULL, "Invariant"); // Invariant: Only the thread associated with the Event/PlatformEvent // may call park(). - int v ; + int v; for (;;) { - v = _Event ; - if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; + v = _Event; + if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; } - guarantee ((v == 0) || (v == 1), "invariant") ; - if (v != 0) return ; + guarantee((v == 0) || (v == 1), "invariant"); + if (v != 0) return; // Do this the hard way by blocking ... // TODO: consider a brief spin here, gated on the success of recent // spin attempts by this thread. while (_Event < 0) { - DWORD rv = ::WaitForSingleObject (_ParkHandle, INFINITE) ; - assert (rv == WAIT_OBJECT_0, "WaitForSingleObject failed") ; + DWORD rv = ::WaitForSingleObject(_ParkHandle, INFINITE); + assert(rv == WAIT_OBJECT_0, "WaitForSingleObject failed"); } // Usually we'll find _Event == 0 at this point, but as // an optional optimization we clear it, just in case can // multiple unpark() operations drove _Event up to 1. - _Event = 0 ; - OrderAccess::fence() ; - guarantee (_Event >= 0, "invariant") ; + _Event = 0; + OrderAccess::fence(); + guarantee(_Event >= 0, "invariant"); } void os::PlatformEvent::unpark() { - guarantee (_ParkHandle != NULL, "Invariant") ; + guarantee(_ParkHandle != NULL, "Invariant"); // Transitions for _Event: // 0 :=> 1 @@ -4907,7 +4907,7 @@ void os::PlatformEvent::unpark() { void Parker::park(bool isAbsolute, jlong time) { - guarantee (_ParkEvent != NULL, "invariant") ; + guarantee(_ParkEvent != NULL, "invariant"); // First, demultiplex/decode time arguments if (time < 0) { // don't wait return; @@ -4941,7 +4941,7 @@ void Parker::park(bool isAbsolute, jlong time) { OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); jt->set_suspend_equivalent(); - WaitForSingleObject(_ParkEvent, time); + WaitForSingleObject(_ParkEvent, time); ResetEvent(_ParkEvent); // If externally suspended while waiting, re-suspend @@ -4952,7 +4952,7 @@ void Parker::park(bool isAbsolute, jlong time) { } void Parker::unpark() { - guarantee (_ParkEvent != NULL, "invariant") ; + guarantee(_ParkEvent != NULL, "invariant"); SetEvent(_ParkEvent); } @@ -5040,7 +5040,7 @@ bool os::find(address addr, outputStream* st) { LONG WINAPI os::win32::serialize_fault_filter(struct _EXCEPTION_POINTERS* e) { DWORD exception_code = e->ExceptionRecord->ExceptionCode; - if ( exception_code == EXCEPTION_ACCESS_VIOLATION ) { + if (exception_code == EXCEPTION_ACCESS_VIOLATION) { JavaThread* thread = (JavaThread*)ThreadLocalStorage::get_thread_slow(); PEXCEPTION_RECORD exceptionRecord = e->ExceptionRecord; address addr = (address) exceptionRecord->ExceptionInformation[1]; diff --git a/hotspot/src/os_cpu/linux_sparc/vm/vm_version_linux_sparc.cpp b/hotspot/src/os_cpu/linux_sparc/vm/vm_version_linux_sparc.cpp index 70dc8f0e5d8..2f3cdf9ac83 100644 --- a/hotspot/src/os_cpu/linux_sparc/vm/vm_version_linux_sparc.cpp +++ b/hotspot/src/os_cpu/linux_sparc/vm/vm_version_linux_sparc.cpp @@ -55,7 +55,7 @@ int VM_Version::platform_features(int features) { if (detect_niagara()) { NOT_PRODUCT(if (PrintMiscellaneous && Verbose) tty->print_cr("Detected Linux on Niagara");) - features = niagara1_m; + features = niagara1_m | T_family_m; } return features; diff --git a/hotspot/src/share/vm/classfile/classFileParser.cpp b/hotspot/src/share/vm/classfile/classFileParser.cpp index 608b43ae150..3ea6d0c9aee 100644 --- a/hotspot/src/share/vm/classfile/classFileParser.cpp +++ b/hotspot/src/share/vm/classfile/classFileParser.cpp @@ -2984,9 +2984,12 @@ void ClassFileParser::parse_classfile_attributes(ClassFileParser::ClassAnnotatio } else if (tag == vmSymbols::tag_enclosing_method()) { if (parsed_enclosingmethod_attribute) { classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", CHECK); - } else { + } else { parsed_enclosingmethod_attribute = true; } + guarantee_property(attribute_length == 4, + "Wrong EnclosingMethod attribute length %u in class file %s", + attribute_length, CHECK); cfs->guarantee_more(4, CHECK); // class_index, method_index enclosing_method_class_index = cfs->get_u2_fast(); enclosing_method_method_index = cfs->get_u2_fast(); @@ -4067,6 +4070,11 @@ instanceKlassHandle ClassFileParser::parseClassFile(Symbol* name, this_klass->set_major_version(major_version); this_klass->set_has_default_methods(has_default_methods); + if (!host_klass.is_null()) { + assert (this_klass->is_anonymous(), "should be the same"); + this_klass->set_host_klass(host_klass()); + } + // Set up Method*::intrinsic_id as soon as we know the names of methods. // (We used to do this lazily, but now we query it in Rewriter, // which is eagerly done for every method, so we might as well do it now, @@ -4664,9 +4672,7 @@ bool ClassFileParser::has_illegal_visibility(jint flags) { } bool ClassFileParser::is_supported_version(u2 major, u2 minor) { - u2 max_version = - JDK_Version::is_gte_jdk17x_version() ? JAVA_MAX_SUPPORTED_VERSION : - (JDK_Version::is_gte_jdk16x_version() ? JAVA_6_VERSION : JAVA_1_5_VERSION); + u2 max_version = JAVA_MAX_SUPPORTED_VERSION; return (major >= JAVA_MIN_SUPPORTED_VERSION) && (major <= max_version) && ((major != max_version) || diff --git a/hotspot/src/share/vm/classfile/classLoader.cpp b/hotspot/src/share/vm/classfile/classLoader.cpp index 8366c8fc4ce..46d979ed1df 100644 --- a/hotspot/src/share/vm/classfile/classLoader.cpp +++ b/hotspot/src/share/vm/classfile/classLoader.cpp @@ -1126,7 +1126,7 @@ void ClassLoader::verify() { // JDK 1.3 version -typedef struct real_jzentry13 { /* Zip file entry */ +typedef struct real_jzentry { /* Zip file entry */ char *name; /* entry name */ jint time; /* modification time */ jint size; /* size of uncompressed data */ @@ -1135,9 +1135,9 @@ typedef struct real_jzentry13 { /* Zip file entry */ char *comment; /* optional zip file comment */ jbyte *extra; /* optional extra data */ jint pos; /* position of LOC header (if negative) or data */ -} real_jzentry13; +} real_jzentry; -typedef struct real_jzfile13 { /* Zip file */ +typedef struct real_jzfile { /* Zip file */ char *name; /* zip file name */ jint refs; /* number of active references */ jint fd; /* open file descriptor */ @@ -1148,42 +1148,14 @@ typedef struct real_jzfile13 { /* Zip file */ jint total; /* total number of entries */ unsigned short *table; /* Hash chain heads: indexes into entries */ jint tablelen; /* number of hash eads */ - real_jzfile13 *next; /* next zip file in search list */ + real_jzfile *next; /* next zip file in search list */ jzentry *cache; /* we cache the most recently freed jzentry */ /* Information on metadata names in META-INF directory */ char **metanames; /* array of meta names (may have null names) */ jint metacount; /* number of slots in metanames array */ /* If there are any per-entry comments, they are in the comments array */ char **comments; -} real_jzfile13; - -// JDK 1.2 version -typedef struct real_jzentry12 { /* Zip file entry */ - char *name; /* entry name */ - jint time; /* modification time */ - jint size; /* size of uncompressed data */ - jint csize; /* size of compressed data (zero if uncompressed) */ - jint crc; /* crc of uncompressed data */ - char *comment; /* optional zip file comment */ - jbyte *extra; /* optional extra data */ - jint pos; /* position of LOC header (if negative) or data */ - struct real_jzentry12 *next; /* next entry in hash table */ -} real_jzentry12; - -typedef struct real_jzfile12 { /* Zip file */ - char *name; /* zip file name */ - jint refs; /* number of active references */ - jint fd; /* open file descriptor */ - void *lock; /* read lock */ - char *comment; /* zip file comment */ - char *msg; /* zip error message */ - real_jzentry12 *entries; /* array of zip entries */ - jint total; /* total number of entries */ - real_jzentry12 **table; /* hash table of entries */ - jint tablelen; /* number of buckets */ - jzfile *next; /* next zip file in search list */ -} real_jzfile12; - +} real_jzfile; void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) { // For now we only compile all methods in all classes in zip/jar files @@ -1197,10 +1169,14 @@ bool ClassPathDirEntry::is_rt_jar() { } void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) { - if (JDK_Version::is_jdk12x_version()) { - compile_the_world12(loader, THREAD); - } else { - compile_the_world13(loader, THREAD); + real_jzfile* zip = (real_jzfile*) _zip; + tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name); + tty->cr(); + // Iterate over all entries in zip file + for (int n = 0; ; n++) { + real_jzentry * ze = (real_jzentry *)((*GetNextEntry)(_zip, n)); + if (ze == NULL) break; + ClassLoader::compile_the_world_in(ze->name, loader, CHECK); } if (HAS_PENDING_EXCEPTION) { if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) { @@ -1213,54 +1189,8 @@ void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) { } } -// Version that works for JDK 1.3.x -void ClassPathZipEntry::compile_the_world13(Handle loader, TRAPS) { - real_jzfile13* zip = (real_jzfile13*) _zip; - tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name); - tty->cr(); - // Iterate over all entries in zip file - for (int n = 0; ; n++) { - real_jzentry13 * ze = (real_jzentry13 *)((*GetNextEntry)(_zip, n)); - if (ze == NULL) break; - ClassLoader::compile_the_world_in(ze->name, loader, CHECK); - } -} - - -// Version that works for JDK 1.2.x -void ClassPathZipEntry::compile_the_world12(Handle loader, TRAPS) { - real_jzfile12* zip = (real_jzfile12*) _zip; - tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name); - tty->cr(); - // Iterate over all entries in zip file - for (int n = 0; ; n++) { - real_jzentry12 * ze = (real_jzentry12 *)((*GetNextEntry)(_zip, n)); - if (ze == NULL) break; - ClassLoader::compile_the_world_in(ze->name, loader, CHECK); - } -} - bool ClassPathZipEntry::is_rt_jar() { - if (JDK_Version::is_jdk12x_version()) { - return is_rt_jar12(); - } else { - return is_rt_jar13(); - } -} - -// JDK 1.3 version -bool ClassPathZipEntry::is_rt_jar13() { - real_jzfile13* zip = (real_jzfile13*) _zip; - int len = (int)strlen(zip->name); - // Check whether zip name ends in "rt.jar" - // This will match other archives named rt.jar as well, but this is - // only used for debugging. - return (len >= 6) && (strcasecmp(zip->name + len - 6, "rt.jar") == 0); -} - -// JDK 1.2 version -bool ClassPathZipEntry::is_rt_jar12() { - real_jzfile12* zip = (real_jzfile12*) _zip; + real_jzfile* zip = (real_jzfile*) _zip; int len = (int)strlen(zip->name); // Check whether zip name ends in "rt.jar" // This will match other archives named rt.jar as well, but this is diff --git a/hotspot/src/share/vm/classfile/classLoader.hpp b/hotspot/src/share/vm/classfile/classLoader.hpp index e03cfad1b57..2cfcde6387e 100644 --- a/hotspot/src/share/vm/classfile/classLoader.hpp +++ b/hotspot/src/share/vm/classfile/classLoader.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -111,11 +111,7 @@ class ClassPathZipEntry: public ClassPathEntry { void contents_do(void f(const char* name, void* context), void* context); // Debugging NOT_PRODUCT(void compile_the_world(Handle loader, TRAPS);) - NOT_PRODUCT(void compile_the_world12(Handle loader, TRAPS);) // JDK 1.2 version - NOT_PRODUCT(void compile_the_world13(Handle loader, TRAPS);) // JDK 1.3 version NOT_PRODUCT(bool is_rt_jar();) - NOT_PRODUCT(bool is_rt_jar12();) - NOT_PRODUCT(bool is_rt_jar13();) }; diff --git a/hotspot/src/share/vm/classfile/classLoaderData.cpp b/hotspot/src/share/vm/classfile/classLoaderData.cpp index bc88beb4343..efbde89ee30 100644 --- a/hotspot/src/share/vm/classfile/classLoaderData.cpp +++ b/hotspot/src/share/vm/classfile/classLoaderData.cpp @@ -624,6 +624,12 @@ void ClassLoaderDataGraph::always_strong_oops_do(OopClosure* f, KlassClosure* kl } } +void ClassLoaderDataGraph::cld_do(CLDClosure* cl) { + for (ClassLoaderData* cld = _head; cl != NULL && cld != NULL; cld = cld->next()) { + cl->do_cld(cld); + } +} + void ClassLoaderDataGraph::classes_do(KlassClosure* klass_closure) { for (ClassLoaderData* cld = _head; cld != NULL; cld = cld->next()) { cld->classes_do(klass_closure); diff --git a/hotspot/src/share/vm/classfile/classLoaderData.hpp b/hotspot/src/share/vm/classfile/classLoaderData.hpp index 5be3caa6515..964e4289ffe 100644 --- a/hotspot/src/share/vm/classfile/classLoaderData.hpp +++ b/hotspot/src/share/vm/classfile/classLoaderData.hpp @@ -77,6 +77,7 @@ class ClassLoaderDataGraph : public AllStatic { static void oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim); static void always_strong_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim); static void keep_alive_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim); + static void cld_do(CLDClosure* cl); static void classes_do(KlassClosure* klass_closure); static void classes_do(void f(Klass* const)); static void methods_do(void f(Method*)); diff --git a/hotspot/src/share/vm/classfile/classLoaderStats.cpp b/hotspot/src/share/vm/classfile/classLoaderStats.cpp new file mode 100644 index 00000000000..4eb98ed321c --- /dev/null +++ b/hotspot/src/share/vm/classfile/classLoaderStats.cpp @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "precompiled.hpp" +#include "classfile/classLoaderStats.hpp" +#include "utilities/globalDefinitions.hpp" + + +class ClassStatsClosure : public KlassClosure { +public: + int _num_classes; + + ClassStatsClosure() : + _num_classes(0) { + } + + virtual void do_klass(Klass* k) { + _num_classes++; + } +}; + + +void ClassLoaderStatsClosure::do_cld(ClassLoaderData* cld) { + oop cl = cld->class_loader(); + ClassLoaderStats* cls; + + // The hashtable key is the ClassLoader oop since we want to account + // for "real" classes and anonymous classes together + ClassLoaderStats** cls_ptr = _stats->get(cl); + if (cls_ptr == NULL) { + cls = new ClassLoaderStats(); + _stats->put(cl, cls); + _total_loaders++; + } else { + cls = *cls_ptr; + } + + if (!cld->is_anonymous()) { + cls->_cld = cld; + } + + cls->_class_loader = cl; + if (cl != NULL) { + cls->_parent = java_lang_ClassLoader::parent(cl); + addEmptyParents(cls->_parent); + } + + ClassStatsClosure csc; + cld->classes_do(&csc); + if(cld->is_anonymous()) { + cls->_anon_classes_count += csc._num_classes; + } else { + cls->_classes_count = csc._num_classes; + } + _total_classes += csc._num_classes; + + Metaspace* ms = cld->metaspace_or_null(); + if (ms != NULL) { + if(cld->is_anonymous()) { + cls->_anon_chunk_sz += ms->allocated_chunks_bytes(); + cls->_anon_block_sz += ms->allocated_blocks_bytes(); + } else { + cls->_chunk_sz = ms->allocated_chunks_bytes(); + cls->_block_sz = ms->allocated_blocks_bytes(); + } + _total_chunk_sz += ms->allocated_chunks_bytes(); + _total_block_sz += ms->allocated_blocks_bytes(); + } +} + + +// Handles the difference in pointer width on 32 and 64 bit platforms +#ifdef _LP64 + #define SPACE "%8s" +#else + #define SPACE "%s" +#endif + + +bool ClassLoaderStatsClosure::do_entry(oop const& key, ClassLoaderStats* const& cls) { + Klass* class_loader_klass = (cls->_class_loader == NULL ? NULL : cls->_class_loader->klass()); + Klass* parent_klass = (cls->_parent == NULL ? NULL : cls->_parent->klass()); + + _out->print(INTPTR_FORMAT " " INTPTR_FORMAT " " INTPTR_FORMAT " " UINTX_FORMAT_W(6) " " SIZE_FORMAT_W(8) " " SIZE_FORMAT_W(8) " ", + p2i(class_loader_klass), p2i(parent_klass), p2i(cls->_cld), + cls->_classes_count, + cls->_chunk_sz, cls->_block_sz); + if (class_loader_klass != NULL) { + _out->print("%s", class_loader_klass->external_name()); + } else { + _out->print(""); + } + _out->cr(); + if (cls->_anon_classes_count > 0) { + _out->print_cr(SPACE SPACE SPACE " " UINTX_FORMAT_W(6) " " SIZE_FORMAT_W(8) " " SIZE_FORMAT_W(8) " + unsafe anonymous classes", + "", "", "", + cls->_anon_classes_count, + cls->_anon_chunk_sz, cls->_anon_block_sz); + } + return true; +} + + +void ClassLoaderStatsClosure::print() { + _out->print_cr("ClassLoader" SPACE " Parent" SPACE " CLD*" SPACE " Classes ChunkSz BlockSz Type", "", "", ""); + _stats->iterate(this); + _out->print("Total = " UINTX_FORMAT_W(-6), _total_loaders); + _out->print(SPACE SPACE SPACE " ", "", "", ""); + _out->print_cr(UINTX_FORMAT_W(6) " " SIZE_FORMAT_W(8) " " SIZE_FORMAT_W(8) " ", + _total_classes, + _total_chunk_sz, + _total_block_sz); + _out->print_cr("ChunkSz: Total size of all allocated metaspace chunks"); + _out->print_cr("BlockSz: Total size of all allocated metaspace blocks (each chunk has several blocks)"); +} + + +void ClassLoaderStatsClosure::addEmptyParents(oop cl) { + while (cl != NULL && java_lang_ClassLoader::loader_data(cl) == NULL) { + // This classloader has not loaded any classes + ClassLoaderStats** cls_ptr = _stats->get(cl); + if (cls_ptr == NULL) { + // It does not exist in our table - add it + ClassLoaderStats* cls = new ClassLoaderStats(); + cls->_class_loader = cl; + cls->_parent = java_lang_ClassLoader::parent(cl); + _stats->put(cl, cls); + _total_loaders++; + } + + cl = java_lang_ClassLoader::parent(cl); + } +} + + +void ClassLoaderStatsVMOperation::doit() { + ClassLoaderStatsClosure clsc (_out); + ClassLoaderDataGraph::cld_do(&clsc); + clsc.print(); +} + + +void ClassLoaderStatsDCmd::execute(DCmdSource source, TRAPS) { + ClassLoaderStatsVMOperation op(output()); + VMThread::execute(&op); +} diff --git a/hotspot/src/share/vm/classfile/classLoaderStats.hpp b/hotspot/src/share/vm/classfile/classLoaderStats.hpp new file mode 100644 index 00000000000..89e0e473b3b --- /dev/null +++ b/hotspot/src/share/vm/classfile/classLoaderStats.hpp @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#ifndef SHARE_VM_CLASSFILE_CLASSLOADERSTATS_HPP +#define SHARE_VM_CLASSFILE_CLASSLOADERSTATS_HPP + + +#include "classfile/classLoaderData.hpp" +#include "oops/klass.hpp" +#include "oops/oopsHierarchy.hpp" +#include "runtime/vm_operations.hpp" +#include "services/diagnosticCommand.hpp" +#include "utilities/resourceHash.hpp" + + +class ClassLoaderStatsDCmd : public DCmd { +public: + ClassLoaderStatsDCmd(outputStream* output, bool heap) : + DCmd(output, heap) { + } + + static const char* name() { + return "VM.classloader_stats"; + } + + static const char* description() { + return "Print statistics about all ClassLoaders."; + } + + static const char* impact() { + return "Low"; + } + + virtual void execute(DCmdSource source, TRAPS); + + static int num_arguments() { + return 0; + } + + static const JavaPermission permission() { + JavaPermission p = {"java.lang.management.ManagementPermission", + "monitor", NULL}; + return p; + } +}; + + +class ClassLoaderStats : public ResourceObj { +public: + ClassLoaderData* _cld; + oop _class_loader; + oop _parent; + + size_t _chunk_sz; + size_t _block_sz; + uintx _classes_count; + + size_t _anon_chunk_sz; + size_t _anon_block_sz; + uintx _anon_classes_count; + + ClassLoaderStats() : + _cld(0), + _class_loader(0), + _parent(0), + _chunk_sz(0), + _block_sz(0), + _classes_count(0), + _anon_block_sz(0), + _anon_chunk_sz(0), + _anon_classes_count(0) { + } +}; + + +class ClassLoaderStatsClosure : public CLDClosure { +protected: + static bool oop_equals(oop const& s1, oop const& s2) { + return s1 == s2; + } + + static unsigned oop_hash(oop const& s1) { + unsigned hash = (unsigned)((uintptr_t)&s1); + return hash ^ (hash >> LogMinObjAlignment); + } + + typedef ResourceHashtable StatsTable; + + outputStream* _out; + StatsTable* _stats; + uintx _total_loaders; + uintx _total_classes; + size_t _total_chunk_sz; + size_t _total_block_sz; + +public: + ClassLoaderStatsClosure(outputStream* out) : + _out(out), + _total_loaders(0), + _total_block_sz(0), + _total_chunk_sz(0), + _total_classes(0), + _stats(new StatsTable()) { + } + + virtual void do_cld(ClassLoaderData* cld); + virtual bool do_entry(oop const& key, ClassLoaderStats* const& cls); + void print(); + +private: + void addEmptyParents(oop cl); +}; + + +class ClassLoaderStatsVMOperation : public VM_Operation { + outputStream* _out; + +public: + ClassLoaderStatsVMOperation(outputStream* out) : + _out(out) { + } + + VMOp_Type type() const { + return VMOp_ClassLoaderStatsOperation; + } + + void doit(); +}; + +#endif // SHARE_VM_CLASSFILE_CLASSLOADERSTATS_HPP diff --git a/hotspot/src/share/vm/classfile/javaClasses.cpp b/hotspot/src/share/vm/classfile/javaClasses.cpp index 628ddf910b7..0e61ff9f391 100644 --- a/hotspot/src/share/vm/classfile/javaClasses.cpp +++ b/hotspot/src/share/vm/classfile/javaClasses.cpp @@ -857,9 +857,7 @@ void java_lang_Class::compute_offsets() { } int java_lang_Class::classRedefinedCount(oop the_class_mirror) { - if (!JDK_Version::is_gte_jdk15x_version() - || classRedefinedCount_offset == -1) { - // The classRedefinedCount field is only present starting in 1.5. + if (classRedefinedCount_offset == -1) { // If we don't have an offset for it then just return -1 as a marker. return -1; } @@ -868,9 +866,7 @@ int java_lang_Class::classRedefinedCount(oop the_class_mirror) { } void java_lang_Class::set_classRedefinedCount(oop the_class_mirror, int value) { - if (!JDK_Version::is_gte_jdk15x_version() - || classRedefinedCount_offset == -1) { - // The classRedefinedCount field is only present starting in 1.5. + if (classRedefinedCount_offset == -1) { // If we don't have an offset for it then nothing to set. return; } @@ -1000,9 +996,7 @@ oop java_lang_Thread::inherited_access_control_context(oop java_thread) { jlong java_lang_Thread::stackSize(oop java_thread) { - // The stackSize field is only present starting in 1.4 if (_stackSize_offset > 0) { - assert(JDK_Version::is_gte_jdk14x_version(), "sanity check"); return java_thread->long_field(_stackSize_offset); } else { return 0; @@ -1078,7 +1072,7 @@ bool java_lang_Thread::set_park_event(oop java_thread, jlong ptr) { const char* java_lang_Thread::thread_status_name(oop java_thread) { - assert(JDK_Version::is_gte_jdk15x_version() && _thread_status_offset != 0, "Must have thread status"); + assert(_thread_status_offset != 0, "Must have thread status"); ThreadStatus status = (java_lang_Thread::ThreadStatus)java_thread->int_field(_thread_status_offset); switch (status) { case NEW : return "NEW"; @@ -1217,7 +1211,6 @@ void java_lang_Throwable::set_stacktrace(oop throwable, oop st_element_array) { } void java_lang_Throwable::clear_stacktrace(oop throwable) { - assert(JDK_Version::is_gte_jdk14x_version(), "should only be called in >= 1.4"); set_stacktrace(throwable, NULL); } @@ -1548,12 +1541,9 @@ void java_lang_Throwable::fill_in_stack_trace(Handle throwable, methodHandle met // Start out by clearing the backtrace for this object, in case the VM // runs out of memory while allocating the stack trace set_backtrace(throwable(), NULL); - if (JDK_Version::is_gte_jdk14x_version()) { - // New since 1.4, clear lazily constructed Java level stacktrace if - // refilling occurs - // This is unnecessary in 1.7+ but harmless - clear_stacktrace(throwable()); - } + // Clear lazily constructed Java level stacktrace if refilling occurs + // This is unnecessary in 1.7+ but harmless + clear_stacktrace(throwable()); int max_depth = MaxJavaStackTraceDepth; JavaThread* thread = (JavaThread*)THREAD; @@ -1739,13 +1729,9 @@ void java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(Handle t if (chunk_count >= max_chunks) break; } - // For Java 7+ we support the Throwable immutability protocol defined for Java 7. This support - // was missing in 7u0 so in 7u0 there is a workaround in the Throwable class. That workaround - // can be removed in a JDK using this JVM version - if (JDK_Version::is_gte_jdk17x_version()) { - java_lang_Throwable::set_stacktrace(throwable(), java_lang_Throwable::unassigned_stacktrace()); - assert(java_lang_Throwable::unassigned_stacktrace() != NULL, "not initialized"); - } + // We support the Throwable immutability protocol defined for Java 7. + java_lang_Throwable::set_stacktrace(throwable(), java_lang_Throwable::unassigned_stacktrace()); + assert(java_lang_Throwable::unassigned_stacktrace() != NULL, "not initialized"); } @@ -3022,8 +3008,7 @@ bool java_lang_ClassLoader::isAncestor(oop loader, oop cl) { // based on non-null field // Written to by java.lang.ClassLoader, vm only reads this field, doesn't set it bool java_lang_ClassLoader::parallelCapable(oop class_loader) { - if (!JDK_Version::is_gte_jdk17x_version() - || parallelCapable_offset == -1) { + if (parallelCapable_offset == -1) { // Default for backward compatibility is false return false; } @@ -3219,7 +3204,6 @@ void java_nio_Buffer::compute_offsets() { void java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(TRAPS) { if (_owner_offset != 0) return; - assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later"); SystemDictionary::load_abstract_ownable_synchronizer_klass(CHECK); Klass* k = SystemDictionary::abstract_ownable_synchronizer_klass(); compute_offset(_owner_offset, k, @@ -3309,15 +3293,10 @@ void JavaClasses::compute_offsets() { java_lang_reflect_Method::compute_offsets(); java_lang_reflect_Constructor::compute_offsets(); java_lang_reflect_Field::compute_offsets(); - if (JDK_Version::is_gte_jdk14x_version()) { - java_nio_Buffer::compute_offsets(); - } - if (JDK_Version::is_gte_jdk15x_version()) { - sun_reflect_ConstantPool::compute_offsets(); - sun_reflect_UnsafeStaticFieldAccessorImpl::compute_offsets(); - } - if (JDK_Version::is_gte_jdk18x_version()) - java_lang_reflect_Parameter::compute_offsets(); + java_nio_Buffer::compute_offsets(); + sun_reflect_ConstantPool::compute_offsets(); + sun_reflect_UnsafeStaticFieldAccessorImpl::compute_offsets(); + java_lang_reflect_Parameter::compute_offsets(); // generated interpreter code wants to know about the offsets we just computed: AbstractAssembler::update_delayed_values(); @@ -3502,7 +3481,7 @@ void JavaClasses::check_offsets() { // into merlin "for some time." Without it, the vm will fail with early // merlin builds. - if (CheckAssertionStatusDirectives && JDK_Version::is_gte_jdk14x_version()) { + if (CheckAssertionStatusDirectives) { const char* nm = "java/lang/AssertionStatusDirectives"; const char* sig = "[Ljava/lang/String;"; CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, classes, sig); diff --git a/hotspot/src/share/vm/classfile/systemDictionary.cpp b/hotspot/src/share/vm/classfile/systemDictionary.cpp index d09de41114d..4a6e1c3e377 100644 --- a/hotspot/src/share/vm/classfile/systemDictionary.cpp +++ b/hotspot/src/share/vm/classfile/systemDictionary.cpp @@ -997,7 +997,6 @@ Klass* SystemDictionary::parse_stream(Symbol* class_name, if (host_klass.not_null() && k.not_null()) { - k->set_host_klass(host_klass()); // If it's anonymous, initialize it now, since nobody else will. { @@ -1754,8 +1753,6 @@ void SystemDictionary::methods_do(void f(Method*)) { // Lazily load klasses void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) { - assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later"); - // if multiple threads calling this function, only one thread will load // the class. The other threads will find the loaded version once the // class is loaded. diff --git a/hotspot/src/share/vm/classfile/systemDictionary.hpp b/hotspot/src/share/vm/classfile/systemDictionary.hpp index 4e1b75dc241..f26a9d8c56e 100644 --- a/hotspot/src/share/vm/classfile/systemDictionary.hpp +++ b/hotspot/src/share/vm/classfile/systemDictionary.hpp @@ -139,14 +139,13 @@ class Ticks; do_klass(reflect_Constructor_klass, java_lang_reflect_Constructor, Pre ) \ \ /* NOTE: needed too early in bootstrapping process to have checks based on JDK version */ \ - /* Universe::is_gte_jdk14x_version() is not set up by this point. */ \ /* It's okay if this turns out to be NULL in non-1.4 JDKs. */ \ do_klass(reflect_MagicAccessorImpl_klass, sun_reflect_MagicAccessorImpl, Opt ) \ - do_klass(reflect_MethodAccessorImpl_klass, sun_reflect_MethodAccessorImpl, Opt_Only_JDK14NewRef) \ - do_klass(reflect_ConstructorAccessorImpl_klass, sun_reflect_ConstructorAccessorImpl, Opt_Only_JDK14NewRef) \ + do_klass(reflect_MethodAccessorImpl_klass, sun_reflect_MethodAccessorImpl, Pre ) \ + do_klass(reflect_ConstructorAccessorImpl_klass, sun_reflect_ConstructorAccessorImpl, Pre ) \ do_klass(reflect_DelegatingClassLoader_klass, sun_reflect_DelegatingClassLoader, Opt ) \ - do_klass(reflect_ConstantPool_klass, sun_reflect_ConstantPool, Opt_Only_JDK15 ) \ - do_klass(reflect_UnsafeStaticFieldAccessorImpl_klass, sun_reflect_UnsafeStaticFieldAccessorImpl, Opt_Only_JDK15 ) \ + do_klass(reflect_ConstantPool_klass, sun_reflect_ConstantPool, Opt ) \ + do_klass(reflect_UnsafeStaticFieldAccessorImpl_klass, sun_reflect_UnsafeStaticFieldAccessorImpl, Opt ) \ do_klass(reflect_CallerSensitive_klass, sun_reflect_CallerSensitive, Opt ) \ \ /* support for dynamic typing; it's OK if these are NULL in earlier JDKs */ \ @@ -169,7 +168,6 @@ class Ticks; \ /* It's NULL in non-1.4 JDKs. */ \ do_klass(StackTraceElement_klass, java_lang_StackTraceElement, Opt ) \ - /* Universe::is_gte_jdk14x_version() is not set up by this point. */ \ /* It's okay if this turns out to be NULL in non-1.4 JDKs. */ \ do_klass(nio_Buffer_klass, java_nio_Buffer, Opt ) \ \ @@ -209,10 +207,8 @@ class SystemDictionary : AllStatic { // Options after this point will use resolve_or_null instead. Opt, // preload tried; NULL if not present - Opt_Only_JDK14NewRef, // preload tried; use only with NewReflection - Opt_Only_JDK15, // preload tried; use only with JDK1.5+ OPTION_LIMIT, - CEIL_LG_OPTION_LIMIT = 4 // OPTION_LIMIT <= (1< 0) { if (TimeLivenessAnalysis) _time_total.start(); @@ -1000,7 +1000,7 @@ bool MethodLiveness::BasicBlock::merge_exception(BitMap other) { } MethodLivenessResult MethodLiveness::BasicBlock::get_liveness_at(ciMethod* method, int bci) { - MethodLivenessResult answer(NEW_RESOURCE_ARRAY(uintptr_t, _analyzer->bit_map_size_words()), + MethodLivenessResult answer(NEW_RESOURCE_ARRAY(BitMap::bm_word_t, _analyzer->bit_map_size_words()), _analyzer->bit_map_size_bits()); answer.set_is_valid(); diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp index 24c62d775bd..9d80a5c7212 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp @@ -127,7 +127,7 @@ bool CMBitMap::allocate(ReservedSpace heap_rs) { } assert(_virtual_space.committed_size() == brs.size(), "didn't reserve backing store for all of concurrent marking bit map?"); - _bm.set_map((uintptr_t*)_virtual_space.low()); + _bm.set_map((BitMap::bm_word_t*)_virtual_space.low()); assert(_virtual_space.committed_size() << (_shifter + LogBitsPerByte) >= _bmWordSize, "inconsistency in bit map sizing"); _bm.set_size(_bmWordSize >> _shifter); diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp index a1dbb6f1b18..2f259ea1beb 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp @@ -433,14 +433,6 @@ HeapRegion* G1CollectedHeap::pop_dirty_cards_region() return hr; } -void G1CollectedHeap::stop_conc_gc_threads() { - _cg1r->stop(); - _cmThread->stop(); - if (G1StringDedup::is_enabled()) { - G1StringDedup::stop(); - } -} - #ifdef ASSERT // A region is added to the collection set as it is retired // so an address p can point to a region which will be in the @@ -2174,20 +2166,14 @@ jint G1CollectedHeap::initialize() { } void G1CollectedHeap::stop() { -#if 0 - // Stopping concurrent worker threads is currently disabled until - // some bugs in concurrent mark has been resolve. Without fixing - // those bugs first we risk haning during VM exit when trying to - // stop these threads. - - // Abort any ongoing concurrent root region scanning and stop all - // concurrent threads. We do this to make sure these threads do - // not continue to execute and access resources (e.g. gclog_or_tty) + // Stop all concurrent threads. We do this to make sure these threads + // do not continue to execute and access resources (e.g. gclog_or_tty) // that are destroyed during shutdown. - _cm->root_regions()->abort(); - _cm->root_regions()->wait_until_scan_finished(); - stop_conc_gc_threads(); -#endif + _cg1r->stop(); + _cmThread->stop(); + if (G1StringDedup::is_enabled()) { + G1StringDedup::stop(); + } } size_t G1CollectedHeap::conservative_max_heap_alignment() { diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp index 77918a64aae..f4d0baae983 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp @@ -1684,8 +1684,6 @@ public: void print_all_rsets() PRODUCT_RETURN; public: - void stop_conc_gc_threads(); - size_t pending_card_num(); size_t cards_scanned(); diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp index 76a368b692c..19a055cc040 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp @@ -71,7 +71,7 @@ ParMarkBitMap::initialize(MemRegion covered_region) if (_virtual_space != NULL && _virtual_space->expand_by(_reserved_byte_size)) { _region_start = covered_region.start(); _region_size = covered_region.word_size(); - idx_t* map = (idx_t*)_virtual_space->reserved_low_addr(); + BitMap::bm_word_t* map = (BitMap::bm_word_t*)_virtual_space->reserved_low_addr(); _beg_bits.set_map(map); _beg_bits.set_size(bits / 2); _end_bits.set_map(map + words / 2); diff --git a/hotspot/src/share/vm/interpreter/linkResolver.cpp b/hotspot/src/share/vm/interpreter/linkResolver.cpp index d732cb2eec5..6fbb3bfa6f1 100644 --- a/hotspot/src/share/vm/interpreter/linkResolver.cpp +++ b/hotspot/src/share/vm/interpreter/linkResolver.cpp @@ -945,12 +945,8 @@ void LinkResolver::linktime_resolve_special_method(methodHandle& resolved_method Klass *klass_to_check = !InstanceKlass::cast(current_klass())->is_anonymous() ? current_klass() : InstanceKlass::cast(current_klass())->host_klass(); - // As of the fix for 4486457 we disable verification for all of the - // dynamically-generated bytecodes associated with the 1.4 - // reflection implementation, not just those associated with - // sun/reflect/SerializationConstructorAccessor. - bool is_reflect = JDK_Version::is_gte_jdk14x_version() && - klass_to_check->is_subclass_of( + // Disable verification for the dynamically-generated reflection bytecodes. + bool is_reflect = klass_to_check->is_subclass_of( SystemDictionary::reflect_MagicAccessorImpl_klass()); if (!is_reflect && diff --git a/hotspot/src/share/vm/memory/guardedMemory.cpp b/hotspot/src/share/vm/memory/guardedMemory.cpp new file mode 100644 index 00000000000..763548fd35d --- /dev/null +++ b/hotspot/src/share/vm/memory/guardedMemory.cpp @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ +#include "precompiled.hpp" +#include "memory/allocation.hpp" +#include "memory/allocation.inline.hpp" +#include "memory/guardedMemory.hpp" +#include "runtime/os.hpp" + +void* GuardedMemory::wrap_copy(const void* ptr, const size_t len, const void* tag) { + size_t total_sz = GuardedMemory::get_total_size(len); + void* outerp = os::malloc(total_sz, mtInternal); + if (outerp != NULL) { + GuardedMemory guarded(outerp, len, tag); + void* innerp = guarded.get_user_ptr(); + memcpy(innerp, ptr, len); + return innerp; + } + return NULL; // OOM +} + +bool GuardedMemory::free_copy(void* p) { + if (p == NULL) { + return true; + } + GuardedMemory guarded((u_char*)p); + bool verify_ok = guarded.verify_guards(); + + /* always attempt to free, pass problem on to any nested memchecker */ + os::free(guarded.release_for_freeing()); + + return verify_ok; +} + +void GuardedMemory::print_on(outputStream* st) const { + if (_base_addr == NULL) { + st->print_cr("GuardedMemory(" PTR_FORMAT ") not associated to any memory", p2i(this)); + return; + } + st->print_cr("GuardedMemory(" PTR_FORMAT ") base_addr=" PTR_FORMAT + " tag=" PTR_FORMAT " user_size=" SIZE_FORMAT " user_data=" PTR_FORMAT, + p2i(this), p2i(_base_addr), p2i(get_tag()), get_user_size(), p2i(get_user_ptr())); + + Guard* guard = get_head_guard(); + st->print_cr(" Header guard @" PTR_FORMAT " is %s", p2i(guard), (guard->verify() ? "OK" : "BROKEN")); + guard = get_tail_guard(); + st->print_cr(" Trailer guard @" PTR_FORMAT " is %s", p2i(guard), (guard->verify() ? "OK" : "BROKEN")); + + u_char udata = *get_user_ptr(); + switch (udata) { + case uninitBlockPad: + st->print_cr(" User data appears unused"); + break; + case freeBlockPad: + st->print_cr(" User data appears to have been freed"); + break; + default: + st->print_cr(" User data appears to be in use"); + break; + } +} + +// test code... + +#ifndef PRODUCT + +static void guarded_memory_test_check(void* p, size_t sz, void* tag) { + assert(p != NULL, "NULL pointer given to check"); + u_char* c = (u_char*) p; + GuardedMemory guarded(c); + assert(guarded.get_tag() == tag, "Tag is not the same as supplied"); + assert(guarded.get_user_ptr() == c, "User pointer is not the same as supplied"); + assert(guarded.get_user_size() == sz, "User size is not the same as supplied"); + assert(guarded.verify_guards(), "Guard broken"); +} + +void GuardedMemory::test_guarded_memory() { + // Test the basic characteristics... + size_t total_sz = GuardedMemory::get_total_size(1); + assert(total_sz > 1 && total_sz >= (sizeof(GuardHeader) + 1 + sizeof(Guard)), "Unexpected size"); + u_char* basep = (u_char*) os::malloc(total_sz, mtInternal); + + GuardedMemory guarded(basep, 1, (void*)0xf000f000); + + assert(*basep == badResourceValue, "Expected guard in the form of badResourceValue"); + u_char* userp = guarded.get_user_ptr(); + assert(*userp == uninitBlockPad, "Expected uninitialized data in the form of uninitBlockPad"); + guarded_memory_test_check(userp, 1, (void*)0xf000f000); + + void* freep = guarded.release_for_freeing(); + assert((u_char*)freep == basep, "Expected the same pointer guard was "); + assert(*userp == freeBlockPad, "Expected user data to be free block padded"); + assert(!guarded.verify_guards(), "Expected failed"); + os::free(freep); + + // Test a number of odd sizes... + size_t sz = 0; + do { + void* p = os::malloc(GuardedMemory::get_total_size(sz), mtInternal); + void* up = guarded.wrap_with_guards(p, sz, (void*)1); + memset(up, 0, sz); + guarded_memory_test_check(up, sz, (void*)1); + os::free(guarded.release_for_freeing()); + sz = (sz << 4) + 1; + } while (sz < (256 * 1024)); + + // Test buffer overrun into head... + basep = (u_char*) os::malloc(GuardedMemory::get_total_size(1), mtInternal); + guarded.wrap_with_guards(basep, 1); + *basep = 0; + assert(!guarded.verify_guards(), "Expected failure"); + os::free(basep); + + // Test buffer overrun into tail with a number of odd sizes... + sz = 1; + do { + void* p = os::malloc(GuardedMemory::get_total_size(sz), mtInternal); + void* up = guarded.wrap_with_guards(p, sz, (void*)1); + memset(up, 0, sz + 1); // Buffer-overwrite (within guard) + assert(!guarded.verify_guards(), "Guard was not broken as expected"); + os::free(guarded.release_for_freeing()); + sz = (sz << 4) + 1; + } while (sz < (256 * 1024)); + + // Test wrap_copy/wrap_free... + assert(GuardedMemory::free_copy(NULL), "Expected free NULL to be OK"); + + const char* str = "Check my bounds out"; + size_t str_sz = strlen(str) + 1; + char* str_copy = (char*) GuardedMemory::wrap_copy(str, str_sz); + guarded_memory_test_check(str_copy, str_sz, NULL); + assert(strcmp(str, str_copy) == 0, "Not identical copy"); + assert(GuardedMemory::free_copy(str_copy), "Free copy failed to verify"); + + void* no_data = NULL; + void* no_data_copy = GuardedMemory::wrap_copy(no_data, 0); + assert(GuardedMemory::free_copy(no_data_copy), "Expected valid guards even for no data copy"); +} + +#endif // !PRODUCT + diff --git a/hotspot/src/share/vm/memory/guardedMemory.hpp b/hotspot/src/share/vm/memory/guardedMemory.hpp new file mode 100644 index 00000000000..0d37bb03361 --- /dev/null +++ b/hotspot/src/share/vm/memory/guardedMemory.hpp @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#ifndef SHARE_VM_MEMORY_GUARDED_MEMORY_HPP +#define SHARE_VM_MEMORY_GUARDED_MEMORY_HPP + +#include "memory/allocation.hpp" +#include "utilities/globalDefinitions.hpp" + +/** + * Guarded memory for detecting buffer overrun. + * + * Allows allocations to be wrapped with padded bytes of a known byte pattern, + * that is a "guard". Guard patterns may be verified to detect buffer overruns. + * + * Primarily used by "debug malloc" and "checked JNI". + * + * Memory layout: + * + * |Offset | Content | Description | + * |------------------------------------------------------------ + * |base_addr | 0xABABABABABABABAB | Head guard | + * |+16 | | User data size | + * |+sizeof(uintptr_t) | | Tag word | + * |+sizeof(void*) | 0xF1 ( | User data | + * |+user_size | 0xABABABABABABABAB | Tail guard | + * ------------------------------------------------------------- + * + * Where: + * - guard padding uses "badResourceValue" (0xAB) + * - tag word is general purpose + * - user data + * -- initially padded with "uninitBlockPad" (0xF1), + * -- to "freeBlockPad" (0xBA), when freed + * + * Usage: + * + * * Allocations: one may wrap allocations with guard memory: + * + * Thing* alloc_thing() { + * void* mem = user_alloc_fn(GuardedMemory::get_total_size(sizeof(thing))); + * GuardedMemory guarded(mem, sizeof(thing)); + * return (Thing*) guarded.get_user_ptr(); + * } + * + * * Verify: memory guards are still in tact + * + * bool verify_thing(Thing* thing) { + * GuardedMemory guarded((void*)thing); + * return guarded.verify_guards(); + * } + * + * * Free: one may mark bytes as freed (further debugging support) + * + * void free_thing(Thing* thing) { + * GuardedMemory guarded((void*)thing); + * assert(guarded.verify_guards(), "Corrupt thing"); + * user_free_fn(guards.release_for_freeing(); + * } + * + */ +class GuardedMemory : StackObj { // Wrapper on stack + + // Private inner classes for memory layout... + +protected: + + /** + * Guard class for header and trailer known pattern to test for overwrites. + */ + class Guard { // Class for raw memory (no vtbl allowed) + friend class GuardedMemory; + protected: + enum { + GUARD_SIZE = 16 + }; + + u_char _guard[GUARD_SIZE]; + + public: + + void build() { + u_char* c = _guard; // Possibly unaligned if tail guard + u_char* end = c + GUARD_SIZE; + while (c < end) { + *c = badResourceValue; + c++; + } + } + + bool verify() const { + u_char* c = (u_char*) _guard; + u_char* end = c + GUARD_SIZE; + while (c < end) { + if (*c != badResourceValue) { + return false; + } + c++; + } + return true; + } + + }; // GuardedMemory::Guard + + /** + * Header guard and size + */ + class GuardHeader : Guard { + friend class GuardedMemory; + protected: + // Take care in modifying fields here, will effect alignment + // e.g. x86 ABI 16 byte stack alignment + union { + uintptr_t __unused_full_word1; + size_t _user_size; + }; + void* _tag; + public: + void set_user_size(const size_t usz) { _user_size = usz; } + size_t get_user_size() const { return _user_size; } + + void set_tag(const void* tag) { _tag = (void*) tag; } + void* get_tag() const { return _tag; } + + }; // GuardedMemory::GuardHeader + + // Guarded Memory... + + protected: + u_char* _base_addr; + + public: + + /** + * Create new guarded memory. + * + * Wraps, starting at the given "base_ptr" with guards. Use "get_user_ptr()" + * to return a pointer suitable for user data. + * + * @param base_ptr allocation wishing to be wrapped, must be at least "GuardedMemory::get_total_size()" bytes. + * @param user_size the size of the user data to be wrapped. + * @param tag optional general purpose tag. + */ + GuardedMemory(void* base_ptr, const size_t user_size, const void* tag = NULL) { + wrap_with_guards(base_ptr, user_size, tag); + } + + /** + * Wrap existing guarded memory. + * + * To use this constructor, one must have created guarded memory with + * "GuardedMemory(void*, size_t, void*)" (or indirectly via helper, e.g. "wrap_copy()"). + * + * @param user_p existing wrapped memory. + */ + GuardedMemory(void* userp) { + u_char* user_ptr = (u_char*) userp; + assert((uintptr_t)user_ptr > (sizeof(GuardHeader) + 0x1000), "Invalid pointer"); + _base_addr = (user_ptr - sizeof(GuardHeader)); + } + + /** + * Create new guarded memory. + * + * Wraps, starting at the given "base_ptr" with guards. Allows reuse of stack allocated helper. + * + * @param base_ptr allocation wishing to be wrapped, must be at least "GuardedMemory::get_total_size()" bytes. + * @param user_size the size of the user data to be wrapped. + * @param tag optional general purpose tag. + * + * @return user data pointer (inner pointer to supplied "base_ptr"). + */ + void* wrap_with_guards(void* base_ptr, size_t user_size, const void* tag = NULL) { + assert(base_ptr != NULL, "Attempt to wrap NULL with memory guard"); + _base_addr = (u_char*)base_ptr; + get_head_guard()->build(); + get_head_guard()->set_user_size(user_size); + get_tail_guard()->build(); + set_tag(tag); + set_user_bytes(uninitBlockPad); + assert(verify_guards(), "Expected valid memory guards"); + return get_user_ptr(); + } + + /** + * Verify head and tail guards. + * + * @return true if guards are intact, false would indicate a buffer overrun. + */ + bool verify_guards() const { + if (_base_addr != NULL) { + return (get_head_guard()->verify() && get_tail_guard()->verify()); + } + return false; + } + + /** + * Set the general purpose tag. + * + * @param tag general purpose tag. + */ + void set_tag(const void* tag) { get_head_guard()->set_tag(tag); } + + /** + * Return the general purpose tag. + * + * @return the general purpose tag, defaults to NULL. + */ + void* get_tag() const { return get_head_guard()->get_tag(); } + + /** + * Return the size of the user data. + * + * @return the size of the user data. + */ + size_t get_user_size() const { + assert(_base_addr != NULL, "Not wrapping any memory"); + return get_head_guard()->get_user_size(); + } + + /** + * Return the user data pointer. + * + * @return the user data pointer. + */ + u_char* get_user_ptr() const { + assert(_base_addr != NULL, "Not wrapping any memory"); + return _base_addr + sizeof(GuardHeader); + } + + /** + * Release the wrapped pointer for resource freeing. + * + * Pads the user data with "freeBlockPad", and dis-associates the helper. + * + * @return the original base pointer used to wrap the data. + */ + void* release_for_freeing() { + set_user_bytes(freeBlockPad); + return release(); + } + + /** + * Dis-associate the help from the original base address. + * + * @return the original base pointer used to wrap the data. + */ + void* release() { + void* p = (void*) _base_addr; + _base_addr = NULL; + return p; + } + + virtual void print_on(outputStream* st) const; + + protected: + GuardHeader* get_head_guard() const { return (GuardHeader*) _base_addr; } + Guard* get_tail_guard() const { return (Guard*) (get_user_ptr() + get_user_size()); }; + void set_user_bytes(u_char ch) { + memset(get_user_ptr(), ch, get_user_size()); + } + + public: + /** + * Return the total size required for wrapping the given user size. + * + * @return the total size required for wrapping the given user size. + */ + static size_t get_total_size(size_t user_size) { + size_t total_size = sizeof(GuardHeader) + user_size + sizeof(Guard); + assert(total_size > user_size, "Unexpected wrap-around"); + return total_size; + } + + // Helper functions... + + /** + * Wrap a copy of size "len" of "ptr". + * + * @param ptr the memory to be copied + * @param len the length of the copy + * @param tag optional general purpose tag (see GuardedMemory::get_tag()) + * + * @return guarded wrapped memory pointer to the user area, or NULL if OOM. + */ + static void* wrap_copy(const void* p, const size_t len, const void* tag = NULL); + + /** + * Free wrapped copy. + * + * Frees memory copied with "wrap_copy()". + * + * @param p memory returned by "wrap_copy()". + * + * @return true if guards were verified as intact. false indicates a buffer overrun. + */ + static bool free_copy(void* p); + + // Testing... +#ifndef PRODUCT + static void test_guarded_memory(void); +#endif +}; // GuardedMemory + +#endif // SHARE_VM_MEMORY_GUARDED_MEMORY_HPP diff --git a/hotspot/src/share/vm/memory/metaspace.cpp b/hotspot/src/share/vm/memory/metaspace.cpp index d2d1ba7992e..2f52e388d52 100644 --- a/hotspot/src/share/vm/memory/metaspace.cpp +++ b/hotspot/src/share/vm/memory/metaspace.cpp @@ -697,6 +697,7 @@ class SpaceManager : public CHeapObj { size_t allocated_blocks_words() const { return _allocated_blocks_words; } size_t allocated_blocks_bytes() const { return _allocated_blocks_words * BytesPerWord; } size_t allocated_chunks_words() const { return _allocated_chunks_words; } + size_t allocated_chunks_bytes() const { return _allocated_chunks_words * BytesPerWord; } size_t allocated_chunks_count() const { return _allocated_chunks_count; } bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); } @@ -3365,6 +3366,16 @@ size_t Metaspace::capacity_bytes_slow(MetadataType mdtype) const { return capacity_words_slow(mdtype) * BytesPerWord; } +size_t Metaspace::allocated_blocks_bytes() const { + return vsm()->allocated_blocks_bytes() + + (using_class_space() ? class_vsm()->allocated_blocks_bytes() : 0); +} + +size_t Metaspace::allocated_chunks_bytes() const { + return vsm()->allocated_chunks_bytes() + + (using_class_space() ? class_vsm()->allocated_chunks_bytes() : 0); +} + void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) { assert(!SafepointSynchronize::is_at_safepoint() || Thread::current()->is_VM_thread(), "should be the VM thread"); diff --git a/hotspot/src/share/vm/memory/metaspace.hpp b/hotspot/src/share/vm/memory/metaspace.hpp index baa25cd6d35..545bf0e7fbd 100644 --- a/hotspot/src/share/vm/memory/metaspace.hpp +++ b/hotspot/src/share/vm/memory/metaspace.hpp @@ -226,6 +226,9 @@ class Metaspace : public CHeapObj { size_t used_bytes_slow(MetadataType mdtype) const; size_t capacity_bytes_slow(MetadataType mdtype) const; + size_t allocated_blocks_bytes() const; + size_t allocated_chunks_bytes() const; + static MetaWord* allocate(ClassLoaderData* loader_data, size_t word_size, bool read_only, MetaspaceObj::Type type, TRAPS); void deallocate(MetaWord* ptr, size_t byte_size, bool is_class); diff --git a/hotspot/src/share/vm/memory/universe.cpp b/hotspot/src/share/vm/memory/universe.cpp index 0250f1a1b8d..5053b46e8c8 100644 --- a/hotspot/src/share/vm/memory/universe.cpp +++ b/hotspot/src/share/vm/memory/universe.cpp @@ -1000,9 +1000,6 @@ void universe2_init() { } -// This function is defined in JVM.cpp -extern void initialize_converter_functions(); - bool universe_post_init() { assert(!is_init_completed(), "Error: initialization not yet completed!"); Universe::_fully_initialized = true; @@ -1144,11 +1141,6 @@ bool universe_post_init() { SystemDictionary::ProtectionDomain_klass(), m);; } - // The following is initializing converter functions for serialization in - // JVM.cpp. If we clean up the StrictMath code above we may want to find - // a better solution for this as well. - initialize_converter_functions(); - // This needs to be done before the first scavenge/gc, since // it's an input to soft ref clearing policy. { diff --git a/hotspot/src/share/vm/oops/method.cpp b/hotspot/src/share/vm/oops/method.cpp index 01ef61f2386..4549c68871f 100644 --- a/hotspot/src/share/vm/oops/method.cpp +++ b/hotspot/src/share/vm/oops/method.cpp @@ -1023,8 +1023,7 @@ bool Method::is_ignored_by_security_stack_walk() const { // This is Method.invoke() -- ignore it return true; } - if (JDK_Version::is_gte_jdk14x_version() && - method_holder()->is_subclass_of(SystemDictionary::reflect_MethodAccessorImpl_klass())) { + if (method_holder()->is_subclass_of(SystemDictionary::reflect_MethodAccessorImpl_klass())) { // This is an auxilary frame -- ignore it return true; } diff --git a/hotspot/src/share/vm/prims/jni.cpp b/hotspot/src/share/vm/prims/jni.cpp index 6bbe5feb691..cdb53afe1b7 100644 --- a/hotspot/src/share/vm/prims/jni.cpp +++ b/hotspot/src/share/vm/prims/jni.cpp @@ -3858,6 +3858,7 @@ _JNI_IMPORT_OR_EXPORT_ jint JNICALL JNI_GetDefaultJavaVMInitArgs(void *args_) { #if INCLUDE_ALL_GCS #include "gc_implementation/g1/heapRegionRemSet.hpp" #endif +#include "memory/guardedMemory.hpp" #include "utilities/quickSort.hpp" #include "utilities/ostream.hpp" #if INCLUDE_VM_STRUCTS @@ -3901,6 +3902,7 @@ void execute_internal_vm_tests() { run_unit_test(arrayOopDesc::test_max_array_length()); run_unit_test(CollectedHeap::test_is_in()); run_unit_test(QuickSort::test_quick_sort()); + run_unit_test(GuardedMemory::test_guarded_memory()); run_unit_test(AltHashing::test_alt_hash()); run_unit_test(test_loggc_filename()); run_unit_test(TestNewSize_test()); diff --git a/hotspot/src/share/vm/prims/jniCheck.cpp b/hotspot/src/share/vm/prims/jniCheck.cpp index 0d5ffab1cdc..cdce2643775 100644 --- a/hotspot/src/share/vm/prims/jniCheck.cpp +++ b/hotspot/src/share/vm/prims/jniCheck.cpp @@ -25,6 +25,7 @@ #include "precompiled.hpp" #include "classfile/systemDictionary.hpp" #include "classfile/vmSymbols.hpp" +#include "memory/guardedMemory.hpp" #include "oops/instanceKlass.hpp" #include "oops/oop.inline.hpp" #include "oops/symbol.hpp" @@ -52,6 +53,8 @@ # include "jniTypes_ppc.hpp" #endif +// Complain every extra number of unplanned local refs +#define CHECK_JNI_LOCAL_REF_CAP_WARN_THRESHOLD 32 // Heap objects are allowed to be directly referenced only in VM code, // not in native code. @@ -167,12 +170,42 @@ static void NativeReportJNIWarning(JavaThread* thr, const char *msg) { * SUPPORT FUNCTIONS */ +/** + * Check whether or not a programmer has actually checked for exceptions. According + * to the JNI Specification ("jni/spec/design.html#java_exceptions"): + * + * There are two cases where the programmer needs to check for exceptions without + * being able to first check an error code: + * + * - The JNI functions that invoke a Java method return the result of the Java method. + * The programmer must call ExceptionOccurred() to check for possible exceptions + * that occurred during the execution of the Java method. + * + * - Some of the JNI array access functions do not return an error code, but may + * throw an ArrayIndexOutOfBoundsException or ArrayStoreException. + * + * In all other cases, a non-error return value guarantees that no exceptions have been thrown. + */ static inline void -functionEnterCritical(JavaThread* thr) -{ +check_pending_exception(JavaThread* thr) { if (thr->has_pending_exception()) { NativeReportJNIWarning(thr, "JNI call made with exception pending"); } + if (thr->is_pending_jni_exception_check()) { + IN_VM( + tty->print_cr("WARNING in native method: JNI call made without checking exceptions when required to from %s", + thr->get_pending_jni_exception_check()); + thr->print_stack(); + ) + thr->clear_pending_jni_exception_check(); // Just complain once + } +} + + +static inline void +functionEnterCritical(JavaThread* thr) +{ + check_pending_exception(thr); } static inline void @@ -186,9 +219,7 @@ functionEnter(JavaThread* thr) if (thr->in_critical()) { tty->print_cr("%s", warn_other_function_in_critical); } - if (thr->has_pending_exception()) { - NativeReportJNIWarning(thr, "JNI call made with exception pending"); - } + check_pending_exception(thr); } static inline void @@ -200,9 +231,20 @@ functionEnterExceptionAllowed(JavaThread* thr) } static inline void -functionExit(JNIEnv *env) +functionExit(JavaThread* thr) { - /* nothing to do at this time */ + JNIHandleBlock* handles = thr->active_handles(); + size_t planned_capacity = handles->get_planned_capacity(); + size_t live_handles = handles->get_number_of_live_handles(); + if (live_handles > planned_capacity) { + IN_VM( + tty->print_cr("WARNING: JNI local refs: %zu, exceeds capacity: %zu", + live_handles, planned_capacity); + thr->print_stack(); + ) + // Complain just the once, reset to current + warn threshold + handles->set_planned_capacity(live_handles + CHECK_JNI_LOCAL_REF_CAP_WARN_THRESHOLD); + } } static inline void @@ -323,6 +365,74 @@ check_is_obj_array(JavaThread* thr, jarray jArray) { } } +/* + * Copy and wrap array elements for bounds checking. + * Remember the original elements (GuardedMemory::get_tag()) + */ +static void* check_jni_wrap_copy_array(JavaThread* thr, jarray array, + void* orig_elements) { + void* result; + IN_VM( + oop a = JNIHandles::resolve_non_null(array); + size_t len = arrayOop(a)->length() << + TypeArrayKlass::cast(a->klass())->log2_element_size(); + result = GuardedMemory::wrap_copy(orig_elements, len, orig_elements); + ) + return result; +} + +static void* check_wrapped_array(JavaThread* thr, const char* fn_name, + void* obj, void* carray, size_t* rsz) { + if (carray == NULL) { + tty->print_cr("%s: elements vector NULL" PTR_FORMAT, fn_name, p2i(obj)); + NativeReportJNIFatalError(thr, "Elements vector NULL"); + } + GuardedMemory guarded(carray); + void* orig_result = guarded.get_tag(); + if (!guarded.verify_guards()) { + tty->print_cr("ReleasePrimitiveArrayCritical: release array failed bounds " + "check, incorrect pointer returned ? array: " PTR_FORMAT " carray: " + PTR_FORMAT, p2i(obj), p2i(carray)); + guarded.print_on(tty); + NativeReportJNIFatalError(thr, "ReleasePrimitiveArrayCritical: " + "failed bounds check"); + } + if (orig_result == NULL) { + tty->print_cr("ReleasePrimitiveArrayCritical: unrecognized elements. array: " + PTR_FORMAT " carray: " PTR_FORMAT, p2i(obj), p2i(carray)); + guarded.print_on(tty); + NativeReportJNIFatalError(thr, "ReleasePrimitiveArrayCritical: " + "unrecognized elements"); + } + if (rsz != NULL) { + *rsz = guarded.get_user_size(); + } + return orig_result; +} + +static void* check_wrapped_array_release(JavaThread* thr, const char* fn_name, + void* obj, void* carray, jint mode) { + size_t sz; + void* orig_result = check_wrapped_array(thr, fn_name, obj, carray, &sz); + switch (mode) { + case 0: + memcpy(orig_result, carray, sz); + GuardedMemory::free_copy(carray); + break; + case JNI_COMMIT: + memcpy(orig_result, carray, sz); + break; + case JNI_ABORT: + GuardedMemory::free_copy(carray); + break; + default: + tty->print_cr("%s: Unrecognized mode %i releasing array " + PTR_FORMAT " elements " PTR_FORMAT, fn_name, mode, p2i(obj), p2i(carray)); + NativeReportJNIFatalError(thr, "Unrecognized array release mode"); + } + return orig_result; +} + oop jniCheck::validate_handle(JavaThread* thr, jobject obj) { if (JNIHandles::is_frame_handle(thr, obj) || JNIHandles::is_local_handle(thr, obj) || @@ -439,7 +549,7 @@ JNI_ENTRY_CHECKED(jclass, jniCheck::validate_object(thr, loader); ) jclass result = UNCHECKED()->DefineClass(env, name, loader, buf, len); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -451,7 +561,7 @@ JNI_ENTRY_CHECKED(jclass, jniCheck::validate_class_descriptor(thr, name); ) jclass result = UNCHECKED()->FindClass(env, name); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -463,7 +573,7 @@ JNI_ENTRY_CHECKED(jmethodID, jniCheck::validate_object(thr, method); ) jmethodID result = UNCHECKED()->FromReflectedMethod(env, method); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -475,7 +585,7 @@ JNI_ENTRY_CHECKED(jfieldID, jniCheck::validate_object(thr, field); ) jfieldID result = UNCHECKED()->FromReflectedField(env, field); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -491,7 +601,7 @@ JNI_ENTRY_CHECKED(jobject, ) jobject result = UNCHECKED()->ToReflectedMethod(env, cls, methodID, isStatic); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -503,7 +613,7 @@ JNI_ENTRY_CHECKED(jclass, jniCheck::validate_class(thr, sub, true); ) jclass result = UNCHECKED()->GetSuperclass(env, sub); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -517,7 +627,7 @@ JNI_ENTRY_CHECKED(jboolean, jniCheck::validate_class(thr, sup, true); ) jboolean result = UNCHECKED()->IsAssignableFrom(env, sub, sup); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -532,7 +642,7 @@ JNI_ENTRY_CHECKED(jobject, ) jobject result = UNCHECKED()->ToReflectedField(env, cls, fieldID, isStatic); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -550,7 +660,7 @@ JNI_ENTRY_CHECKED(jint, } ) jint result = UNCHECKED()->Throw(env, obj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -565,15 +675,16 @@ JNI_ENTRY_CHECKED(jint, jniCheck::validate_throwable_klass(thr, k); ) jint result = UNCHECKED()->ThrowNew(env, clazz, msg); - functionExit(env); + functionExit(thr); return result; JNI_END JNI_ENTRY_CHECKED(jthrowable, checked_jni_ExceptionOccurred(JNIEnv *env)) + thr->clear_pending_jni_exception_check(); functionEnterExceptionAllowed(thr); jthrowable result = UNCHECKED()->ExceptionOccurred(env); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -581,22 +692,24 @@ JNI_ENTRY_CHECKED(void, checked_jni_ExceptionDescribe(JNIEnv *env)) functionEnterExceptionAllowed(thr); UNCHECKED()->ExceptionDescribe(env); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, checked_jni_ExceptionClear(JNIEnv *env)) + thr->clear_pending_jni_exception_check(); functionEnterExceptionAllowed(thr); UNCHECKED()->ExceptionClear(env); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, checked_jni_FatalError(JNIEnv *env, const char *msg)) + thr->clear_pending_jni_exception_check(); functionEnter(thr); UNCHECKED()->FatalError(env, msg); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jint, @@ -606,7 +719,10 @@ JNI_ENTRY_CHECKED(jint, if (capacity < 0) NativeReportJNIFatalError(thr, "negative capacity"); jint result = UNCHECKED()->PushLocalFrame(env, capacity); - functionExit(env); + if (result == JNI_OK) { + thr->active_handles()->set_planned_capacity(capacity + CHECK_JNI_LOCAL_REF_CAP_WARN_THRESHOLD); + } + functionExit(thr); return result; JNI_END @@ -615,7 +731,7 @@ JNI_ENTRY_CHECKED(jobject, jobject result)) functionEnterExceptionAllowed(thr); jobject res = UNCHECKED()->PopLocalFrame(env, result); - functionExit(env); + functionExit(thr); return res; JNI_END @@ -629,7 +745,7 @@ JNI_ENTRY_CHECKED(jobject, } ) jobject result = UNCHECKED()->NewGlobalRef(env,lobj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -645,7 +761,7 @@ JNI_ENTRY_CHECKED(void, } ) UNCHECKED()->DeleteGlobalRef(env,gref); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -660,7 +776,7 @@ JNI_ENTRY_CHECKED(void, "Invalid local JNI handle passed to DeleteLocalRef"); ) UNCHECKED()->DeleteLocalRef(env, obj); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jboolean, @@ -681,7 +797,7 @@ JNI_ENTRY_CHECKED(jboolean, } ) jboolean result = UNCHECKED()->IsSameObject(env,obj1,obj2); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -695,7 +811,7 @@ JNI_ENTRY_CHECKED(jobject, } ) jobject result = UNCHECKED()->NewLocalRef(env, ref); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -707,7 +823,10 @@ JNI_ENTRY_CHECKED(jint, NativeReportJNIFatalError(thr, "negative capacity"); } jint result = UNCHECKED()->EnsureLocalCapacity(env, capacity); - functionExit(env); + if (result == JNI_OK) { + thr->active_handles()->set_planned_capacity(capacity + CHECK_JNI_LOCAL_REF_CAP_WARN_THRESHOLD); + } + functionExit(thr); return result; JNI_END @@ -719,7 +838,7 @@ JNI_ENTRY_CHECKED(jobject, jniCheck::validate_class(thr, clazz, false); ) jobject result = UNCHECKED()->AllocObject(env,clazz); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -737,7 +856,7 @@ JNI_ENTRY_CHECKED(jobject, va_start(args, methodID); jobject result = UNCHECKED()->NewObjectV(env,clazz,methodID,args); va_end(args); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -752,7 +871,7 @@ JNI_ENTRY_CHECKED(jobject, jniCheck::validate_jmethod_id(thr, methodID); ) jobject result = UNCHECKED()->NewObjectV(env,clazz,methodID,args); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -767,7 +886,7 @@ JNI_ENTRY_CHECKED(jobject, jniCheck::validate_jmethod_id(thr, methodID); ) jobject result = UNCHECKED()->NewObjectA(env,clazz,methodID,args); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -779,7 +898,7 @@ JNI_ENTRY_CHECKED(jclass, jniCheck::validate_object(thr, obj); ) jclass result = UNCHECKED()->GetObjectClass(env,obj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -793,7 +912,7 @@ JNI_ENTRY_CHECKED(jboolean, jniCheck::validate_class(thr, clazz, true); ) jboolean result = UNCHECKED()->IsInstanceOf(env,obj,clazz); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -807,7 +926,7 @@ JNI_ENTRY_CHECKED(jmethodID, jniCheck::validate_class(thr, clazz, false); ) jmethodID result = UNCHECKED()->GetMethodID(env,clazz,name,sig); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -826,7 +945,8 @@ JNI_ENTRY_CHECKED(ResultType, \ ResultType result =UNCHECKED()->Call##Result##MethodV(env, obj, methodID, \ args); \ va_end(args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("Call"#Result"Method"); \ + functionExit(thr); \ return result; \ JNI_END \ \ @@ -841,7 +961,8 @@ JNI_ENTRY_CHECKED(ResultType, \ ) \ ResultType result = UNCHECKED()->Call##Result##MethodV(env, obj, methodID,\ args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("Call"#Result"MethodV"); \ + functionExit(thr); \ return result; \ JNI_END \ \ @@ -856,7 +977,8 @@ JNI_ENTRY_CHECKED(ResultType, \ ) \ ResultType result = UNCHECKED()->Call##Result##MethodA(env, obj, methodID,\ args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("Call"#Result"MethodA"); \ + functionExit(thr); \ return result; \ JNI_END @@ -883,7 +1005,8 @@ JNI_ENTRY_CHECKED(void, va_start(args,methodID); UNCHECKED()->CallVoidMethodV(env,obj,methodID,args); va_end(args); - functionExit(env); + thr->set_pending_jni_exception_check("CallVoidMethod"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -896,7 +1019,8 @@ JNI_ENTRY_CHECKED(void, jniCheck::validate_call_object(thr, obj, methodID); ) UNCHECKED()->CallVoidMethodV(env,obj,methodID,args); - functionExit(env); + thr->set_pending_jni_exception_check("CallVoidMethodV"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -909,7 +1033,8 @@ JNI_ENTRY_CHECKED(void, jniCheck::validate_call_object(thr, obj, methodID); ) UNCHECKED()->CallVoidMethodA(env,obj,methodID,args); - functionExit(env); + thr->set_pending_jni_exception_check("CallVoidMethodA"); + functionExit(thr); JNI_END #define WRAPPER_CallNonvirtualMethod(ResultType, Result) \ @@ -932,7 +1057,8 @@ JNI_ENTRY_CHECKED(ResultType, \ methodID,\ args); \ va_end(args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("CallNonvirtual"#Result"Method"); \ + functionExit(thr); \ return result; \ JNI_END \ \ @@ -952,7 +1078,8 @@ JNI_ENTRY_CHECKED(ResultType, \ clazz, \ methodID,\ args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("CallNonvirtual"#Result"MethodV"); \ + functionExit(thr); \ return result; \ JNI_END \ \ @@ -972,7 +1099,8 @@ JNI_ENTRY_CHECKED(ResultType, \ clazz, \ methodID,\ args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("CallNonvirtual"#Result"MethodA"); \ + functionExit(thr); \ return result; \ JNI_END @@ -1001,7 +1129,8 @@ JNI_ENTRY_CHECKED(void, va_start(args,methodID); UNCHECKED()->CallNonvirtualVoidMethodV(env,obj,clazz,methodID,args); va_end(args); - functionExit(env); + thr->set_pending_jni_exception_check("CallNonvirtualVoidMethod"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -1016,7 +1145,8 @@ JNI_ENTRY_CHECKED(void, jniCheck::validate_call_class(thr, clazz, methodID); ) UNCHECKED()->CallNonvirtualVoidMethodV(env,obj,clazz,methodID,args); - functionExit(env); + thr->set_pending_jni_exception_check("CallNonvirtualVoidMethodV"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -1031,7 +1161,8 @@ JNI_ENTRY_CHECKED(void, jniCheck::validate_call_class(thr, clazz, methodID); ) UNCHECKED()->CallNonvirtualVoidMethodA(env,obj,clazz,methodID,args); - functionExit(env); + thr->set_pending_jni_exception_check("CallNonvirtualVoidMethodA"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jfieldID, @@ -1044,7 +1175,7 @@ JNI_ENTRY_CHECKED(jfieldID, jniCheck::validate_class(thr, clazz, false); ) jfieldID result = UNCHECKED()->GetFieldID(env,clazz,name,sig); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1058,7 +1189,7 @@ JNI_ENTRY_CHECKED(ReturnType, \ checkInstanceFieldID(thr, fieldID, obj, FieldType); \ ) \ ReturnType result = UNCHECKED()->Get##Result##Field(env,obj,fieldID); \ - functionExit(env); \ + functionExit(thr); \ return result; \ JNI_END @@ -1083,7 +1214,7 @@ JNI_ENTRY_CHECKED(void, \ checkInstanceFieldID(thr, fieldID, obj, FieldType); \ ) \ UNCHECKED()->Set##Result##Field(env,obj,fieldID,val); \ - functionExit(env); \ + functionExit(thr); \ JNI_END WRAPPER_SetField(jobject, Object, T_OBJECT) @@ -1107,7 +1238,7 @@ JNI_ENTRY_CHECKED(jmethodID, jniCheck::validate_class(thr, clazz, false); ) jmethodID result = UNCHECKED()->GetStaticMethodID(env,clazz,name,sig); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1129,7 +1260,8 @@ JNI_ENTRY_CHECKED(ReturnType, \ methodID, \ args); \ va_end(args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("CallStatic"#Result"Method"); \ + functionExit(thr); \ return result; \ JNI_END \ \ @@ -1147,7 +1279,8 @@ JNI_ENTRY_CHECKED(ReturnType, \ clazz, \ methodID, \ args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("CallStatic"#Result"MethodV"); \ + functionExit(thr); \ return result; \ JNI_END \ \ @@ -1165,7 +1298,8 @@ JNI_ENTRY_CHECKED(ReturnType, \ clazz, \ methodID, \ args); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("CallStatic"#Result"MethodA"); \ + functionExit(thr); \ return result; \ JNI_END @@ -1193,7 +1327,8 @@ JNI_ENTRY_CHECKED(void, va_start(args,methodID); UNCHECKED()->CallStaticVoidMethodV(env,cls,methodID,args); va_end(args); - functionExit(env); + thr->set_pending_jni_exception_check("CallStaticVoidMethod"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -1207,7 +1342,8 @@ JNI_ENTRY_CHECKED(void, jniCheck::validate_class(thr, cls, false); ) UNCHECKED()->CallStaticVoidMethodV(env,cls,methodID,args); - functionExit(env); + thr->set_pending_jni_exception_check("CallStaticVoidMethodV"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -1221,7 +1357,8 @@ JNI_ENTRY_CHECKED(void, jniCheck::validate_class(thr, cls, false); ) UNCHECKED()->CallStaticVoidMethodA(env,cls,methodID,args); - functionExit(env); + thr->set_pending_jni_exception_check("CallStaticVoidMethodA"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jfieldID, @@ -1234,7 +1371,7 @@ JNI_ENTRY_CHECKED(jfieldID, jniCheck::validate_class(thr, clazz, false); ) jfieldID result = UNCHECKED()->GetStaticFieldID(env,clazz,name,sig); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1251,7 +1388,7 @@ JNI_ENTRY_CHECKED(ReturnType, \ ReturnType result = UNCHECKED()->GetStatic##Result##Field(env, \ clazz, \ fieldID); \ - functionExit(env); \ + functionExit(thr); \ return result; \ JNI_END @@ -1277,7 +1414,7 @@ JNI_ENTRY_CHECKED(void, \ checkStaticFieldID(thr, fieldID, clazz, FieldType); \ ) \ UNCHECKED()->SetStatic##Result##Field(env,clazz,fieldID,value); \ - functionExit(env); \ + functionExit(thr); \ JNI_END WRAPPER_SetStaticField(jobject, Object, T_OBJECT) @@ -1297,7 +1434,7 @@ JNI_ENTRY_CHECKED(jstring, jsize len)) functionEnter(thr); jstring result = UNCHECKED()->NewString(env,unicode,len); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1309,12 +1446,12 @@ JNI_ENTRY_CHECKED(jsize, checkString(thr, str); ) jsize result = UNCHECKED()->GetStringLength(env,str); - functionExit(env); + functionExit(thr); return result; JNI_END // Arbitrary (but well-known) tag -const jint STRING_TAG = 0x47114711; +const void* STRING_TAG = (void*)0x47114711; JNI_ENTRY_CHECKED(const jchar *, checked_jni_GetStringChars(JNIEnv *env, @@ -1324,21 +1461,22 @@ JNI_ENTRY_CHECKED(const jchar *, IN_VM( checkString(thr, str); ) - jchar* newResult = NULL; + jchar* new_result = NULL; const jchar *result = UNCHECKED()->GetStringChars(env,str,isCopy); assert (isCopy == NULL || *isCopy == JNI_TRUE, "GetStringChars didn't return a copy as expected"); if (result != NULL) { size_t len = UNCHECKED()->GetStringLength(env,str) + 1; // + 1 for NULL termination - jint* tagLocation = (jint*) AllocateHeap(len * sizeof(jchar) + sizeof(jint), mtInternal); - *tagLocation = STRING_TAG; - newResult = (jchar*) (tagLocation + 1); - memcpy(newResult, result, len * sizeof(jchar)); + len *= sizeof(jchar); + new_result = (jchar*) GuardedMemory::wrap_copy(result, len, STRING_TAG); + if (new_result == NULL) { + vm_exit_out_of_memory(len, OOM_MALLOC_ERROR, "checked_jni_GetStringChars"); + } // Avoiding call to UNCHECKED()->ReleaseStringChars() since that will fire unexpected dtrace probes // Note that the dtrace arguments for the allocated memory will not match up with this solution. FreeHeap((char*)result); } - functionExit(env); - return newResult; + functionExit(thr); + return new_result; JNI_END JNI_ENTRY_CHECKED(void, @@ -1354,13 +1492,25 @@ JNI_ENTRY_CHECKED(void, UNCHECKED()->ReleaseStringChars(env,str,chars); } else { - jint* tagLocation = ((jint*) chars) - 1; - if (*tagLocation != STRING_TAG) { - NativeReportJNIFatalError(thr, "ReleaseStringChars called on something not allocated by GetStringChars"); - } - UNCHECKED()->ReleaseStringChars(env,str,(const jchar*)tagLocation); + GuardedMemory guarded((void*)chars); + if (!guarded.verify_guards()) { + tty->print_cr("ReleaseStringChars: release chars failed bounds check. " + "string: " PTR_FORMAT " chars: " PTR_FORMAT, p2i(str), p2i(chars)); + guarded.print_on(tty); + NativeReportJNIFatalError(thr, "ReleaseStringChars: " + "release chars failed bounds check."); + } + if (guarded.get_tag() != STRING_TAG) { + tty->print_cr("ReleaseStringChars: called on something not allocated " + "by GetStringChars. string: " PTR_FORMAT " chars: " PTR_FORMAT, + p2i(str), p2i(chars)); + NativeReportJNIFatalError(thr, "ReleaseStringChars called on something " + "not allocated by GetStringChars"); + } + UNCHECKED()->ReleaseStringChars(env, str, + (const jchar*) guarded.release_for_freeing()); } - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jstring, @@ -1368,7 +1518,7 @@ JNI_ENTRY_CHECKED(jstring, const char *utf)) functionEnter(thr); jstring result = UNCHECKED()->NewStringUTF(env,utf); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1380,12 +1530,12 @@ JNI_ENTRY_CHECKED(jsize, checkString(thr, str); ) jsize result = UNCHECKED()->GetStringUTFLength(env,str); - functionExit(env); + functionExit(thr); return result; JNI_END // Arbitrary (but well-known) tag - different than GetStringChars -const jint STRING_UTF_TAG = 0x48124812; +const void* STRING_UTF_TAG = (void*) 0x48124812; JNI_ENTRY_CHECKED(const char *, checked_jni_GetStringUTFChars(JNIEnv *env, @@ -1395,21 +1545,21 @@ JNI_ENTRY_CHECKED(const char *, IN_VM( checkString(thr, str); ) - char* newResult = NULL; + char* new_result = NULL; const char *result = UNCHECKED()->GetStringUTFChars(env,str,isCopy); assert (isCopy == NULL || *isCopy == JNI_TRUE, "GetStringUTFChars didn't return a copy as expected"); if (result != NULL) { size_t len = strlen(result) + 1; // + 1 for NULL termination - jint* tagLocation = (jint*) AllocateHeap(len + sizeof(jint), mtInternal); - *tagLocation = STRING_UTF_TAG; - newResult = (char*) (tagLocation + 1); - strcpy(newResult, result); + new_result = (char*) GuardedMemory::wrap_copy(result, len, STRING_UTF_TAG); + if (new_result == NULL) { + vm_exit_out_of_memory(len, OOM_MALLOC_ERROR, "checked_jni_GetStringUTFChars"); + } // Avoiding call to UNCHECKED()->ReleaseStringUTFChars() since that will fire unexpected dtrace probes // Note that the dtrace arguments for the allocated memory will not match up with this solution. FreeHeap((char*)result, mtInternal); } - functionExit(env); - return newResult; + functionExit(thr); + return new_result; JNI_END JNI_ENTRY_CHECKED(void, @@ -1425,13 +1575,25 @@ JNI_ENTRY_CHECKED(void, UNCHECKED()->ReleaseStringUTFChars(env,str,chars); } else { - jint* tagLocation = ((jint*) chars) - 1; - if (*tagLocation != STRING_UTF_TAG) { - NativeReportJNIFatalError(thr, "ReleaseStringUTFChars called on something not allocated by GetStringUTFChars"); - } - UNCHECKED()->ReleaseStringUTFChars(env,str,(const char*)tagLocation); + GuardedMemory guarded((void*)chars); + if (!guarded.verify_guards()) { + tty->print_cr("ReleaseStringUTFChars: release chars failed bounds check. " + "string: " PTR_FORMAT " chars: " PTR_FORMAT, p2i(str), p2i(chars)); + guarded.print_on(tty); + NativeReportJNIFatalError(thr, "ReleaseStringUTFChars: " + "release chars failed bounds check."); + } + if (guarded.get_tag() != STRING_UTF_TAG) { + tty->print_cr("ReleaseStringUTFChars: called on something not " + "allocated by GetStringUTFChars. string: " PTR_FORMAT " chars: " + PTR_FORMAT, p2i(str), p2i(chars)); + NativeReportJNIFatalError(thr, "ReleaseStringUTFChars " + "called on something not allocated by GetStringUTFChars"); + } + UNCHECKED()->ReleaseStringUTFChars(env, str, + (const char*) guarded.release_for_freeing()); } - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jsize, @@ -1442,7 +1604,7 @@ JNI_ENTRY_CHECKED(jsize, check_is_array(thr, array); ) jsize result = UNCHECKED()->GetArrayLength(env,array); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1453,7 +1615,7 @@ JNI_ENTRY_CHECKED(jobjectArray, jobject init)) functionEnter(thr); jobjectArray result = UNCHECKED()->NewObjectArray(env,len,clazz,init); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1466,7 +1628,8 @@ JNI_ENTRY_CHECKED(jobject, check_is_obj_array(thr, array); ) jobject result = UNCHECKED()->GetObjectArrayElement(env,array,index); - functionExit(env); + thr->set_pending_jni_exception_check("GetObjectArrayElement"); + functionExit(thr); return result; JNI_END @@ -1480,7 +1643,8 @@ JNI_ENTRY_CHECKED(void, check_is_obj_array(thr, array); ) UNCHECKED()->SetObjectArrayElement(env,array,index,val); - functionExit(env); + thr->set_pending_jni_exception_check("SetObjectArrayElement"); + functionExit(thr); JNI_END #define WRAPPER_NewScalarArray(Return, Result) \ @@ -1489,7 +1653,7 @@ JNI_ENTRY_CHECKED(Return, \ jsize len)) \ functionEnter(thr); \ Return result = UNCHECKED()->New##Result##Array(env,len); \ - functionExit(env); \ + functionExit(thr); \ return (Return) result; \ JNI_END @@ -1514,7 +1678,10 @@ JNI_ENTRY_CHECKED(ElementType *, \ ElementType *result = UNCHECKED()->Get##Result##ArrayElements(env, \ array, \ isCopy); \ - functionExit(env); \ + if (result != NULL) { \ + result = (ElementType *) check_jni_wrap_copy_array(thr, array, result); \ + } \ + functionExit(thr); \ return result; \ JNI_END @@ -1538,13 +1705,11 @@ JNI_ENTRY_CHECKED(void, \ check_primitive_array_type(thr, array, ElementTag); \ ASSERT_OOPS_ALLOWED; \ typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(array)); \ - /* cannot check validity of copy, unless every request is logged by - * checking code. Implementation of this check is deferred until a - * subsequent release. - */ \ ) \ - UNCHECKED()->Release##Result##ArrayElements(env,array,elems,mode); \ - functionExit(env); \ + ElementType* orig_result = (ElementType *) check_wrapped_array_release( \ + thr, "checked_jni_Release"#Result"ArrayElements", array, elems, mode); \ + UNCHECKED()->Release##Result##ArrayElements(env, array, orig_result, mode); \ + functionExit(thr); \ JNI_END WRAPPER_ReleaseScalarArrayElements(T_BOOLEAN,jboolean, Boolean, bool) @@ -1568,7 +1733,8 @@ JNI_ENTRY_CHECKED(void, \ check_primitive_array_type(thr, array, ElementTag); \ ) \ UNCHECKED()->Get##Result##ArrayRegion(env,array,start,len,buf); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("Get"#Result"ArrayRegion"); \ + functionExit(thr); \ JNI_END WRAPPER_GetScalarArrayRegion(T_BOOLEAN, jboolean, Boolean) @@ -1592,7 +1758,8 @@ JNI_ENTRY_CHECKED(void, \ check_primitive_array_type(thr, array, ElementTag); \ ) \ UNCHECKED()->Set##Result##ArrayRegion(env,array,start,len,buf); \ - functionExit(env); \ + thr->set_pending_jni_exception_check("Set"#Result"ArrayRegion"); \ + functionExit(thr); \ JNI_END WRAPPER_SetScalarArrayRegion(T_BOOLEAN, jboolean, Boolean) @@ -1611,7 +1778,7 @@ JNI_ENTRY_CHECKED(jint, jint nMethods)) functionEnter(thr); jint result = UNCHECKED()->RegisterNatives(env,clazz,methods,nMethods); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1620,7 +1787,7 @@ JNI_ENTRY_CHECKED(jint, jclass clazz)) functionEnter(thr); jint result = UNCHECKED()->UnregisterNatives(env,clazz); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1632,7 +1799,7 @@ JNI_ENTRY_CHECKED(jint, jniCheck::validate_object(thr, obj); ) jint result = UNCHECKED()->MonitorEnter(env,obj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1644,7 +1811,7 @@ JNI_ENTRY_CHECKED(jint, jniCheck::validate_object(thr, obj); ) jint result = UNCHECKED()->MonitorExit(env,obj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1653,7 +1820,7 @@ JNI_ENTRY_CHECKED(jint, JavaVM **vm)) functionEnter(thr); jint result = UNCHECKED()->GetJavaVM(env,vm); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1668,7 +1835,8 @@ JNI_ENTRY_CHECKED(void, checkString(thr, str); ) UNCHECKED()->GetStringRegion(env, str, start, len, buf); - functionExit(env); + thr->set_pending_jni_exception_check("GetStringRegion"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void, @@ -1682,7 +1850,8 @@ JNI_ENTRY_CHECKED(void, checkString(thr, str); ) UNCHECKED()->GetStringUTFRegion(env, str, start, len, buf); - functionExit(env); + thr->set_pending_jni_exception_check("GetStringUTFRegion"); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(void *, @@ -1694,7 +1863,10 @@ JNI_ENTRY_CHECKED(void *, check_is_primitive_array(thr, array); ) void *result = UNCHECKED()->GetPrimitiveArrayCritical(env, array, isCopy); - functionExit(env); + if (result != NULL) { + result = check_jni_wrap_copy_array(thr, array, result); + } + functionExit(thr); return result; JNI_END @@ -1707,11 +1879,10 @@ JNI_ENTRY_CHECKED(void, IN_VM( check_is_primitive_array(thr, array); ) - /* The Hotspot JNI code does not use the parameters, so just check the - * array parameter as a minor sanity check - */ - UNCHECKED()->ReleasePrimitiveArrayCritical(env, array, carray, mode); - functionExit(env); + // Check the element array... + void* orig_result = check_wrapped_array_release(thr, "ReleasePrimitiveArrayCritical", array, carray, mode); + UNCHECKED()->ReleasePrimitiveArrayCritical(env, array, orig_result, mode); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(const jchar*, @@ -1723,7 +1894,7 @@ JNI_ENTRY_CHECKED(const jchar*, checkString(thr, string); ) const jchar *result = UNCHECKED()->GetStringCritical(env, string, isCopy); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1739,7 +1910,7 @@ JNI_ENTRY_CHECKED(void, * string parameter as a minor sanity check */ UNCHECKED()->ReleaseStringCritical(env, str, chars); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jweak, @@ -1752,7 +1923,7 @@ JNI_ENTRY_CHECKED(jweak, } ) jweak result = UNCHECKED()->NewWeakGlobalRef(env, obj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1761,14 +1932,15 @@ JNI_ENTRY_CHECKED(void, jweak ref)) functionEnterExceptionAllowed(thr); UNCHECKED()->DeleteWeakGlobalRef(env, ref); - functionExit(env); + functionExit(thr); JNI_END JNI_ENTRY_CHECKED(jboolean, checked_jni_ExceptionCheck(JNIEnv *env)) + thr->clear_pending_jni_exception_check(); functionEnterExceptionAllowed(thr); jboolean result = UNCHECKED()->ExceptionCheck(env); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1778,7 +1950,7 @@ JNI_ENTRY_CHECKED(jobject, jlong capacity)) functionEnter(thr); jobject result = UNCHECKED()->NewDirectByteBuffer(env, address, capacity); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1787,7 +1959,7 @@ JNI_ENTRY_CHECKED(void *, jobject buf)) functionEnter(thr); void* result = UNCHECKED()->GetDirectBufferAddress(env, buf); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1796,7 +1968,7 @@ JNI_ENTRY_CHECKED(jlong, jobject buf)) functionEnter(thr); jlong result = UNCHECKED()->GetDirectBufferCapacity(env, buf); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1809,7 +1981,7 @@ JNI_ENTRY_CHECKED(jobjectRefType, jniCheck::validate_object(thr, obj); ) jobjectRefType result = UNCHECKED()->GetObjectRefType(env, obj); - functionExit(env); + functionExit(thr); return result; JNI_END @@ -1818,7 +1990,7 @@ JNI_ENTRY_CHECKED(jint, checked_jni_GetVersion(JNIEnv *env)) functionEnter(thr); jint result = UNCHECKED()->GetVersion(env); - functionExit(env); + functionExit(thr); return result; JNI_END diff --git a/hotspot/src/share/vm/prims/jvm.cpp b/hotspot/src/share/vm/prims/jvm.cpp index 5b96377b24a..69e45bd11f7 100644 --- a/hotspot/src/share/vm/prims/jvm.cpp +++ b/hotspot/src/share/vm/prims/jvm.cpp @@ -3923,50 +3923,6 @@ JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) { } -// Support for Serialization - -typedef jfloat (JNICALL *IntBitsToFloatFn )(JNIEnv* env, jclass cb, jint value); -typedef jdouble (JNICALL *LongBitsToDoubleFn)(JNIEnv* env, jclass cb, jlong value); -typedef jint (JNICALL *FloatToIntBitsFn )(JNIEnv* env, jclass cb, jfloat value); -typedef jlong (JNICALL *DoubleToLongBitsFn)(JNIEnv* env, jclass cb, jdouble value); - -static IntBitsToFloatFn int_bits_to_float_fn = NULL; -static LongBitsToDoubleFn long_bits_to_double_fn = NULL; -static FloatToIntBitsFn float_to_int_bits_fn = NULL; -static DoubleToLongBitsFn double_to_long_bits_fn = NULL; - - -void initialize_converter_functions() { - if (JDK_Version::is_gte_jdk14x_version()) { - // These functions only exist for compatibility with 1.3.1 and earlier - return; - } - - // called from universe_post_init() - assert( - int_bits_to_float_fn == NULL && - long_bits_to_double_fn == NULL && - float_to_int_bits_fn == NULL && - double_to_long_bits_fn == NULL , - "initialization done twice" - ); - // initialize - int_bits_to_float_fn = CAST_TO_FN_PTR(IntBitsToFloatFn , NativeLookup::base_library_lookup("java/lang/Float" , "intBitsToFloat" , "(I)F")); - long_bits_to_double_fn = CAST_TO_FN_PTR(LongBitsToDoubleFn, NativeLookup::base_library_lookup("java/lang/Double", "longBitsToDouble", "(J)D")); - float_to_int_bits_fn = CAST_TO_FN_PTR(FloatToIntBitsFn , NativeLookup::base_library_lookup("java/lang/Float" , "floatToIntBits" , "(F)I")); - double_to_long_bits_fn = CAST_TO_FN_PTR(DoubleToLongBitsFn, NativeLookup::base_library_lookup("java/lang/Double", "doubleToLongBits", "(D)J")); - // verify - assert( - int_bits_to_float_fn != NULL && - long_bits_to_double_fn != NULL && - float_to_int_bits_fn != NULL && - double_to_long_bits_fn != NULL , - "initialization failed" - ); -} - - - // Shared JNI/JVM entry points ////////////////////////////////////////////////////////////// jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init, Handle loader, Handle protection_domain, jboolean throwError, TRAPS) { diff --git a/hotspot/src/share/vm/prims/unsafe.cpp b/hotspot/src/share/vm/prims/unsafe.cpp index 4dd10cfca57..332f8fb74ab 100644 --- a/hotspot/src/share/vm/prims/unsafe.cpp +++ b/hotspot/src/share/vm/prims/unsafe.cpp @@ -185,64 +185,7 @@ jint Unsafe_invocation_key_to_method_slot(jint key) { // Get/SetObject must be special-cased, since it works with handles. -// The xxx140 variants for backward compatibility do not allow a full-width offset. -UNSAFE_ENTRY(jobject, Unsafe_GetObject140(JNIEnv *env, jobject unsafe, jobject obj, jint offset)) - UnsafeWrapper("Unsafe_GetObject"); - if (obj == NULL) THROW_0(vmSymbols::java_lang_NullPointerException()); - GET_OOP_FIELD(obj, offset, v) - jobject ret = JNIHandles::make_local(env, v); -#if INCLUDE_ALL_GCS - // We could be accessing the referent field in a reference - // object. If G1 is enabled then we need to register a non-null - // referent with the SATB barrier. - if (UseG1GC) { - bool needs_barrier = false; - - if (ret != NULL) { - if (offset == java_lang_ref_Reference::referent_offset) { - oop o = JNIHandles::resolve_non_null(obj); - Klass* k = o->klass(); - if (InstanceKlass::cast(k)->reference_type() != REF_NONE) { - assert(InstanceKlass::cast(k)->is_subclass_of(SystemDictionary::Reference_klass()), "sanity"); - needs_barrier = true; - } - } - } - - if (needs_barrier) { - oop referent = JNIHandles::resolve(ret); - G1SATBCardTableModRefBS::enqueue(referent); - } - } -#endif // INCLUDE_ALL_GCS - return ret; -UNSAFE_END - -UNSAFE_ENTRY(void, Unsafe_SetObject140(JNIEnv *env, jobject unsafe, jobject obj, jint offset, jobject x_h)) - UnsafeWrapper("Unsafe_SetObject"); - if (obj == NULL) THROW(vmSymbols::java_lang_NullPointerException()); - oop x = JNIHandles::resolve(x_h); - //SET_FIELD(obj, offset, oop, x); - oop p = JNIHandles::resolve(obj); - if (UseCompressedOops) { - if (x != NULL) { - // If there is a heap base pointer, we are obliged to emit a store barrier. - oop_store((narrowOop*)index_oop_from_field_offset_long(p, offset), x); - } else { - narrowOop n = oopDesc::encode_heap_oop_not_null(x); - *(narrowOop*)index_oop_from_field_offset_long(p, offset) = n; - } - } else { - if (x != NULL) { - // If there is a heap base pointer, we are obliged to emit a store barrier. - oop_store((oop*)index_oop_from_field_offset_long(p, offset), x); - } else { - *(oop*)index_oop_from_field_offset_long(p, offset) = x; - } - } -UNSAFE_END - -// The normal variants allow a null base pointer with an arbitrary address. +// These functions allow a null base pointer with an arbitrary address. // But if the base pointer is non-null, the offset should make some sense. // That is, it should be in the range [0, MAX_OBJECT_SIZE]. UNSAFE_ENTRY(jobject, Unsafe_GetObject(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) @@ -1350,9 +1293,6 @@ UNSAFE_END // These are the methods for 1.4.0 static JNINativeMethod methods_140[] = { - {CC"getObject", CC"("OBJ"I)"OBJ"", FN_PTR(Unsafe_GetObject140)}, - {CC"putObject", CC"("OBJ"I"OBJ")V", FN_PTR(Unsafe_SetObject140)}, - DECLARE_GETSETOOP_140(Boolean, Z), DECLARE_GETSETOOP_140(Byte, B), DECLARE_GETSETOOP_140(Short, S), diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index 3c032fbf270..c2b41d44f04 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -222,10 +222,8 @@ void Arguments::init_version_specific_system_properties() { const char* spec_vendor = "Sun Microsystems Inc."; uint32_t spec_version = 0; - if (JDK_Version::is_gte_jdk17x_version()) { - spec_vendor = "Oracle Corporation"; - spec_version = JDK_Version::current().major_version(); - } + spec_vendor = "Oracle Corporation"; + spec_version = JDK_Version::current().major_version(); jio_snprintf(buffer, bufsz, "1." UINT32_FORMAT, spec_version); PropertyList_add(&_system_properties, @@ -2455,6 +2453,8 @@ bool Arguments::check_vm_args_consistency() { warning("The VM option CICompilerCountPerCPU overrides CICompilerCount."); } + status &= check_vm_args_consistency_ext(); + return status; } @@ -3699,14 +3699,6 @@ jint Arguments::parse(const JavaVMInitArgs* args) { PrintGC = true; } - if (!JDK_Version::is_gte_jdk18x_version()) { - // To avoid changing the log format for 7 updates this flag is only - // true by default in JDK8 and above. - if (FLAG_IS_DEFAULT(PrintGCCause)) { - FLAG_SET_DEFAULT(PrintGCCause, false); - } - } - // Set object alignment values. set_object_alignment(); diff --git a/hotspot/src/share/vm/runtime/arguments.hpp b/hotspot/src/share/vm/runtime/arguments.hpp index 69551e3c96e..a6329dab66e 100644 --- a/hotspot/src/share/vm/runtime/arguments.hpp +++ b/hotspot/src/share/vm/runtime/arguments.hpp @@ -462,6 +462,7 @@ class Arguments : AllStatic { static void check_deprecated_gc_flags(); // Check consistency or otherwise of VM argument settings static bool check_vm_args_consistency(); + static bool check_vm_args_consistency_ext(); // Check stack pages settings static bool check_stack_pages(); // Used by os_solaris diff --git a/jdk/src/share/classes/com/sun/java/browser/net/ProxyInfo.java b/hotspot/src/share/vm/runtime/arguments_ext.cpp similarity index 67% rename from jdk/src/share/classes/com/sun/java/browser/net/ProxyInfo.java rename to hotspot/src/share/vm/runtime/arguments_ext.cpp index f966e813591..5edd449b3da 100644 --- a/jdk/src/share/classes/com/sun/java/browser/net/ProxyInfo.java +++ b/hotspot/src/share/vm/runtime/arguments_ext.cpp @@ -1,12 +1,10 @@ /* - * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. 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 @@ -21,16 +19,12 @@ * 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 com.sun.java.browser.net; - -/** * - * @author Zhengyu Gu */ -public interface ProxyInfo { - public String getHost(); - public int getPort(); - public boolean isSocks(); + +#include "precompiled.hpp" +#include "runtime/arguments.hpp" + +bool Arguments::check_vm_args_consistency_ext() { + return true; } diff --git a/hotspot/src/share/vm/runtime/atomic.hpp b/hotspot/src/share/vm/runtime/atomic.hpp index 5b46b530b51..b2b56171362 100644 --- a/hotspot/src/share/vm/runtime/atomic.hpp +++ b/hotspot/src/share/vm/runtime/atomic.hpp @@ -116,7 +116,7 @@ class Atomic : AllStatic { atomic_decl #else #define ATOMIC_SHORT_PAIR(atomic_decl, non_atomic_decl) \ - atomic_decl ; \ + atomic_decl; \ non_atomic_decl #endif diff --git a/hotspot/src/share/vm/runtime/java.cpp b/hotspot/src/share/vm/runtime/java.cpp index e852b56ef54..3a075117afe 100644 --- a/hotspot/src/share/vm/runtime/java.cpp +++ b/hotspot/src/share/vm/runtime/java.cpp @@ -501,9 +501,6 @@ void before_exit(JavaThread * thread) { os::infinite_sleep(); } - // Stop any ongoing concurrent GC work - Universe::heap()->stop(); - // Terminate watcher thread - must before disenrolling any periodic task if (PeriodicTask::num_tasks() > 0) WatcherThread::stop(); @@ -518,10 +515,8 @@ void before_exit(JavaThread * thread) { StatSampler::disengage(); StatSampler::destroy(); - // We do not need to explicitly stop concurrent GC threads because the - // JVM will be taken down at a safepoint when such threads are inactive -- - // except for some concurrent G1 threads, see (comment in) - // Threads::destroy_vm(). + // Stop concurrent GC threads + Universe::heap()->stop(); // Print GC/heap related information. if (PrintGCDetails) { diff --git a/hotspot/src/share/vm/runtime/java.hpp b/hotspot/src/share/vm/runtime/java.hpp index e5bae38c171..02ac99ebb60 100644 --- a/hotspot/src/share/vm/runtime/java.hpp +++ b/hotspot/src/share/vm/runtime/java.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -197,58 +197,6 @@ class JDK_Version VALUE_OBJ_CLASS_SPEC { _runtime_version = version; } - // Convenience methods for queries on the current major/minor version - static bool is_jdk12x_version() { - return current().compare_major(2) == 0; - } - - static bool is_jdk13x_version() { - return current().compare_major(3) == 0; - } - - static bool is_jdk14x_version() { - return current().compare_major(4) == 0; - } - - static bool is_jdk15x_version() { - return current().compare_major(5) == 0; - } - - static bool is_jdk16x_version() { - return current().compare_major(6) == 0; - } - - static bool is_jdk17x_version() { - return current().compare_major(7) == 0; - } - - static bool is_jdk18x_version() { - return current().compare_major(8) == 0; - } - - static bool is_gte_jdk13x_version() { - return current().compare_major(3) >= 0; - } - - static bool is_gte_jdk14x_version() { - return current().compare_major(4) >= 0; - } - - static bool is_gte_jdk15x_version() { - return current().compare_major(5) >= 0; - } - - static bool is_gte_jdk16x_version() { - return current().compare_major(6) >= 0; - } - - static bool is_gte_jdk17x_version() { - return current().compare_major(7) >= 0; - } - - static bool is_gte_jdk18x_version() { - return current().compare_major(8) >= 0; - } }; #endif // SHARE_VM_RUNTIME_JAVA_HPP diff --git a/hotspot/src/share/vm/runtime/jniHandles.cpp b/hotspot/src/share/vm/runtime/jniHandles.cpp index 7ff38335029..9ce7ce8ae44 100644 --- a/hotspot/src/share/vm/runtime/jniHandles.cpp +++ b/hotspot/src/share/vm/runtime/jniHandles.cpp @@ -298,6 +298,7 @@ JNIHandleBlock* JNIHandleBlock::allocate_block(Thread* thread) { block->_top = 0; block->_next = NULL; block->_pop_frame_link = NULL; + block->_planned_capacity = block_size_in_oops; // _last, _free_list & _allocate_before_rebuild initialized in allocate_handle debug_only(block->_last = NULL); debug_only(block->_free_list = NULL); @@ -531,6 +532,12 @@ int JNIHandleBlock::length() const { return result; } +const size_t JNIHandleBlock::get_number_of_live_handles() { + CountHandleClosure counter; + oops_do(&counter); + return counter.count(); +} + // This method is not thread-safe, i.e., must be called while holding a lock on the // structure. long JNIHandleBlock::memory_usage() const { diff --git a/hotspot/src/share/vm/runtime/jniHandles.hpp b/hotspot/src/share/vm/runtime/jniHandles.hpp index 1bd97c3cf09..069a1f35cfa 100644 --- a/hotspot/src/share/vm/runtime/jniHandles.hpp +++ b/hotspot/src/share/vm/runtime/jniHandles.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -112,6 +112,9 @@ class JNIHandleBlock : public CHeapObj { oop* _free_list; // Handle free list int _allocate_before_rebuild; // Number of blocks to allocate before rebuilding free list + // Check JNI, "planned capacity" for current frame (or push/ensure) + size_t _planned_capacity; + #ifndef PRODUCT JNIHandleBlock* _block_list_link; // Link for list below static JNIHandleBlock* _block_list; // List of all allocated blocks (for debugging only) @@ -152,6 +155,11 @@ class JNIHandleBlock : public CHeapObj { // Traversal of weak handles. Unreachable oops are cleared. void weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f); + // Checked JNI support + void set_planned_capacity(size_t planned_capacity) { _planned_capacity = planned_capacity; } + const size_t get_planned_capacity() { return _planned_capacity; } + const size_t get_number_of_live_handles(); + // Debugging bool chain_contains(jobject handle) const; // Does this block or following blocks contain handle bool contains(jobject handle) const; // Does this block contain handle diff --git a/hotspot/src/share/vm/runtime/mutex.cpp b/hotspot/src/share/vm/runtime/mutex.cpp index 34c9366f0d1..f5ac0f8ea15 100644 --- a/hotspot/src/share/vm/runtime/mutex.cpp +++ b/hotspot/src/share/vm/runtime/mutex.cpp @@ -269,62 +269,62 @@ PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC #define CASPTR(a,c,s) intptr_t(Atomic::cmpxchg_ptr ((void *)(s),(void *)(a),(void *)(c))) #define UNS(x) (uintptr_t(x)) -#define TRACE(m) { static volatile int ctr = 0 ; int x = ++ctr ; if ((x & (x-1))==0) { ::printf ("%d:%s\n", x, #m); ::fflush(stdout); }} +#define TRACE(m) { static volatile int ctr = 0; int x = ++ctr; if ((x & (x-1))==0) { ::printf ("%d:%s\n", x, #m); ::fflush(stdout); }} // Simplistic low-quality Marsaglia SHIFT-XOR RNG. // Bijective except for the trailing mask operation. // Useful for spin loops as the compiler can't optimize it away. static inline jint MarsagliaXORV (jint x) { - if (x == 0) x = 1|os::random() ; + if (x == 0) x = 1|os::random(); x ^= x << 6; x ^= ((unsigned)x) >> 21; - x ^= x << 7 ; - return x & 0x7FFFFFFF ; + x ^= x << 7; + return x & 0x7FFFFFFF; } static int Stall (int its) { - static volatile jint rv = 1 ; - volatile int OnFrame = 0 ; - jint v = rv ^ UNS(OnFrame) ; + static volatile jint rv = 1; + volatile int OnFrame = 0; + jint v = rv ^ UNS(OnFrame); while (--its >= 0) { - v = MarsagliaXORV (v) ; + v = MarsagliaXORV(v); } // Make this impossible for the compiler to optimize away, // but (mostly) avoid W coherency sharing on MP systems. - if (v == 0x12345) rv = v ; - return v ; + if (v == 0x12345) rv = v; + return v; } -int Monitor::TryLock () { - intptr_t v = _LockWord.FullWord ; +int Monitor::TryLock() { + intptr_t v = _LockWord.FullWord; for (;;) { - if ((v & _LBIT) != 0) return 0 ; - const intptr_t u = CASPTR (&_LockWord, v, v|_LBIT) ; - if (v == u) return 1 ; - v = u ; + if ((v & _LBIT) != 0) return 0; + const intptr_t u = CASPTR(&_LockWord, v, v|_LBIT); + if (v == u) return 1; + v = u; } } -int Monitor::TryFast () { +int Monitor::TryFast() { // Optimistic fast-path form ... // Fast-path attempt for the common uncontended case. // Avoid RTS->RTO $ coherence upgrade on typical SMP systems. - intptr_t v = CASPTR (&_LockWord, 0, _LBIT) ; // agro ... - if (v == 0) return 1 ; + intptr_t v = CASPTR(&_LockWord, 0, _LBIT); // agro ... + if (v == 0) return 1; for (;;) { - if ((v & _LBIT) != 0) return 0 ; - const intptr_t u = CASPTR (&_LockWord, v, v|_LBIT) ; - if (v == u) return 1 ; - v = u ; + if ((v & _LBIT) != 0) return 0; + const intptr_t u = CASPTR(&_LockWord, v, v|_LBIT); + if (v == u) return 1; + v = u; } } -int Monitor::ILocked () { - const intptr_t w = _LockWord.FullWord & 0xFF ; - assert (w == 0 || w == _LBIT, "invariant") ; - return w == _LBIT ; +int Monitor::ILocked() { + const intptr_t w = _LockWord.FullWord & 0xFF; + assert(w == 0 || w == _LBIT, "invariant"); + return w == _LBIT; } // Polite TATAS spinlock with exponential backoff - bounded spin. @@ -342,38 +342,38 @@ int Monitor::ILocked () { // See synchronizer.cpp for details and rationale. int Monitor::TrySpin (Thread * const Self) { - if (TryLock()) return 1 ; - if (!os::is_MP()) return 0 ; + if (TryLock()) return 1; + if (!os::is_MP()) return 0; - int Probes = 0 ; - int Delay = 0 ; - int Steps = 0 ; - int SpinMax = NativeMonitorSpinLimit ; - int flgs = NativeMonitorFlags ; + int Probes = 0; + int Delay = 0; + int Steps = 0; + int SpinMax = NativeMonitorSpinLimit; + int flgs = NativeMonitorFlags; for (;;) { intptr_t v = _LockWord.FullWord; if ((v & _LBIT) == 0) { if (CASPTR (&_LockWord, v, v|_LBIT) == v) { - return 1 ; + return 1; } - continue ; + continue; } if ((flgs & 8) == 0) { - SpinPause () ; + SpinPause(); } // Periodically increase Delay -- variable Delay form // conceptually: delay *= 1 + 1/Exponent - ++ Probes; - if (Probes > SpinMax) return 0 ; + ++Probes; + if (Probes > SpinMax) return 0; if ((Probes & 0x7) == 0) { - Delay = ((Delay << 1)|1) & 0x7FF ; + Delay = ((Delay << 1)|1) & 0x7FF; // CONSIDER: Delay += 1 + (Delay/4); Delay &= 0x7FF ; } - if (flgs & 2) continue ; + if (flgs & 2) continue; // Consider checking _owner's schedctl state, if OFFPROC abort spin. // If the owner is OFFPROC then it's unlike that the lock will be dropped @@ -389,48 +389,48 @@ int Monitor::TrySpin (Thread * const Self) { // spin loop. N1 and brethren write-around the L1$ over the xbar into the L2$. // Furthermore, they don't have a W$ like traditional SPARC processors. // We currently use a Marsaglia Shift-Xor RNG loop. - Steps += Delay ; + Steps += Delay; if (Self != NULL) { - jint rv = Self->rng[0] ; - for (int k = Delay ; --k >= 0; ) { - rv = MarsagliaXORV (rv) ; - if ((flgs & 4) == 0 && SafepointSynchronize::do_call_back()) return 0 ; + jint rv = Self->rng[0]; + for (int k = Delay; --k >= 0;) { + rv = MarsagliaXORV(rv); + if ((flgs & 4) == 0 && SafepointSynchronize::do_call_back()) return 0; } - Self->rng[0] = rv ; + Self->rng[0] = rv; } else { - Stall (Delay) ; + Stall(Delay); } } } static int ParkCommon (ParkEvent * ev, jlong timo) { // Diagnostic support - periodically unwedge blocked threads - intx nmt = NativeMonitorTimeout ; + intx nmt = NativeMonitorTimeout; if (nmt > 0 && (nmt < timo || timo <= 0)) { - timo = nmt ; + timo = nmt; } - int err = OS_OK ; + int err = OS_OK; if (0 == timo) { - ev->park() ; + ev->park(); } else { - err = ev->park(timo) ; + err = ev->park(timo); } - return err ; + return err; } inline int Monitor::AcquireOrPush (ParkEvent * ESelf) { - intptr_t v = _LockWord.FullWord ; + intptr_t v = _LockWord.FullWord; for (;;) { if ((v & _LBIT) == 0) { - const intptr_t u = CASPTR (&_LockWord, v, v|_LBIT) ; - if (u == v) return 1 ; // indicate acquired - v = u ; + const intptr_t u = CASPTR(&_LockWord, v, v|_LBIT); + if (u == v) return 1; // indicate acquired + v = u; } else { // Anticipate success ... - ESelf->ListNext = (ParkEvent *) (v & ~_LBIT) ; - const intptr_t u = CASPTR (&_LockWord, v, intptr_t(ESelf)|_LBIT) ; - if (u == v) return 0 ; // indicate pushed onto cxq - v = u ; + ESelf->ListNext = (ParkEvent *)(v & ~_LBIT); + const intptr_t u = CASPTR(&_LockWord, v, intptr_t(ESelf)|_LBIT); + if (u == v) return 0; // indicate pushed onto cxq + v = u; } // Interference - LockWord change - just retry } @@ -444,33 +444,33 @@ inline int Monitor::AcquireOrPush (ParkEvent * ESelf) { // _owner is a higher-level logical concept. void Monitor::ILock (Thread * Self) { - assert (_OnDeck != Self->_MutexEvent, "invariant") ; + assert(_OnDeck != Self->_MutexEvent, "invariant"); if (TryFast()) { Exeunt: - assert (ILocked(), "invariant") ; - return ; + assert(ILocked(), "invariant"); + return; } - ParkEvent * const ESelf = Self->_MutexEvent ; - assert (_OnDeck != ESelf, "invariant") ; + ParkEvent * const ESelf = Self->_MutexEvent; + assert(_OnDeck != ESelf, "invariant"); // As an optimization, spinners could conditionally try to set ONDECK to _LBIT // Synchronizer.cpp uses a similar optimization. - if (TrySpin (Self)) goto Exeunt ; + if (TrySpin(Self)) goto Exeunt; // Slow-path - the lock is contended. // Either Enqueue Self on cxq or acquire the outer lock. // LockWord encoding = (cxq,LOCKBYTE) - ESelf->reset() ; - OrderAccess::fence() ; + ESelf->reset(); + OrderAccess::fence(); // Optional optimization ... try barging on the inner lock if ((NativeMonitorFlags & 32) && CASPTR (&_OnDeck, NULL, UNS(Self)) == 0) { - goto OnDeck_LOOP ; + goto OnDeck_LOOP; } - if (AcquireOrPush (ESelf)) goto Exeunt ; + if (AcquireOrPush(ESelf)) goto Exeunt; // At any given time there is at most one ondeck thread. // ondeck implies not resident on cxq and not resident on EntryList @@ -478,26 +478,26 @@ void Monitor::ILock (Thread * Self) { // CONSIDER: use Self->OnDeck instead of m->OnDeck. // Deschedule Self so that others may run. while (_OnDeck != ESelf) { - ParkCommon (ESelf, 0) ; + ParkCommon(ESelf, 0); } // Self is now in the ONDECK position and will remain so until it // manages to acquire the lock. OnDeck_LOOP: for (;;) { - assert (_OnDeck == ESelf, "invariant") ; - if (TrySpin (Self)) break ; + assert(_OnDeck == ESelf, "invariant"); + if (TrySpin(Self)) break; // CONSIDER: if ESelf->TryPark() && TryLock() break ... // It's probably wise to spin only if we *actually* blocked // CONSIDER: check the lockbyte, if it remains set then // preemptively drain the cxq into the EntryList. // The best place and time to perform queue operations -- lock metadata -- // is _before having acquired the outer lock, while waiting for the lock to drop. - ParkCommon (ESelf, 0) ; + ParkCommon(ESelf, 0); } - assert (_OnDeck == ESelf, "invariant") ; - _OnDeck = NULL ; + assert(_OnDeck == ESelf, "invariant"); + _OnDeck = NULL; // Note that we current drop the inner lock (clear OnDeck) in the slow-path // epilogue immediately after having acquired the outer lock. @@ -512,11 +512,11 @@ void Monitor::ILock (Thread * Self) { // effective length of the critical section. // Note that (A) and (B) are tantamount to succession by direct handoff for // the inner lock. - goto Exeunt ; + goto Exeunt; } void Monitor::IUnlock (bool RelaxAssert) { - assert (ILocked(), "invariant") ; + assert(ILocked(), "invariant"); // Conceptually we need a MEMBAR #storestore|#loadstore barrier or fence immediately // before the store that releases the lock. Crucially, all the stores and loads in the // critical section must be globally visible before the store of 0 into the lock-word @@ -532,9 +532,9 @@ void Monitor::IUnlock (bool RelaxAssert) { // safety or lock release consistency. OrderAccess::release_store(&_LockWord.Bytes[_LSBINDEX], 0); // drop outer lock - OrderAccess::storeload (); - ParkEvent * const w = _OnDeck ; - assert (RelaxAssert || w != Thread::current()->_MutexEvent, "invariant") ; + OrderAccess::storeload(); + ParkEvent * const w = _OnDeck; + assert(RelaxAssert || w != Thread::current()->_MutexEvent, "invariant"); if (w != NULL) { // Either we have a valid ondeck thread or ondeck is transiently "locked" // by some exiting thread as it arranges for succession. The LSBit of @@ -549,19 +549,19 @@ void Monitor::IUnlock (bool RelaxAssert) { // then progress is known to have occurred as that means the thread associated // with "w" acquired the lock. In that case this thread need take no further // action to guarantee progress. - if ((UNS(w) & _LBIT) == 0) w->unpark() ; - return ; + if ((UNS(w) & _LBIT) == 0) w->unpark(); + return; } - intptr_t cxq = _LockWord.FullWord ; + intptr_t cxq = _LockWord.FullWord; if (((cxq & ~_LBIT)|UNS(_EntryList)) == 0) { - return ; // normal fast-path exit - cxq and EntryList both empty + return; // normal fast-path exit - cxq and EntryList both empty } if (cxq & _LBIT) { // Optional optimization ... // Some other thread acquired the lock in the window since this // thread released it. Succession is now that thread's responsibility. - return ; + return; } Succession: @@ -575,22 +575,22 @@ void Monitor::IUnlock (bool RelaxAssert) { // picks a successor and marks that thread as OnDeck. That successor // thread will then clear OnDeck once it eventually acquires the outer lock. if (CASPTR (&_OnDeck, NULL, _LBIT) != UNS(NULL)) { - return ; + return; } - ParkEvent * List = _EntryList ; + ParkEvent * List = _EntryList; if (List != NULL) { // Transfer the head of the EntryList to the OnDeck position. // Once OnDeck, a thread stays OnDeck until it acquires the lock. // For a given lock there is at most OnDeck thread at any one instant. WakeOne: - assert (List == _EntryList, "invariant") ; - ParkEvent * const w = List ; - assert (RelaxAssert || w != Thread::current()->_MutexEvent, "invariant") ; - _EntryList = w->ListNext ; + assert(List == _EntryList, "invariant"); + ParkEvent * const w = List; + assert(RelaxAssert || w != Thread::current()->_MutexEvent, "invariant"); + _EntryList = w->ListNext; // as a diagnostic measure consider setting w->_ListNext = BAD - assert (UNS(_OnDeck) == _LBIT, "invariant") ; - _OnDeck = w ; // pass OnDeck to w. + assert(UNS(_OnDeck) == _LBIT, "invariant"); + _OnDeck = w; // pass OnDeck to w. // w will clear OnDeck once it acquires the outer lock // Another optional optimization ... @@ -599,25 +599,25 @@ void Monitor::IUnlock (bool RelaxAssert) { // Try to defer the unpark() operation - Delegate the responsibility // for unpark()ing the OnDeck thread to the current or subsequent owners // That is, the new owner is responsible for unparking the OnDeck thread. - OrderAccess::storeload() ; - cxq = _LockWord.FullWord ; - if (cxq & _LBIT) return ; + OrderAccess::storeload(); + cxq = _LockWord.FullWord; + if (cxq & _LBIT) return; - w->unpark() ; - return ; + w->unpark(); + return; } - cxq = _LockWord.FullWord ; + cxq = _LockWord.FullWord; if ((cxq & ~_LBIT) != 0) { // The EntryList is empty but the cxq is populated. // drain RATs from cxq into EntryList // Detach RATs segment with CAS and then merge into EntryList for (;;) { // optional optimization - if locked, the owner is responsible for succession - if (cxq & _LBIT) goto Punt ; - const intptr_t vfy = CASPTR (&_LockWord, cxq, cxq & _LBIT) ; - if (vfy == cxq) break ; - cxq = vfy ; + if (cxq & _LBIT) goto Punt; + const intptr_t vfy = CASPTR(&_LockWord, cxq, cxq & _LBIT); + if (vfy == cxq) break; + cxq = vfy; // Interference - LockWord changed - Just retry // We can see concurrent interference from contending threads // pushing themselves onto the cxq or from lock-unlock operations. @@ -639,10 +639,10 @@ void Monitor::IUnlock (bool RelaxAssert) { // the EntryList, but it might make sense to reverse the order // or perhaps sort by thread priority. See the comments in // synchronizer.cpp objectMonitor::exit(). - assert (_EntryList == NULL, "invariant") ; - _EntryList = List = (ParkEvent *)(cxq & ~_LBIT) ; - assert (List != NULL, "invariant") ; - goto WakeOne ; + assert(_EntryList == NULL, "invariant"); + _EntryList = List = (ParkEvent *)(cxq & ~_LBIT); + assert(List != NULL, "invariant"); + goto WakeOne; } // cxq|EntryList is empty. @@ -651,8 +651,8 @@ void Monitor::IUnlock (bool RelaxAssert) { // A thread could have added itself to cxq since this thread previously checked. // Detect and recover by refetching cxq. Punt: - assert (UNS(_OnDeck) == _LBIT, "invariant") ; - _OnDeck = NULL ; // Release inner lock. + assert(UNS(_OnDeck) == _LBIT, "invariant"); + _OnDeck = NULL; // Release inner lock. OrderAccess::storeload(); // Dekker duality - pivot point // Resample LockWord/cxq to recover from possible race. @@ -665,32 +665,32 @@ void Monitor::IUnlock (bool RelaxAssert) { // Note that we don't need to recheck EntryList, just cxq. // If threads moved onto EntryList since we dropped OnDeck // that implies some other thread forced succession. - cxq = _LockWord.FullWord ; + cxq = _LockWord.FullWord; if ((cxq & ~_LBIT) != 0 && (cxq & _LBIT) == 0) { - goto Succession ; // potential race -- re-run succession + goto Succession; // potential race -- re-run succession } - return ; + return; } bool Monitor::notify() { - assert (_owner == Thread::current(), "invariant") ; - assert (ILocked(), "invariant") ; - if (_WaitSet == NULL) return true ; - NotifyCount ++ ; + assert(_owner == Thread::current(), "invariant"); + assert(ILocked(), "invariant"); + if (_WaitSet == NULL) return true; + NotifyCount++; // Transfer one thread from the WaitSet to the EntryList or cxq. // Currently we just unlink the head of the WaitSet and prepend to the cxq. // And of course we could just unlink it and unpark it, too, but // in that case it'd likely impale itself on the reentry. - Thread::muxAcquire (_WaitLock, "notify:WaitLock") ; - ParkEvent * nfy = _WaitSet ; + Thread::muxAcquire(_WaitLock, "notify:WaitLock"); + ParkEvent * nfy = _WaitSet; if (nfy != NULL) { // DCL idiom - _WaitSet = nfy->ListNext ; - assert (nfy->Notified == 0, "invariant") ; + _WaitSet = nfy->ListNext; + assert(nfy->Notified == 0, "invariant"); // push nfy onto the cxq for (;;) { - const intptr_t v = _LockWord.FullWord ; - assert ((v & 0xFF) == _LBIT, "invariant") ; + const intptr_t v = _LockWord.FullWord; + assert((v & 0xFF) == _LBIT, "invariant"); nfy->ListNext = (ParkEvent *)(v & ~_LBIT); if (CASPTR (&_LockWord, v, UNS(nfy)|_LBIT) == v) break; // interference - _LockWord changed -- just retry @@ -698,17 +698,17 @@ bool Monitor::notify() { // Note that setting Notified before pushing nfy onto the cxq is // also legal and safe, but the safety properties are much more // subtle, so for the sake of code stewardship ... - OrderAccess::fence() ; + OrderAccess::fence(); nfy->Notified = 1; } - Thread::muxRelease (_WaitLock) ; + Thread::muxRelease(_WaitLock); if (nfy != NULL && (NativeMonitorFlags & 16)) { // Experimental code ... light up the wakee in the hope that this thread (the owner) // will drop the lock just about the time the wakee comes ONPROC. - nfy->unpark() ; + nfy->unpark(); } - assert (ILocked(), "invariant") ; - return true ; + assert(ILocked(), "invariant"); + return true; } // Currently notifyAll() transfers the waiters one-at-a-time from the waitset @@ -719,14 +719,14 @@ bool Monitor::notify() { // will be empty and the cxq will be "DCBAXYZ". This is benign, of course. bool Monitor::notify_all() { - assert (_owner == Thread::current(), "invariant") ; - assert (ILocked(), "invariant") ; - while (_WaitSet != NULL) notify() ; - return true ; + assert(_owner == Thread::current(), "invariant"); + assert(ILocked(), "invariant"); + while (_WaitSet != NULL) notify(); + return true; } int Monitor::IWait (Thread * Self, jlong timo) { - assert (ILocked(), "invariant") ; + assert(ILocked(), "invariant"); // Phases: // 1. Enqueue Self on WaitSet - currently prepend @@ -734,10 +734,10 @@ int Monitor::IWait (Thread * Self, jlong timo) { // 3. wait for either notification or timeout // 4. lock - reentry - reacquire the outer lock - ParkEvent * const ESelf = Self->_MutexEvent ; - ESelf->Notified = 0 ; - ESelf->reset() ; - OrderAccess::fence() ; + ParkEvent * const ESelf = Self->_MutexEvent; + ESelf->Notified = 0; + ESelf->reset(); + OrderAccess::fence(); // Add Self to WaitSet // Ideally only the holder of the outer lock would manipulate the WaitSet - @@ -766,10 +766,10 @@ int Monitor::IWait (Thread * Self, jlong timo) { // In that case we could have one ListElement on the WaitSet and another // on the EntryList, with both referring to the same pure Event. - Thread::muxAcquire (_WaitLock, "wait:WaitLock:Add") ; - ESelf->ListNext = _WaitSet ; - _WaitSet = ESelf ; - Thread::muxRelease (_WaitLock) ; + Thread::muxAcquire(_WaitLock, "wait:WaitLock:Add"); + ESelf->ListNext = _WaitSet; + _WaitSet = ESelf; + Thread::muxRelease(_WaitLock); // Release the outer lock // We call IUnlock (RelaxAssert=true) as a thread T1 might @@ -781,16 +781,16 @@ int Monitor::IWait (Thread * Self, jlong timo) { // IUnlock() call a thread should _never find itself on the EntryList // or cxq, but in the case of wait() it's possible. // See synchronizer.cpp objectMonitor::wait(). - IUnlock (true) ; + IUnlock(true); // Wait for either notification or timeout // Beware that in some circumstances we might propagate // spurious wakeups back to the caller. for (;;) { - if (ESelf->Notified) break ; - int err = ParkCommon (ESelf, timo) ; - if (err == OS_TIMEOUT || (NativeMonitorFlags & 1)) break ; + if (ESelf->Notified) break; + int err = ParkCommon(ESelf, timo); + if (err == OS_TIMEOUT || (NativeMonitorFlags & 1)) break; } // Prepare for reentry - if necessary, remove ESelf from WaitSet @@ -799,55 +799,55 @@ int Monitor::IWait (Thread * Self, jlong timo) { // 2. On the cxq or EntryList // 3. Not resident on cxq, EntryList or WaitSet, but in the OnDeck position. - OrderAccess::fence() ; - int WasOnWaitSet = 0 ; + OrderAccess::fence(); + int WasOnWaitSet = 0; if (ESelf->Notified == 0) { - Thread::muxAcquire (_WaitLock, "wait:WaitLock:remove") ; + Thread::muxAcquire(_WaitLock, "wait:WaitLock:remove"); if (ESelf->Notified == 0) { // DCL idiom - assert (_OnDeck != ESelf, "invariant") ; // can't be both OnDeck and on WaitSet + assert(_OnDeck != ESelf, "invariant"); // can't be both OnDeck and on WaitSet // ESelf is resident on the WaitSet -- unlink it. // A doubly-linked list would be better here so we can unlink in constant-time. // We have to unlink before we potentially recontend as ESelf might otherwise // end up on the cxq|EntryList -- it can't be on two lists at once. - ParkEvent * p = _WaitSet ; - ParkEvent * q = NULL ; // classic q chases p + ParkEvent * p = _WaitSet; + ParkEvent * q = NULL; // classic q chases p while (p != NULL && p != ESelf) { - q = p ; - p = p->ListNext ; + q = p; + p = p->ListNext; } - assert (p == ESelf, "invariant") ; + assert(p == ESelf, "invariant"); if (p == _WaitSet) { // found at head - assert (q == NULL, "invariant") ; - _WaitSet = p->ListNext ; + assert(q == NULL, "invariant"); + _WaitSet = p->ListNext; } else { // found in interior - assert (q->ListNext == p, "invariant") ; - q->ListNext = p->ListNext ; + assert(q->ListNext == p, "invariant"); + q->ListNext = p->ListNext; } - WasOnWaitSet = 1 ; // We were *not* notified but instead encountered timeout + WasOnWaitSet = 1; // We were *not* notified but instead encountered timeout } - Thread::muxRelease (_WaitLock) ; + Thread::muxRelease(_WaitLock); } // Reentry phase - reacquire the lock if (WasOnWaitSet) { // ESelf was previously on the WaitSet but we just unlinked it above // because of a timeout. ESelf is not resident on any list and is not OnDeck - assert (_OnDeck != ESelf, "invariant") ; - ILock (Self) ; + assert(_OnDeck != ESelf, "invariant"); + ILock(Self); } else { // A prior notify() operation moved ESelf from the WaitSet to the cxq. // ESelf is now on the cxq, EntryList or at the OnDeck position. // The following fragment is extracted from Monitor::ILock() for (;;) { - if (_OnDeck == ESelf && TrySpin(Self)) break ; - ParkCommon (ESelf, 0) ; + if (_OnDeck == ESelf && TrySpin(Self)) break; + ParkCommon(ESelf, 0); } - assert (_OnDeck == ESelf, "invariant") ; - _OnDeck = NULL ; + assert(_OnDeck == ESelf, "invariant"); + _OnDeck = NULL; } - assert (ILocked(), "invariant") ; - return WasOnWaitSet != 0 ; // return true IFF timeout + assert(ILocked(), "invariant"); + return WasOnWaitSet != 0; // return true IFF timeout } @@ -896,15 +896,15 @@ void Monitor::lock (Thread * Self) { #endif // CHECK_UNHANDLED_OOPS debug_only(check_prelock_state(Self)); - assert (_owner != Self , "invariant") ; - assert (_OnDeck != Self->_MutexEvent, "invariant") ; + assert(_owner != Self , "invariant"); + assert(_OnDeck != Self->_MutexEvent, "invariant"); if (TryFast()) { Exeunt: - assert (ILocked(), "invariant") ; - assert (owner() == NULL, "invariant"); - set_owner (Self); - return ; + assert(ILocked(), "invariant"); + assert(owner() == NULL, "invariant"); + set_owner(Self); + return; } // The lock is contended ... @@ -916,23 +916,23 @@ void Monitor::lock (Thread * Self) { // and go on. we note this with _snuck so we can also // pretend to unlock when the time comes. _snuck = true; - goto Exeunt ; + goto Exeunt; } // Try a brief spin to avoid passing thru thread state transition ... - if (TrySpin (Self)) goto Exeunt ; + if (TrySpin(Self)) goto Exeunt; check_block_state(Self); if (Self->is_Java_thread()) { // Horrible dictu - we suffer through a state transition assert(rank() > Mutex::special, "Potential deadlock with special or lesser rank mutex"); - ThreadBlockInVM tbivm ((JavaThread *) Self) ; - ILock (Self) ; + ThreadBlockInVM tbivm((JavaThread *) Self); + ILock(Self); } else { // Mirabile dictu - ILock (Self) ; + ILock(Self); } - goto Exeunt ; + goto Exeunt; } void Monitor::lock() { @@ -945,14 +945,14 @@ void Monitor::lock() { // thread state set to be in VM, the safepoint synchronization code will deadlock! void Monitor::lock_without_safepoint_check (Thread * Self) { - assert (_owner != Self, "invariant") ; - ILock (Self) ; - assert (_owner == NULL, "invariant"); - set_owner (Self); + assert(_owner != Self, "invariant"); + ILock(Self); + assert(_owner == NULL, "invariant"); + set_owner(Self); } -void Monitor::lock_without_safepoint_check () { - lock_without_safepoint_check (Thread::current()) ; +void Monitor::lock_without_safepoint_check() { + lock_without_safepoint_check(Thread::current()); } @@ -976,23 +976,23 @@ bool Monitor::try_lock() { if (TryLock()) { // We got the lock - assert (_owner == NULL, "invariant"); - set_owner (Self); + assert(_owner == NULL, "invariant"); + set_owner(Self); return true; } return false; } void Monitor::unlock() { - assert (_owner == Thread::current(), "invariant") ; - assert (_OnDeck != Thread::current()->_MutexEvent , "invariant") ; - set_owner (NULL) ; + assert(_owner == Thread::current(), "invariant"); + assert(_OnDeck != Thread::current()->_MutexEvent , "invariant"); + set_owner(NULL); if (_snuck) { assert(SafepointSynchronize::is_at_safepoint() && Thread::current()->is_VM_thread(), "sneak"); _snuck = false; - return ; + return; } - IUnlock (false) ; + IUnlock(false); } // Yet another degenerate version of Monitor::lock() or lock_without_safepoint_check() @@ -1020,29 +1020,29 @@ void Monitor::jvm_raw_lock() { if (TryLock()) { Exeunt: - assert (ILocked(), "invariant") ; - assert (_owner == NULL, "invariant"); + assert(ILocked(), "invariant"); + assert(_owner == NULL, "invariant"); // This can potentially be called by non-java Threads. Thus, the ThreadLocalStorage // might return NULL. Don't call set_owner since it will break on an NULL owner // Consider installing a non-null "ANON" distinguished value instead of just NULL. _owner = ThreadLocalStorage::thread(); - return ; + return; } - if (TrySpin(NULL)) goto Exeunt ; + if (TrySpin(NULL)) goto Exeunt; // slow-path - apparent contention // Allocate a ParkEvent for transient use. // The ParkEvent remains associated with this thread until // the time the thread manages to acquire the lock. - ParkEvent * const ESelf = ParkEvent::Allocate(NULL) ; - ESelf->reset() ; - OrderAccess::storeload() ; + ParkEvent * const ESelf = ParkEvent::Allocate(NULL); + ESelf->reset(); + OrderAccess::storeload(); // Either Enqueue Self on cxq or acquire the outer lock. if (AcquireOrPush (ESelf)) { - ParkEvent::Release (ESelf) ; // surrender the ParkEvent - goto Exeunt ; + ParkEvent::Release(ESelf); // surrender the ParkEvent + goto Exeunt; } // At any given time there is at most one ondeck thread. @@ -1050,37 +1050,37 @@ void Monitor::jvm_raw_lock() { // Only the OnDeck thread can try to acquire -- contended for -- the lock. // CONSIDER: use Self->OnDeck instead of m->OnDeck. for (;;) { - if (_OnDeck == ESelf && TrySpin(NULL)) break ; - ParkCommon (ESelf, 0) ; + if (_OnDeck == ESelf && TrySpin(NULL)) break; + ParkCommon(ESelf, 0); } - assert (_OnDeck == ESelf, "invariant") ; - _OnDeck = NULL ; - ParkEvent::Release (ESelf) ; // surrender the ParkEvent - goto Exeunt ; + assert(_OnDeck == ESelf, "invariant"); + _OnDeck = NULL; + ParkEvent::Release(ESelf); // surrender the ParkEvent + goto Exeunt; } void Monitor::jvm_raw_unlock() { // Nearly the same as Monitor::unlock() ... // directly set _owner instead of using set_owner(null) - _owner = NULL ; + _owner = NULL; if (_snuck) { // ??? assert(SafepointSynchronize::is_at_safepoint() && Thread::current()->is_VM_thread(), "sneak"); _snuck = false; - return ; + return; } - IUnlock(false) ; + IUnlock(false); } bool Monitor::wait(bool no_safepoint_check, long timeout, bool as_suspend_equivalent) { - Thread * const Self = Thread::current() ; - assert (_owner == Self, "invariant") ; - assert (ILocked(), "invariant") ; + Thread * const Self = Thread::current(); + assert(_owner == Self, "invariant"); + assert(ILocked(), "invariant"); // as_suspend_equivalent logically implies !no_safepoint_check - guarantee (!as_suspend_equivalent || !no_safepoint_check, "invariant") ; + guarantee(!as_suspend_equivalent || !no_safepoint_check, "invariant"); // !no_safepoint_check logically implies java_thread - guarantee (no_safepoint_check || Self->is_Java_thread(), "invariant") ; + guarantee(no_safepoint_check || Self->is_Java_thread(), "invariant"); #ifdef ASSERT Monitor * least = get_least_ranked_lock_besides_this(Self->owned_locks()); @@ -1093,14 +1093,14 @@ bool Monitor::wait(bool no_safepoint_check, long timeout, bool as_suspend_equiva } #endif // ASSERT - int wait_status ; + int wait_status; // conceptually set the owner to NULL in anticipation of // abdicating the lock in wait set_owner(NULL); if (no_safepoint_check) { - wait_status = IWait (Self, timeout) ; + wait_status = IWait(Self, timeout); } else { - assert (Self->is_Java_thread(), "invariant") ; + assert(Self->is_Java_thread(), "invariant"); JavaThread *jt = (JavaThread *)Self; // Enter safepoint region - ornate and Rococo ... @@ -1113,7 +1113,7 @@ bool Monitor::wait(bool no_safepoint_check, long timeout, bool as_suspend_equiva // java_suspend_self() } - wait_status = IWait (Self, timeout) ; + wait_status = IWait(Self, timeout); // were we externally suspended while we were waiting? if (as_suspend_equivalent && jt->handle_special_suspend_equivalent_condition()) { @@ -1121,67 +1121,67 @@ bool Monitor::wait(bool no_safepoint_check, long timeout, bool as_suspend_equiva // while we were waiting another thread suspended us. We don't // want to hold the lock while suspended because that // would surprise the thread that suspended us. - assert (ILocked(), "invariant") ; - IUnlock (true) ; + assert(ILocked(), "invariant"); + IUnlock(true); jt->java_suspend_self(); - ILock (Self) ; - assert (ILocked(), "invariant") ; + ILock(Self); + assert(ILocked(), "invariant"); } } // Conceptually reestablish ownership of the lock. // The "real" lock -- the LockByte -- was reacquired by IWait(). - assert (ILocked(), "invariant") ; - assert (_owner == NULL, "invariant") ; - set_owner (Self) ; - return wait_status != 0 ; // return true IFF timeout + assert(ILocked(), "invariant"); + assert(_owner == NULL, "invariant"); + set_owner(Self); + return wait_status != 0; // return true IFF timeout } Monitor::~Monitor() { - assert ((UNS(_owner)|UNS(_LockWord.FullWord)|UNS(_EntryList)|UNS(_WaitSet)|UNS(_OnDeck)) == 0, "") ; + assert((UNS(_owner)|UNS(_LockWord.FullWord)|UNS(_EntryList)|UNS(_WaitSet)|UNS(_OnDeck)) == 0, ""); } void Monitor::ClearMonitor (Monitor * m, const char *name) { - m->_owner = NULL ; - m->_snuck = false ; + m->_owner = NULL; + m->_snuck = false; if (name == NULL) { - strcpy(m->_name, "UNKNOWN") ; + strcpy(m->_name, "UNKNOWN"); } else { strncpy(m->_name, name, MONITOR_NAME_LEN - 1); m->_name[MONITOR_NAME_LEN - 1] = '\0'; } - m->_LockWord.FullWord = 0 ; - m->_EntryList = NULL ; - m->_OnDeck = NULL ; - m->_WaitSet = NULL ; - m->_WaitLock[0] = 0 ; + m->_LockWord.FullWord = 0; + m->_EntryList = NULL; + m->_OnDeck = NULL; + m->_WaitSet = NULL; + m->_WaitLock[0] = 0; } Monitor::Monitor() { ClearMonitor(this); } Monitor::Monitor (int Rank, const char * name, bool allow_vm_block) { - ClearMonitor (this, name) ; + ClearMonitor(this, name); #ifdef ASSERT _allow_vm_block = allow_vm_block; - _rank = Rank ; + _rank = Rank; #endif } Mutex::~Mutex() { - assert ((UNS(_owner)|UNS(_LockWord.FullWord)|UNS(_EntryList)|UNS(_WaitSet)|UNS(_OnDeck)) == 0, "") ; + assert((UNS(_owner)|UNS(_LockWord.FullWord)|UNS(_EntryList)|UNS(_WaitSet)|UNS(_OnDeck)) == 0, ""); } Mutex::Mutex (int Rank, const char * name, bool allow_vm_block) { - ClearMonitor ((Monitor *) this, name) ; + ClearMonitor((Monitor *) this, name); #ifdef ASSERT _allow_vm_block = allow_vm_block; - _rank = Rank ; + _rank = Rank; #endif } bool Monitor::owned_by_self() const { bool ret = _owner == Thread::current(); - assert (!ret || _LockWord.Bytes[_LSBINDEX] != 0, "invariant") ; + assert(!ret || _LockWord.Bytes[_LSBINDEX] != 0, "invariant"); return ret; } diff --git a/hotspot/src/share/vm/runtime/objectMonitor.cpp b/hotspot/src/share/vm/runtime/objectMonitor.cpp index 6f2323c8668..d9682ebf601 100644 --- a/hotspot/src/share/vm/runtime/objectMonitor.cpp +++ b/hotspot/src/share/vm/runtime/objectMonitor.cpp @@ -114,38 +114,38 @@ // The knob* variables are effectively final. Once set they should // never be modified hence. Consider using __read_mostly with GCC. -int ObjectMonitor::Knob_Verbose = 0 ; -int ObjectMonitor::Knob_SpinLimit = 5000 ; // derived by an external tool - -static int Knob_LogSpins = 0 ; // enable jvmstat tally for spins -static int Knob_HandOff = 0 ; -static int Knob_ReportSettings = 0 ; +int ObjectMonitor::Knob_Verbose = 0; +int ObjectMonitor::Knob_SpinLimit = 5000; // derived by an external tool - +static int Knob_LogSpins = 0; // enable jvmstat tally for spins +static int Knob_HandOff = 0; +static int Knob_ReportSettings = 0; -static int Knob_SpinBase = 0 ; // Floor AKA SpinMin -static int Knob_SpinBackOff = 0 ; // spin-loop backoff -static int Knob_CASPenalty = -1 ; // Penalty for failed CAS -static int Knob_OXPenalty = -1 ; // Penalty for observed _owner change -static int Knob_SpinSetSucc = 1 ; // spinners set the _succ field -static int Knob_SpinEarly = 1 ; -static int Knob_SuccEnabled = 1 ; // futile wake throttling -static int Knob_SuccRestrict = 0 ; // Limit successors + spinners to at-most-one -static int Knob_MaxSpinners = -1 ; // Should be a function of # CPUs -static int Knob_Bonus = 100 ; // spin success bonus -static int Knob_BonusB = 100 ; // spin success bonus -static int Knob_Penalty = 200 ; // spin failure penalty -static int Knob_Poverty = 1000 ; -static int Knob_SpinAfterFutile = 1 ; // Spin after returning from park() -static int Knob_FixedSpin = 0 ; -static int Knob_OState = 3 ; // Spinner checks thread state of _owner -static int Knob_UsePause = 1 ; -static int Knob_ExitPolicy = 0 ; -static int Knob_PreSpin = 10 ; // 20-100 likely better -static int Knob_ResetEvent = 0 ; -static int BackOffMask = 0 ; +static int Knob_SpinBase = 0; // Floor AKA SpinMin +static int Knob_SpinBackOff = 0; // spin-loop backoff +static int Knob_CASPenalty = -1; // Penalty for failed CAS +static int Knob_OXPenalty = -1; // Penalty for observed _owner change +static int Knob_SpinSetSucc = 1; // spinners set the _succ field +static int Knob_SpinEarly = 1; +static int Knob_SuccEnabled = 1; // futile wake throttling +static int Knob_SuccRestrict = 0; // Limit successors + spinners to at-most-one +static int Knob_MaxSpinners = -1; // Should be a function of # CPUs +static int Knob_Bonus = 100; // spin success bonus +static int Knob_BonusB = 100; // spin success bonus +static int Knob_Penalty = 200; // spin failure penalty +static int Knob_Poverty = 1000; +static int Knob_SpinAfterFutile = 1; // Spin after returning from park() +static int Knob_FixedSpin = 0; +static int Knob_OState = 3; // Spinner checks thread state of _owner +static int Knob_UsePause = 1; +static int Knob_ExitPolicy = 0; +static int Knob_PreSpin = 10; // 20-100 likely better +static int Knob_ResetEvent = 0; +static int BackOffMask = 0; -static int Knob_FastHSSEC = 0 ; -static int Knob_MoveNotifyee = 2 ; // notify() - disposition of notifyee -static int Knob_QMode = 0 ; // EntryList-cxq policy - queue discipline -static volatile int InitDone = 0 ; +static int Knob_FastHSSEC = 0; +static int Knob_MoveNotifyee = 2; // notify() - disposition of notifyee +static int Knob_QMode = 0; // EntryList-cxq policy - queue discipline +static volatile int InitDone = 0; #define TrySpin TrySpin_VaryDuration @@ -265,9 +265,9 @@ bool ObjectMonitor::try_enter(Thread* THREAD) { if (THREAD != _owner) { if (THREAD->is_lock_owned ((address)_owner)) { assert(_recursions == 0, "internal state error"); - _owner = THREAD ; - _recursions = 1 ; - OwnerIsThread = 1 ; + _owner = THREAD; + _recursions = 1; + OwnerIsThread = 1; return true; } if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) { @@ -283,37 +283,37 @@ bool ObjectMonitor::try_enter(Thread* THREAD) { void ATTR ObjectMonitor::enter(TRAPS) { // The following code is ordered to check the most common cases first // and to reduce RTS->RTO cache line upgrades on SPARC and IA32 processors. - Thread * const Self = THREAD ; - void * cur ; + Thread * const Self = THREAD; + void * cur; - cur = Atomic::cmpxchg_ptr (Self, &_owner, NULL) ; + cur = Atomic::cmpxchg_ptr(Self, &_owner, NULL); if (cur == NULL) { // Either ASSERT _recursions == 0 or explicitly set _recursions = 0. - assert (_recursions == 0 , "invariant") ; - assert (_owner == Self, "invariant") ; + assert(_recursions == 0 , "invariant"); + assert(_owner == Self, "invariant"); // CONSIDER: set or assert OwnerIsThread == 1 - return ; + return; } if (cur == Self) { // TODO-FIXME: check for integer overflow! BUGID 6557169. - _recursions ++ ; - return ; + _recursions++; + return; } if (Self->is_lock_owned ((address)cur)) { - assert (_recursions == 0, "internal state error"); - _recursions = 1 ; + assert(_recursions == 0, "internal state error"); + _recursions = 1; // Commute owner from a thread-specific on-stack BasicLockObject address to // a full-fledged "Thread *". - _owner = Self ; - OwnerIsThread = 1 ; - return ; + _owner = Self; + OwnerIsThread = 1; + return; } // We've encountered genuine contention. - assert (Self->_Stalled == 0, "invariant") ; - Self->_Stalled = intptr_t(this) ; + assert(Self->_Stalled == 0, "invariant"); + Self->_Stalled = intptr_t(this); // Try one round of spinning *before* enqueueing Self // and before going through the awkward and expensive state @@ -321,21 +321,21 @@ void ATTR ObjectMonitor::enter(TRAPS) { // Note that if we acquire the monitor from an initial spin // we forgo posting JVMTI events and firing DTRACE probes. if (Knob_SpinEarly && TrySpin (Self) > 0) { - assert (_owner == Self , "invariant") ; - assert (_recursions == 0 , "invariant") ; - assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; - Self->_Stalled = 0 ; - return ; + assert(_owner == Self , "invariant"); + assert(_recursions == 0 , "invariant"); + assert(((oop)(object()))->mark() == markOopDesc::encode(this), "invariant"); + Self->_Stalled = 0; + return; } - assert (_owner != Self , "invariant") ; - assert (_succ != Self , "invariant") ; - assert (Self->is_Java_thread() , "invariant") ; - JavaThread * jt = (JavaThread *) Self ; - assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ; - assert (jt->thread_state() != _thread_blocked , "invariant") ; - assert (this->object() != NULL , "invariant") ; - assert (_count >= 0, "invariant") ; + assert(_owner != Self , "invariant"); + assert(_succ != Self , "invariant"); + assert(Self->is_Java_thread() , "invariant"); + JavaThread * jt = (JavaThread *) Self; + assert(!SafepointSynchronize::is_at_safepoint(), "invariant"); + assert(jt->thread_state() != _thread_blocked , "invariant"); + assert(this->object() != NULL , "invariant"); + assert(_count >= 0, "invariant"); // Prevent deflation at STW-time. See deflate_idle_monitors() and is_busy(). // Ensure the object-monitor relationship remains stable while there's contention. @@ -368,9 +368,9 @@ void ATTR ObjectMonitor::enter(TRAPS) { // cleared by handle_special_suspend_equivalent_condition() // or java_suspend_self() - EnterI (THREAD) ; + EnterI(THREAD); - if (!ExitSuspendEquivalent(jt)) break ; + if (!ExitSuspendEquivalent(jt)) break; // // We have acquired the contended monitor, but while we were @@ -378,9 +378,9 @@ void ATTR ObjectMonitor::enter(TRAPS) { // the monitor while suspended because that would surprise the // thread that suspended us. // - _recursions = 0 ; - _succ = NULL ; - exit (false, Self) ; + _recursions = 0; + _succ = NULL; + exit(false, Self); jt->java_suspend_self(); } @@ -397,14 +397,14 @@ void ATTR ObjectMonitor::enter(TRAPS) { } Atomic::dec_ptr(&_count); - assert (_count >= 0, "invariant") ; - Self->_Stalled = 0 ; + assert(_count >= 0, "invariant"); + Self->_Stalled = 0; // Must either set _recursions = 0 or ASSERT _recursions == 0. - assert (_recursions == 0 , "invariant") ; - assert (_owner == Self , "invariant") ; - assert (_succ != Self , "invariant") ; - assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; + assert(_recursions == 0 , "invariant"); + assert(_owner == Self , "invariant"); + assert(_succ != Self , "invariant"); + assert(((oop)(object()))->mark() == markOopDesc::encode(this), "invariant"); // The thread -- now the owner -- is back in vm mode. // Report the glorious news via TI,DTrace and jvmstat. @@ -437,7 +437,7 @@ void ATTR ObjectMonitor::enter(TRAPS) { } if (ObjectMonitor::_sync_ContendedLockAttempts != NULL) { - ObjectMonitor::_sync_ContendedLockAttempts->inc() ; + ObjectMonitor::_sync_ContendedLockAttempts->inc(); } } @@ -447,37 +447,37 @@ void ATTR ObjectMonitor::enter(TRAPS) { int ObjectMonitor::TryLock (Thread * Self) { for (;;) { - void * own = _owner ; - if (own != NULL) return 0 ; + void * own = _owner; + if (own != NULL) return 0; if (Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) { // Either guarantee _recursions == 0 or set _recursions = 0. - assert (_recursions == 0, "invariant") ; - assert (_owner == Self, "invariant") ; + assert(_recursions == 0, "invariant"); + assert(_owner == Self, "invariant"); // CONSIDER: set or assert that OwnerIsThread == 1 - return 1 ; + return 1; } // The lock had been free momentarily, but we lost the race to the lock. // Interference -- the CAS failed. // We can either return -1 or retry. // Retry doesn't make as much sense because the lock was just acquired. - if (true) return -1 ; + if (true) return -1; } } void ATTR ObjectMonitor::EnterI (TRAPS) { - Thread * Self = THREAD ; - assert (Self->is_Java_thread(), "invariant") ; - assert (((JavaThread *) Self)->thread_state() == _thread_blocked , "invariant") ; + Thread * Self = THREAD; + assert(Self->is_Java_thread(), "invariant"); + assert(((JavaThread *) Self)->thread_state() == _thread_blocked , "invariant"); // Try the lock - TATAS if (TryLock (Self) > 0) { - assert (_succ != Self , "invariant") ; - assert (_owner == Self , "invariant") ; - assert (_Responsible != Self , "invariant") ; - return ; + assert(_succ != Self , "invariant"); + assert(_owner == Self , "invariant"); + assert(_Responsible != Self , "invariant"); + return; } - DeferredInitialize () ; + DeferredInitialize(); // We try one round of spinning *before* enqueueing Self. // @@ -487,16 +487,16 @@ void ATTR ObjectMonitor::EnterI (TRAPS) { // effects. if (TrySpin (Self) > 0) { - assert (_owner == Self , "invariant") ; - assert (_succ != Self , "invariant") ; - assert (_Responsible != Self , "invariant") ; - return ; + assert(_owner == Self , "invariant"); + assert(_succ != Self , "invariant"); + assert(_Responsible != Self , "invariant"); + return; } // The Spin failed -- Enqueue and park the thread ... - assert (_succ != Self , "invariant") ; - assert (_owner != Self , "invariant") ; - assert (_Responsible != Self , "invariant") ; + assert(_succ != Self , "invariant"); + assert(_owner != Self , "invariant"); + assert(_Responsible != Self , "invariant"); // Enqueue "Self" on ObjectMonitor's _cxq. // @@ -508,27 +508,27 @@ void ATTR ObjectMonitor::EnterI (TRAPS) { // TODO: eliminate ObjectWaiter and enqueue either Threads or Events. // - ObjectWaiter node(Self) ; - Self->_ParkEvent->reset() ; - node._prev = (ObjectWaiter *) 0xBAD ; - node.TState = ObjectWaiter::TS_CXQ ; + ObjectWaiter node(Self); + Self->_ParkEvent->reset(); + node._prev = (ObjectWaiter *) 0xBAD; + node.TState = ObjectWaiter::TS_CXQ; // Push "Self" onto the front of the _cxq. // Once on cxq/EntryList, Self stays on-queue until it acquires the lock. // Note that spinning tends to reduce the rate at which threads // enqueue and dequeue on EntryList|cxq. - ObjectWaiter * nxt ; + ObjectWaiter * nxt; for (;;) { - node._next = nxt = _cxq ; - if (Atomic::cmpxchg_ptr (&node, &_cxq, nxt) == nxt) break ; + node._next = nxt = _cxq; + if (Atomic::cmpxchg_ptr(&node, &_cxq, nxt) == nxt) break; // Interference - the CAS failed because _cxq changed. Just retry. // As an optional optimization we retry the lock. if (TryLock (Self) > 0) { - assert (_succ != Self , "invariant") ; - assert (_owner == Self , "invariant") ; - assert (_Responsible != Self , "invariant") ; - return ; + assert(_succ != Self , "invariant"); + assert(_owner == Self , "invariant"); + assert(_Responsible != Self , "invariant"); + return; } } @@ -558,7 +558,7 @@ void ATTR ObjectMonitor::EnterI (TRAPS) { if ((SyncFlags & 16) == 0 && nxt == NULL && _EntryList == NULL) { // Try to assume the role of responsible thread for the monitor. // CONSIDER: ST vs CAS vs { if (Responsible==null) Responsible=Self } - Atomic::cmpxchg_ptr (Self, &_Responsible, NULL) ; + Atomic::cmpxchg_ptr(Self, &_Responsible, NULL); } // The lock have been released while this thread was occupied queueing @@ -572,49 +572,49 @@ void ATTR ObjectMonitor::EnterI (TRAPS) { // to defer the state transitions until absolutely necessary, // and in doing so avoid some transitions ... - TEVENT (Inflated enter - Contention) ; - int nWakeups = 0 ; - int RecheckInterval = 1 ; + TEVENT(Inflated enter - Contention); + int nWakeups = 0; + int RecheckInterval = 1; for (;;) { - if (TryLock (Self) > 0) break ; - assert (_owner != Self, "invariant") ; + if (TryLock(Self) > 0) break; + assert(_owner != Self, "invariant"); if ((SyncFlags & 2) && _Responsible == NULL) { - Atomic::cmpxchg_ptr (Self, &_Responsible, NULL) ; + Atomic::cmpxchg_ptr(Self, &_Responsible, NULL); } // park self if (_Responsible == Self || (SyncFlags & 1)) { - TEVENT (Inflated enter - park TIMED) ; - Self->_ParkEvent->park ((jlong) RecheckInterval) ; + TEVENT(Inflated enter - park TIMED); + Self->_ParkEvent->park((jlong) RecheckInterval); // Increase the RecheckInterval, but clamp the value. - RecheckInterval *= 8 ; - if (RecheckInterval > 1000) RecheckInterval = 1000 ; + RecheckInterval *= 8; + if (RecheckInterval > 1000) RecheckInterval = 1000; } else { - TEVENT (Inflated enter - park UNTIMED) ; - Self->_ParkEvent->park() ; + TEVENT(Inflated enter - park UNTIMED); + Self->_ParkEvent->park(); } - if (TryLock(Self) > 0) break ; + if (TryLock(Self) > 0) break; // The lock is still contested. // Keep a tally of the # of futile wakeups. // Note that the counter is not protected by a lock or updated by atomics. // That is by design - we trade "lossy" counters which are exposed to // races during updates for a lower probe effect. - TEVENT (Inflated enter - Futile wakeup) ; + TEVENT(Inflated enter - Futile wakeup); if (ObjectMonitor::_sync_FutileWakeups != NULL) { - ObjectMonitor::_sync_FutileWakeups->inc() ; + ObjectMonitor::_sync_FutileWakeups->inc(); } - ++ nWakeups ; + ++nWakeups; // Assuming this is not a spurious wakeup we'll normally find _succ == Self. // We can defer clearing _succ until after the spin completes // TrySpin() must tolerate being called with _succ == Self. // Try yet another round of adaptive spinning. - if ((Knob_SpinAfterFutile & 1) && TrySpin (Self) > 0) break ; + if ((Knob_SpinAfterFutile & 1) && TrySpin(Self) > 0) break; // We can find that we were unpark()ed and redesignated _succ while // we were spinning. That's harmless. If we iterate and call park(), @@ -625,13 +625,13 @@ void ATTR ObjectMonitor::EnterI (TRAPS) { // in the next iteration. if ((Knob_ResetEvent & 1) && Self->_ParkEvent->fired()) { - Self->_ParkEvent->reset() ; - OrderAccess::fence() ; + Self->_ParkEvent->reset(); + OrderAccess::fence(); } - if (_succ == Self) _succ = NULL ; + if (_succ == Self) _succ = NULL; // Invariant: after clearing _succ a thread *must* retry _owner before parking. - OrderAccess::fence() ; + OrderAccess::fence(); } // Egress : @@ -642,18 +642,18 @@ void ATTR ObjectMonitor::EnterI (TRAPS) { // The head of cxq is volatile but the interior is stable. // In addition, Self.TState is stable. - assert (_owner == Self , "invariant") ; - assert (object() != NULL , "invariant") ; + assert(_owner == Self , "invariant"); + assert(object() != NULL , "invariant"); // I'd like to write: // guarantee (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; // but as we're at a safepoint that's not safe. - UnlinkAfterAcquire (Self, &node) ; - if (_succ == Self) _succ = NULL ; + UnlinkAfterAcquire(Self, &node); + if (_succ == Self) _succ = NULL; - assert (_succ != Self, "invariant") ; + assert(_succ != Self, "invariant"); if (_Responsible == Self) { - _Responsible = NULL ; + _Responsible = NULL; OrderAccess::fence(); // Dekker pivot-point // We may leave threads on cxq|EntryList without a designated @@ -700,9 +700,9 @@ void ATTR ObjectMonitor::EnterI (TRAPS) { // execute a serializing instruction. if (SyncFlags & 8) { - OrderAccess::fence() ; + OrderAccess::fence(); } - return ; + return; } // ReenterI() is a specialized inline form of the latter half of the @@ -714,24 +714,24 @@ void ATTR ObjectMonitor::EnterI (TRAPS) { // loop accordingly. void ATTR ObjectMonitor::ReenterI (Thread * Self, ObjectWaiter * SelfNode) { - assert (Self != NULL , "invariant") ; - assert (SelfNode != NULL , "invariant") ; - assert (SelfNode->_thread == Self , "invariant") ; - assert (_waiters > 0 , "invariant") ; - assert (((oop)(object()))->mark() == markOopDesc::encode(this) , "invariant") ; - assert (((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ; - JavaThread * jt = (JavaThread *) Self ; + assert(Self != NULL , "invariant"); + assert(SelfNode != NULL , "invariant"); + assert(SelfNode->_thread == Self , "invariant"); + assert(_waiters > 0 , "invariant"); + assert(((oop)(object()))->mark() == markOopDesc::encode(this) , "invariant"); + assert(((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant"); + JavaThread * jt = (JavaThread *) Self; - int nWakeups = 0 ; + int nWakeups = 0; for (;;) { - ObjectWaiter::TStates v = SelfNode->TState ; - guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ; - assert (_owner != Self, "invariant") ; + ObjectWaiter::TStates v = SelfNode->TState; + guarantee(v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant"); + assert(_owner != Self, "invariant"); - if (TryLock (Self) > 0) break ; - if (TrySpin (Self) > 0) break ; + if (TryLock(Self) > 0) break; + if (TrySpin(Self) > 0) break; - TEVENT (Wait Reentry - parking) ; + TEVENT(Wait Reentry - parking); // State transition wrappers around park() ... // ReenterI() wisely defers state transitions until @@ -744,14 +744,14 @@ void ATTR ObjectMonitor::ReenterI (Thread * Self, ObjectWaiter * SelfNode) { // or java_suspend_self() jt->set_suspend_equivalent(); if (SyncFlags & 1) { - Self->_ParkEvent->park ((jlong)1000) ; + Self->_ParkEvent->park((jlong)1000); } else { - Self->_ParkEvent->park () ; + Self->_ParkEvent->park(); } // were we externally suspended while we were waiting? for (;;) { - if (!ExitSuspendEquivalent (jt)) break ; + if (!ExitSuspendEquivalent(jt)) break; if (_succ == Self) { _succ = NULL; OrderAccess::fence(); } jt->java_suspend_self(); jt->set_suspend_equivalent(); @@ -761,26 +761,26 @@ void ATTR ObjectMonitor::ReenterI (Thread * Self, ObjectWaiter * SelfNode) { // Try again, but just so we distinguish between futile wakeups and // successful wakeups. The following test isn't algorithmically // necessary, but it helps us maintain sensible statistics. - if (TryLock(Self) > 0) break ; + if (TryLock(Self) > 0) break; // The lock is still contested. // Keep a tally of the # of futile wakeups. // Note that the counter is not protected by a lock or updated by atomics. // That is by design - we trade "lossy" counters which are exposed to // races during updates for a lower probe effect. - TEVENT (Wait Reentry - futile wakeup) ; - ++ nWakeups ; + TEVENT(Wait Reentry - futile wakeup); + ++nWakeups; // Assuming this is not a spurious wakeup we'll normally // find that _succ == Self. - if (_succ == Self) _succ = NULL ; + if (_succ == Self) _succ = NULL; // Invariant: after clearing _succ a contending thread // *must* retry _owner before parking. - OrderAccess::fence() ; + OrderAccess::fence(); if (ObjectMonitor::_sync_FutileWakeups != NULL) { - ObjectMonitor::_sync_FutileWakeups->inc() ; + ObjectMonitor::_sync_FutileWakeups->inc(); } } @@ -792,13 +792,13 @@ void ATTR ObjectMonitor::ReenterI (Thread * Self, ObjectWaiter * SelfNode) { // The head of cxq is volatile but the interior is stable. // In addition, Self.TState is stable. - assert (_owner == Self, "invariant") ; - assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; - UnlinkAfterAcquire (Self, SelfNode) ; - if (_succ == Self) _succ = NULL ; - assert (_succ != Self, "invariant") ; - SelfNode->TState = ObjectWaiter::TS_RUN ; - OrderAccess::fence() ; // see comments at the end of EnterI() + assert(_owner == Self, "invariant"); + assert(((oop)(object()))->mark() == markOopDesc::encode(this), "invariant"); + UnlinkAfterAcquire(Self, SelfNode); + if (_succ == Self) _succ = NULL; + assert(_succ != Self, "invariant"); + SelfNode->TState = ObjectWaiter::TS_RUN; + OrderAccess::fence(); // see comments at the end of EnterI() } // after the thread acquires the lock in ::enter(). Equally, we could defer @@ -806,22 +806,22 @@ void ATTR ObjectMonitor::ReenterI (Thread * Self, ObjectWaiter * SelfNode) { void ObjectMonitor::UnlinkAfterAcquire (Thread * Self, ObjectWaiter * SelfNode) { - assert (_owner == Self, "invariant") ; - assert (SelfNode->_thread == Self, "invariant") ; + assert(_owner == Self, "invariant"); + assert(SelfNode->_thread == Self, "invariant"); if (SelfNode->TState == ObjectWaiter::TS_ENTER) { // Normal case: remove Self from the DLL EntryList . // This is a constant-time operation. - ObjectWaiter * nxt = SelfNode->_next ; - ObjectWaiter * prv = SelfNode->_prev ; - if (nxt != NULL) nxt->_prev = prv ; - if (prv != NULL) prv->_next = nxt ; - if (SelfNode == _EntryList ) _EntryList = nxt ; - assert (nxt == NULL || nxt->TState == ObjectWaiter::TS_ENTER, "invariant") ; - assert (prv == NULL || prv->TState == ObjectWaiter::TS_ENTER, "invariant") ; - TEVENT (Unlink from EntryList) ; + ObjectWaiter * nxt = SelfNode->_next; + ObjectWaiter * prv = SelfNode->_prev; + if (nxt != NULL) nxt->_prev = prv; + if (prv != NULL) prv->_next = nxt; + if (SelfNode == _EntryList) _EntryList = nxt; + assert(nxt == NULL || nxt->TState == ObjectWaiter::TS_ENTER, "invariant"); + assert(prv == NULL || prv->TState == ObjectWaiter::TS_ENTER, "invariant"); + TEVENT(Unlink from EntryList); } else { - guarantee (SelfNode->TState == ObjectWaiter::TS_CXQ, "invariant") ; + guarantee(SelfNode->TState == ObjectWaiter::TS_CXQ, "invariant"); // Inopportune interleaving -- Self is still on the cxq. // This usually means the enqueue of self raced an exiting thread. // Normally we'll find Self near the front of the cxq, so @@ -835,36 +835,36 @@ void ObjectMonitor::UnlinkAfterAcquire (Thread * Self, ObjectWaiter * SelfNode) // and then unlink Self from EntryList. We have to drain eventually, // so it might as well be now. - ObjectWaiter * v = _cxq ; - assert (v != NULL, "invariant") ; + ObjectWaiter * v = _cxq; + assert(v != NULL, "invariant"); if (v != SelfNode || Atomic::cmpxchg_ptr (SelfNode->_next, &_cxq, v) != v) { // The CAS above can fail from interference IFF a "RAT" arrived. // In that case Self must be in the interior and can no longer be // at the head of cxq. if (v == SelfNode) { - assert (_cxq != v, "invariant") ; - v = _cxq ; // CAS above failed - start scan at head of list + assert(_cxq != v, "invariant"); + v = _cxq; // CAS above failed - start scan at head of list } - ObjectWaiter * p ; - ObjectWaiter * q = NULL ; - for (p = v ; p != NULL && p != SelfNode; p = p->_next) { - q = p ; - assert (p->TState == ObjectWaiter::TS_CXQ, "invariant") ; + ObjectWaiter * p; + ObjectWaiter * q = NULL; + for (p = v; p != NULL && p != SelfNode; p = p->_next) { + q = p; + assert(p->TState == ObjectWaiter::TS_CXQ, "invariant"); } - assert (v != SelfNode, "invariant") ; - assert (p == SelfNode, "Node not found on cxq") ; - assert (p != _cxq, "invariant") ; - assert (q != NULL, "invariant") ; - assert (q->_next == p, "invariant") ; - q->_next = p->_next ; + assert(v != SelfNode, "invariant"); + assert(p == SelfNode, "Node not found on cxq"); + assert(p != _cxq, "invariant"); + assert(q != NULL, "invariant"); + assert(q->_next == p, "invariant"); + q->_next = p->_next; } - TEVENT (Unlink from cxq) ; + TEVENT(Unlink from cxq); } // Diagnostic hygiene ... - SelfNode->_prev = (ObjectWaiter *) 0xBAD ; - SelfNode->_next = (ObjectWaiter *) 0xBAD ; - SelfNode->TState = ObjectWaiter::TS_RUN ; + SelfNode->_prev = (ObjectWaiter *) 0xBAD; + SelfNode->_next = (ObjectWaiter *) 0xBAD; + SelfNode->TState = ObjectWaiter::TS_RUN; } // ----------------------------------------------------------------------------- @@ -919,22 +919,22 @@ void ObjectMonitor::UnlinkAfterAcquire (Thread * Self, ObjectWaiter * SelfNode) // a monitor will use a timer. void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { - Thread * Self = THREAD ; + Thread * Self = THREAD; if (THREAD != _owner) { if (THREAD->is_lock_owned((address) _owner)) { // Transmute _owner from a BasicLock pointer to a Thread address. // We don't need to hold _mutex for this transition. // Non-null to Non-null is safe as long as all readers can // tolerate either flavor. - assert (_recursions == 0, "invariant") ; - _owner = THREAD ; - _recursions = 0 ; - OwnerIsThread = 1 ; + assert(_recursions == 0, "invariant"); + _owner = THREAD; + _recursions = 0; + OwnerIsThread = 1; } else { // NOTE: we need to handle unbalanced monitor enter/exit // in native code by throwing an exception. // TODO: Throw an IllegalMonitorStateException ? - TEVENT (Exit - Throw IMSX) ; + TEVENT(Exit - Throw IMSX); assert(false, "Non-balanced monitor enter/exit!"); if (false) { THROW(vmSymbols::java_lang_IllegalMonitorStateException()); @@ -945,14 +945,14 @@ void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { if (_recursions != 0) { _recursions--; // this is simple recursive enter - TEVENT (Inflated exit - recursive) ; - return ; + TEVENT(Inflated exit - recursive); + return; } // Invariant: after setting Responsible=null an thread must execute // a MEMBAR or other serializing instruction before fetching EntryList|cxq. if ((SyncFlags & 4) == 0) { - _Responsible = NULL ; + _Responsible = NULL; } #if INCLUDE_TRACE @@ -964,7 +964,7 @@ void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { #endif for (;;) { - assert (THREAD == _owner, "invariant") ; + assert(THREAD == _owner, "invariant"); if (Knob_ExitPolicy == 0) { @@ -980,13 +980,13 @@ void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { // in massive wasteful coherency traffic on classic SMP systems. // Instead, I use release_store(), which is implemented as just a simple // ST on x64, x86 and SPARC. - OrderAccess::release_store_ptr (&_owner, NULL) ; // drop the lock - OrderAccess::storeload() ; // See if we need to wake a successor + OrderAccess::release_store_ptr(&_owner, NULL); // drop the lock + OrderAccess::storeload(); // See if we need to wake a successor if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) { - TEVENT (Inflated exit - simple egress) ; - return ; + TEVENT(Inflated exit - simple egress); + return; } - TEVENT (Inflated exit - complex egress) ; + TEVENT(Inflated exit - complex egress); // Normally the exiting thread is responsible for ensuring succession, // but if other successors are ready or other entering threads are spinning @@ -1026,17 +1026,17 @@ void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { // falls to the new owner. // if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) { - return ; + return; } - TEVENT (Exit - Reacquired) ; + TEVENT(Exit - Reacquired); } else { if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) { - OrderAccess::release_store_ptr (&_owner, NULL) ; // drop the lock - OrderAccess::storeload() ; + OrderAccess::release_store_ptr(&_owner, NULL); // drop the lock + OrderAccess::storeload(); // Ratify the previously observed values. if (_cxq == NULL || _succ != NULL) { - TEVENT (Inflated exit - simple egress) ; - return ; + TEVENT(Inflated exit - simple egress); + return; } // inopportune interleaving -- the exiting thread (this thread) @@ -1051,29 +1051,29 @@ void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { // we could simply unpark() the lead thread and return // without having set _succ. if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) { - TEVENT (Inflated exit - reacquired succeeded) ; - return ; + TEVENT(Inflated exit - reacquired succeeded); + return; } - TEVENT (Inflated exit - reacquired failed) ; + TEVENT(Inflated exit - reacquired failed); } else { - TEVENT (Inflated exit - complex egress) ; + TEVENT(Inflated exit - complex egress); } } - guarantee (_owner == THREAD, "invariant") ; + guarantee(_owner == THREAD, "invariant"); - ObjectWaiter * w = NULL ; - int QMode = Knob_QMode ; + ObjectWaiter * w = NULL; + int QMode = Knob_QMode; if (QMode == 2 && _cxq != NULL) { // QMode == 2 : cxq has precedence over EntryList. // Try to directly wake a successor from the cxq. // If successful, the successor will need to unlink itself from cxq. - w = _cxq ; - assert (w != NULL, "invariant") ; - assert (w->TState == ObjectWaiter::TS_CXQ, "Invariant") ; - ExitEpilog (Self, w) ; - return ; + w = _cxq; + assert(w != NULL, "invariant"); + assert(w->TState == ObjectWaiter::TS_CXQ, "Invariant"); + ExitEpilog(Self, w); + return; } if (QMode == 3 && _cxq != NULL) { @@ -1082,33 +1082,33 @@ void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { // Drain _cxq into EntryList - bulk transfer. // First, detach _cxq. // The following loop is tantamount to: w = swap (&cxq, NULL) - w = _cxq ; + w = _cxq; for (;;) { - assert (w != NULL, "Invariant") ; - ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ; - if (u == w) break ; - w = u ; + assert(w != NULL, "Invariant"); + ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr(NULL, &_cxq, w); + if (u == w) break; + w = u; } - assert (w != NULL , "invariant") ; + assert(w != NULL , "invariant"); - ObjectWaiter * q = NULL ; - ObjectWaiter * p ; - for (p = w ; p != NULL ; p = p->_next) { - guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ; - p->TState = ObjectWaiter::TS_ENTER ; - p->_prev = q ; - q = p ; + ObjectWaiter * q = NULL; + ObjectWaiter * p; + for (p = w; p != NULL; p = p->_next) { + guarantee(p->TState == ObjectWaiter::TS_CXQ, "Invariant"); + p->TState = ObjectWaiter::TS_ENTER; + p->_prev = q; + q = p; } // Append the RATs to the EntryList // TODO: organize EntryList as a CDLL so we can locate the tail in constant-time. - ObjectWaiter * Tail ; - for (Tail = _EntryList ; Tail != NULL && Tail->_next != NULL ; Tail = Tail->_next) ; + ObjectWaiter * Tail; + for (Tail = _EntryList; Tail != NULL && Tail->_next != NULL; Tail = Tail->_next); if (Tail == NULL) { - _EntryList = w ; + _EntryList = w; } else { - Tail->_next = w ; - w->_prev = Tail ; + Tail->_next = w; + w->_prev = Tail; } // Fall thru into code that tries to wake a successor from EntryList @@ -1121,35 +1121,35 @@ void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { // Drain _cxq into EntryList - bulk transfer. // First, detach _cxq. // The following loop is tantamount to: w = swap (&cxq, NULL) - w = _cxq ; + w = _cxq; for (;;) { - assert (w != NULL, "Invariant") ; - ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ; - if (u == w) break ; - w = u ; + assert(w != NULL, "Invariant"); + ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr(NULL, &_cxq, w); + if (u == w) break; + w = u; } - assert (w != NULL , "invariant") ; + assert(w != NULL , "invariant"); - ObjectWaiter * q = NULL ; - ObjectWaiter * p ; - for (p = w ; p != NULL ; p = p->_next) { - guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ; - p->TState = ObjectWaiter::TS_ENTER ; - p->_prev = q ; - q = p ; + ObjectWaiter * q = NULL; + ObjectWaiter * p; + for (p = w; p != NULL; p = p->_next) { + guarantee(p->TState == ObjectWaiter::TS_CXQ, "Invariant"); + p->TState = ObjectWaiter::TS_ENTER; + p->_prev = q; + q = p; } // Prepend the RATs to the EntryList if (_EntryList != NULL) { - q->_next = _EntryList ; - _EntryList->_prev = q ; + q->_next = _EntryList; + _EntryList->_prev = q; } - _EntryList = w ; + _EntryList = w; // Fall thru into code that tries to wake a successor from EntryList } - w = _EntryList ; + w = _EntryList; if (w != NULL) { // I'd like to write: guarantee (w->_thread != Self). // But in practice an exiting thread may find itself on the EntryList. @@ -1162,29 +1162,29 @@ void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { // reacquires the lock and then finds itself on the EntryList. // Given all that, we have to tolerate the circumstance where "w" is // associated with Self. - assert (w->TState == ObjectWaiter::TS_ENTER, "invariant") ; - ExitEpilog (Self, w) ; - return ; + assert(w->TState == ObjectWaiter::TS_ENTER, "invariant"); + ExitEpilog(Self, w); + return; } // If we find that both _cxq and EntryList are null then just // re-run the exit protocol from the top. - w = _cxq ; - if (w == NULL) continue ; + w = _cxq; + if (w == NULL) continue; // Drain _cxq into EntryList - bulk transfer. // First, detach _cxq. // The following loop is tantamount to: w = swap (&cxq, NULL) for (;;) { - assert (w != NULL, "Invariant") ; - ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ; - if (u == w) break ; - w = u ; + assert(w != NULL, "Invariant"); + ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr(NULL, &_cxq, w); + if (u == w) break; + w = u; } - TEVENT (Inflated exit - drain cxq into EntryList) ; + TEVENT(Inflated exit - drain cxq into EntryList); - assert (w != NULL , "invariant") ; - assert (_EntryList == NULL , "invariant") ; + assert(w != NULL , "invariant"); + assert(_EntryList == NULL , "invariant"); // Convert the LIFO SLL anchored by _cxq into a DLL. // The list reorganization step operates in O(LENGTH(w)) time. @@ -1198,30 +1198,30 @@ void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { if (QMode == 1) { // QMode == 1 : drain cxq to EntryList, reversing order // We also reverse the order of the list. - ObjectWaiter * s = NULL ; - ObjectWaiter * t = w ; - ObjectWaiter * u = NULL ; + ObjectWaiter * s = NULL; + ObjectWaiter * t = w; + ObjectWaiter * u = NULL; while (t != NULL) { - guarantee (t->TState == ObjectWaiter::TS_CXQ, "invariant") ; - t->TState = ObjectWaiter::TS_ENTER ; - u = t->_next ; - t->_prev = u ; - t->_next = s ; + guarantee(t->TState == ObjectWaiter::TS_CXQ, "invariant"); + t->TState = ObjectWaiter::TS_ENTER; + u = t->_next; + t->_prev = u; + t->_next = s; s = t; - t = u ; + t = u; } - _EntryList = s ; - assert (s != NULL, "invariant") ; + _EntryList = s; + assert(s != NULL, "invariant"); } else { // QMode == 0 or QMode == 2 - _EntryList = w ; - ObjectWaiter * q = NULL ; - ObjectWaiter * p ; - for (p = w ; p != NULL ; p = p->_next) { - guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ; - p->TState = ObjectWaiter::TS_ENTER ; - p->_prev = q ; - q = p ; + _EntryList = w; + ObjectWaiter * q = NULL; + ObjectWaiter * p; + for (p = w; p != NULL; p = p->_next) { + guarantee(p->TState == ObjectWaiter::TS_CXQ, "Invariant"); + p->TState = ObjectWaiter::TS_ENTER; + p->_prev = q; + q = p; } } @@ -1233,11 +1233,11 @@ void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { // context-switch rate. if (_succ != NULL) continue; - w = _EntryList ; + w = _EntryList; if (w != NULL) { - guarantee (w->TState == ObjectWaiter::TS_ENTER, "invariant") ; - ExitEpilog (Self, w) ; - return ; + guarantee(w->TState == ObjectWaiter::TS_ENTER, "invariant"); + ExitEpilog(Self, w); + return; } } } @@ -1275,22 +1275,22 @@ void ATTR ObjectMonitor::exit(bool not_suspended, TRAPS) { bool ObjectMonitor::ExitSuspendEquivalent (JavaThread * jSelf) { - int Mode = Knob_FastHSSEC ; + int Mode = Knob_FastHSSEC; if (Mode && !jSelf->is_external_suspend()) { - assert (jSelf->is_suspend_equivalent(), "invariant") ; - jSelf->clear_suspend_equivalent() ; - if (2 == Mode) OrderAccess::storeload() ; - if (!jSelf->is_external_suspend()) return false ; + assert(jSelf->is_suspend_equivalent(), "invariant"); + jSelf->clear_suspend_equivalent(); + if (2 == Mode) OrderAccess::storeload(); + if (!jSelf->is_external_suspend()) return false; // We raced a suspension -- fall thru into the slow path - TEVENT (ExitSuspendEquivalent - raced) ; - jSelf->set_suspend_equivalent() ; + TEVENT(ExitSuspendEquivalent - raced); + jSelf->set_suspend_equivalent(); } - return jSelf->handle_special_suspend_equivalent_condition() ; + return jSelf->handle_special_suspend_equivalent_condition(); } void ObjectMonitor::ExitEpilog (Thread * Self, ObjectWaiter * Wakee) { - assert (_owner == Self, "invariant") ; + assert(_owner == Self, "invariant"); // Exit protocol: // 1. ST _succ = wakee @@ -1298,28 +1298,28 @@ void ObjectMonitor::ExitEpilog (Thread * Self, ObjectWaiter * Wakee) { // 2. ST _owner = NULL // 3. unpark(wakee) - _succ = Knob_SuccEnabled ? Wakee->_thread : NULL ; - ParkEvent * Trigger = Wakee->_event ; + _succ = Knob_SuccEnabled ? Wakee->_thread : NULL; + ParkEvent * Trigger = Wakee->_event; // Hygiene -- once we've set _owner = NULL we can't safely dereference Wakee again. // The thread associated with Wakee may have grabbed the lock and "Wakee" may be // out-of-scope (non-extant). - Wakee = NULL ; + Wakee = NULL; // Drop the lock - OrderAccess::release_store_ptr (&_owner, NULL) ; - OrderAccess::fence() ; // ST _owner vs LD in unpark() + OrderAccess::release_store_ptr(&_owner, NULL); + OrderAccess::fence(); // ST _owner vs LD in unpark() if (SafepointSynchronize::do_call_back()) { - TEVENT (unpark before SAFEPOINT) ; + TEVENT(unpark before SAFEPOINT); } DTRACE_MONITOR_PROBE(contended__exit, this, object(), Self); - Trigger->unpark() ; + Trigger->unpark(); // Maintain stats and report events to JVMTI if (ObjectMonitor::_sync_Parks != NULL) { - ObjectMonitor::_sync_Parks->inc() ; + ObjectMonitor::_sync_Parks->inc(); } } @@ -1343,17 +1343,17 @@ intptr_t ObjectMonitor::complete_exit(TRAPS) { if (THREAD != _owner) { if (THREAD->is_lock_owned ((address)_owner)) { assert(_recursions == 0, "internal state error"); - _owner = THREAD ; /* Convert from basiclock addr to Thread addr */ - _recursions = 0 ; - OwnerIsThread = 1 ; + _owner = THREAD; /* Convert from basiclock addr to Thread addr */ + _recursions = 0; + OwnerIsThread = 1; } } guarantee(Self == _owner, "complete_exit not owner"); intptr_t save = _recursions; // record the old recursion count _recursions = 0; // set the recursion level to be 0 - exit (true, Self) ; // exit the monitor - guarantee (_owner != Self, "invariant"); + exit(true, Self); // exit the monitor + guarantee(_owner != Self, "invariant"); return save; } @@ -1365,8 +1365,8 @@ void ObjectMonitor::reenter(intptr_t recursions, TRAPS) { JavaThread *jt = (JavaThread *)THREAD; guarantee(_owner != Self, "reenter already owner"); - enter (THREAD); // enter the monitor - guarantee (_recursions == 0, "reenter recursion"); + enter(THREAD); // enter the monitor + guarantee(_recursions == 0, "reenter recursion"); _recursions = recursions; return; } @@ -1382,11 +1382,11 @@ void ObjectMonitor::reenter(intptr_t recursions, TRAPS) { do { \ if (THREAD != _owner) { \ if (THREAD->is_lock_owned((address) _owner)) { \ - _owner = THREAD ; /* Convert from basiclock addr to Thread addr */ \ + _owner = THREAD; /* Convert from basiclock addr to Thread addr */ \ _recursions = 0; \ - OwnerIsThread = 1 ; \ + OwnerIsThread = 1; \ } else { \ - TEVENT (Throw IMSX) ; \ + TEVENT(Throw IMSX); \ THROW(vmSymbols::java_lang_IllegalMonitorStateException()); \ } \ } \ @@ -1396,15 +1396,15 @@ void ObjectMonitor::reenter(intptr_t recursions, TRAPS) { // TODO-FIXME: remove check_slow() -- it's likely dead. void ObjectMonitor::check_slow(TRAPS) { - TEVENT (check_slow - throw IMSX) ; + TEVENT(check_slow - throw IMSX); assert(THREAD != _owner && !THREAD->is_lock_owned((address) _owner), "must not be owner"); THROW_MSG(vmSymbols::java_lang_IllegalMonitorStateException(), "current thread not owner"); } static int Adjust (volatile int * adr, int dx) { - int v ; - for (v = *adr ; Atomic::cmpxchg (v + dx, adr, v) != v; v = *adr) ; - return v ; + int v; + for (v = *adr; Atomic::cmpxchg(v + dx, adr, v) != v; v = *adr); + return v; } // helper method for posting a monitor wait event @@ -1426,11 +1426,11 @@ void ObjectMonitor::post_monitor_wait_event(EventJavaMonitorWait* event, // Note: a subset of changes to ObjectMonitor::wait() // will need to be replicated in complete_exit above void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) { - Thread * const Self = THREAD ; + Thread * const Self = THREAD; assert(Self->is_Java_thread(), "Must be Java thread!"); JavaThread *jt = (JavaThread *)THREAD; - DeferredInitialize () ; + DeferredInitialize(); // Throw IMSX or IEX. CHECK_OWNER(); @@ -1456,23 +1456,23 @@ void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) { if (event.should_commit()) { post_monitor_wait_event(&event, 0, millis, false); } - TEVENT (Wait - Throw IEX) ; + TEVENT(Wait - Throw IEX); THROW(vmSymbols::java_lang_InterruptedException()); - return ; + return; } - TEVENT (Wait) ; + TEVENT(Wait); - assert (Self->_Stalled == 0, "invariant") ; - Self->_Stalled = intptr_t(this) ; + assert(Self->_Stalled == 0, "invariant"); + Self->_Stalled = intptr_t(this); jt->set_current_waiting_monitor(this); // create a node to be put into the queue // Critically, after we reset() the event but prior to park(), we must check // for a pending interrupt. ObjectWaiter node(Self); - node.TState = ObjectWaiter::TS_WAIT ; - Self->_ParkEvent->reset() ; + node.TState = ObjectWaiter::TS_WAIT; + Self->_ParkEvent->reset(); OrderAccess::fence(); // ST into Event; membar ; LD interrupted-flag // Enter the waiting queue, which is a circular doubly linked list in this case @@ -1482,18 +1482,18 @@ void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) { // returns because of a timeout of interrupt. Contention is exceptionally rare // so we use a simple spin-lock instead of a heavier-weight blocking lock. - Thread::SpinAcquire (&_WaitSetLock, "WaitSet - add") ; - AddWaiter (&node) ; - Thread::SpinRelease (&_WaitSetLock) ; + Thread::SpinAcquire(&_WaitSetLock, "WaitSet - add"); + AddWaiter(&node); + Thread::SpinRelease(&_WaitSetLock); if ((SyncFlags & 4) == 0) { - _Responsible = NULL ; + _Responsible = NULL; } intptr_t save = _recursions; // record the old recursion count _waiters++; // increment the number of waiters _recursions = 0; // set the recursion level to be 1 - exit (true, Self) ; // exit the monitor - guarantee (_owner != Self, "invariant") ; + exit(true, Self); // exit the monitor + guarantee(_owner != Self, "invariant"); // The thread is on the WaitSet list - now park() it. // On MP systems it's conceivable that a brief spin before we park @@ -1502,8 +1502,8 @@ void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) { // TODO-FIXME: change the following logic to a loop of the form // while (!timeout && !interrupted && _notified == 0) park() - int ret = OS_OK ; - int WasNotified = 0 ; + int ret = OS_OK; + int WasNotified = 0; { // State transition wrappers OSThread* osthread = Self->osthread(); OSThreadWaitState osts(osthread, true); @@ -1517,9 +1517,9 @@ void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) { } else if (node._notified == 0) { if (millis <= 0) { - Self->_ParkEvent->park () ; + Self->_ParkEvent->park(); } else { - ret = Self->_ParkEvent->park (millis) ; + ret = Self->_ParkEvent->park(millis); } } @@ -1548,23 +1548,23 @@ void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) { // That is, we fail toward safety. if (node.TState == ObjectWaiter::TS_WAIT) { - Thread::SpinAcquire (&_WaitSetLock, "WaitSet - unlink") ; + Thread::SpinAcquire(&_WaitSetLock, "WaitSet - unlink"); if (node.TState == ObjectWaiter::TS_WAIT) { - DequeueSpecificWaiter (&node) ; // unlink from WaitSet + DequeueSpecificWaiter(&node); // unlink from WaitSet assert(node._notified == 0, "invariant"); - node.TState = ObjectWaiter::TS_RUN ; + node.TState = ObjectWaiter::TS_RUN; } - Thread::SpinRelease (&_WaitSetLock) ; + Thread::SpinRelease(&_WaitSetLock); } // The thread is now either on off-list (TS_RUN), // on the EntryList (TS_ENTER), or on the cxq (TS_CXQ). // The Node's TState variable is stable from the perspective of this thread. // No other threads will asynchronously modify TState. - guarantee (node.TState != ObjectWaiter::TS_WAIT, "invariant") ; - OrderAccess::loadload() ; - if (_succ == Self) _succ = NULL ; - WasNotified = node._notified ; + guarantee(node.TState != ObjectWaiter::TS_WAIT, "invariant"); + OrderAccess::loadload(); + if (_succ == Self) _succ = NULL; + WasNotified = node._notified; // Reentry phase -- reacquire the monitor. // re-enter contended monitor after object.wait(). @@ -1601,18 +1601,18 @@ void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) { post_monitor_wait_event(&event, node._notifier_tid, millis, ret == OS_TIMEOUT); } - OrderAccess::fence() ; + OrderAccess::fence(); - assert (Self->_Stalled != 0, "invariant") ; - Self->_Stalled = 0 ; + assert(Self->_Stalled != 0, "invariant"); + Self->_Stalled = 0; - assert (_owner != Self, "invariant") ; - ObjectWaiter::TStates v = node.TState ; + assert(_owner != Self, "invariant"); + ObjectWaiter::TStates v = node.TState; if (v == ObjectWaiter::TS_RUN) { - enter (Self) ; + enter(Self); } else { - guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ; - ReenterI (Self, &node) ; + guarantee(v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant"); + ReenterI(Self, &node); node.wait_reenter_end(this); } @@ -1620,24 +1620,24 @@ void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) { // Lifecycle - the node representing Self must not appear on any queues. // Node is about to go out-of-scope, but even if it were immortal we wouldn't // want residual elements associated with this thread left on any lists. - guarantee (node.TState == ObjectWaiter::TS_RUN, "invariant") ; - assert (_owner == Self, "invariant") ; - assert (_succ != Self , "invariant") ; + guarantee(node.TState == ObjectWaiter::TS_RUN, "invariant"); + assert(_owner == Self, "invariant"); + assert(_succ != Self , "invariant"); } // OSThreadWaitState() jt->set_current_waiting_monitor(NULL); - guarantee (_recursions == 0, "invariant") ; + guarantee(_recursions == 0, "invariant"); _recursions = save; // restore the old recursion count _waiters--; // decrement the number of waiters // Verify a few postconditions - assert (_owner == Self , "invariant") ; - assert (_succ != Self , "invariant") ; - assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; + assert(_owner == Self , "invariant"); + assert(_succ != Self , "invariant"); + assert(((oop)(object()))->mark() == markOopDesc::encode(this), "invariant"); if (SyncFlags & 32) { - OrderAccess::fence() ; + OrderAccess::fence(); } // check if the notification happened @@ -1645,7 +1645,7 @@ void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) { // no, it could be timeout or Thread.interrupt() or both // check for interrupt event, otherwise it is timeout if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) { - TEVENT (Wait - throw IEX from epilog) ; + TEVENT(Wait - throw IEX from epilog); THROW(vmSymbols::java_lang_InterruptedException()); } } @@ -1663,99 +1663,99 @@ void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) { void ObjectMonitor::notify(TRAPS) { CHECK_OWNER(); if (_WaitSet == NULL) { - TEVENT (Empty-Notify) ; - return ; + TEVENT(Empty-Notify); + return; } DTRACE_MONITOR_PROBE(notify, this, object(), THREAD); - int Policy = Knob_MoveNotifyee ; + int Policy = Knob_MoveNotifyee; - Thread::SpinAcquire (&_WaitSetLock, "WaitSet - notify") ; - ObjectWaiter * iterator = DequeueWaiter() ; + Thread::SpinAcquire(&_WaitSetLock, "WaitSet - notify"); + ObjectWaiter * iterator = DequeueWaiter(); if (iterator != NULL) { - TEVENT (Notify1 - Transfer) ; - guarantee (iterator->TState == ObjectWaiter::TS_WAIT, "invariant") ; - guarantee (iterator->_notified == 0, "invariant") ; + TEVENT(Notify1 - Transfer); + guarantee(iterator->TState == ObjectWaiter::TS_WAIT, "invariant"); + guarantee(iterator->_notified == 0, "invariant"); if (Policy != 4) { - iterator->TState = ObjectWaiter::TS_ENTER ; + iterator->TState = ObjectWaiter::TS_ENTER; } - iterator->_notified = 1 ; + iterator->_notified = 1; Thread * Self = THREAD; iterator->_notifier_tid = Self->osthread()->thread_id(); - ObjectWaiter * List = _EntryList ; + ObjectWaiter * List = _EntryList; if (List != NULL) { - assert (List->_prev == NULL, "invariant") ; - assert (List->TState == ObjectWaiter::TS_ENTER, "invariant") ; - assert (List != iterator, "invariant") ; + assert(List->_prev == NULL, "invariant"); + assert(List->TState == ObjectWaiter::TS_ENTER, "invariant"); + assert(List != iterator, "invariant"); } if (Policy == 0) { // prepend to EntryList if (List == NULL) { - iterator->_next = iterator->_prev = NULL ; - _EntryList = iterator ; + iterator->_next = iterator->_prev = NULL; + _EntryList = iterator; } else { - List->_prev = iterator ; - iterator->_next = List ; - iterator->_prev = NULL ; - _EntryList = iterator ; + List->_prev = iterator; + iterator->_next = List; + iterator->_prev = NULL; + _EntryList = iterator; } } else if (Policy == 1) { // append to EntryList if (List == NULL) { - iterator->_next = iterator->_prev = NULL ; - _EntryList = iterator ; + iterator->_next = iterator->_prev = NULL; + _EntryList = iterator; } else { // CONSIDER: finding the tail currently requires a linear-time walk of // the EntryList. We can make tail access constant-time by converting to // a CDLL instead of using our current DLL. - ObjectWaiter * Tail ; - for (Tail = List ; Tail->_next != NULL ; Tail = Tail->_next) ; - assert (Tail != NULL && Tail->_next == NULL, "invariant") ; - Tail->_next = iterator ; - iterator->_prev = Tail ; - iterator->_next = NULL ; + ObjectWaiter * Tail; + for (Tail = List; Tail->_next != NULL; Tail = Tail->_next); + assert(Tail != NULL && Tail->_next == NULL, "invariant"); + Tail->_next = iterator; + iterator->_prev = Tail; + iterator->_next = NULL; } } else if (Policy == 2) { // prepend to cxq // prepend to cxq if (List == NULL) { - iterator->_next = iterator->_prev = NULL ; - _EntryList = iterator ; + iterator->_next = iterator->_prev = NULL; + _EntryList = iterator; } else { - iterator->TState = ObjectWaiter::TS_CXQ ; + iterator->TState = ObjectWaiter::TS_CXQ; for (;;) { - ObjectWaiter * Front = _cxq ; - iterator->_next = Front ; + ObjectWaiter * Front = _cxq; + iterator->_next = Front; if (Atomic::cmpxchg_ptr (iterator, &_cxq, Front) == Front) { - break ; + break; } } } } else if (Policy == 3) { // append to cxq - iterator->TState = ObjectWaiter::TS_CXQ ; + iterator->TState = ObjectWaiter::TS_CXQ; for (;;) { - ObjectWaiter * Tail ; - Tail = _cxq ; + ObjectWaiter * Tail; + Tail = _cxq; if (Tail == NULL) { - iterator->_next = NULL ; + iterator->_next = NULL; if (Atomic::cmpxchg_ptr (iterator, &_cxq, NULL) == NULL) { - break ; + break; } } else { - while (Tail->_next != NULL) Tail = Tail->_next ; - Tail->_next = iterator ; - iterator->_prev = Tail ; - iterator->_next = NULL ; - break ; + while (Tail->_next != NULL) Tail = Tail->_next; + Tail->_next = iterator; + iterator->_prev = Tail; + iterator->_next = NULL; + break; } } } else { - ParkEvent * ev = iterator->_event ; - iterator->TState = ObjectWaiter::TS_RUN ; - OrderAccess::fence() ; - ev->unpark() ; + ParkEvent * ev = iterator->_event; + iterator->TState = ObjectWaiter::TS_RUN; + OrderAccess::fence(); + ev->unpark(); } if (Policy < 4) { @@ -1771,10 +1771,10 @@ void ObjectMonitor::notify(TRAPS) { // critical section. } - Thread::SpinRelease (&_WaitSetLock) ; + Thread::SpinRelease(&_WaitSetLock); if (iterator != NULL && ObjectMonitor::_sync_Notifications != NULL) { - ObjectMonitor::_sync_Notifications->inc() ; + ObjectMonitor::_sync_Notifications->inc(); } } @@ -1783,103 +1783,103 @@ void ObjectMonitor::notifyAll(TRAPS) { CHECK_OWNER(); ObjectWaiter* iterator; if (_WaitSet == NULL) { - TEVENT (Empty-NotifyAll) ; - return ; + TEVENT(Empty-NotifyAll); + return; } DTRACE_MONITOR_PROBE(notifyAll, this, object(), THREAD); - int Policy = Knob_MoveNotifyee ; - int Tally = 0 ; - Thread::SpinAcquire (&_WaitSetLock, "WaitSet - notifyall") ; + int Policy = Knob_MoveNotifyee; + int Tally = 0; + Thread::SpinAcquire(&_WaitSetLock, "WaitSet - notifyall"); for (;;) { - iterator = DequeueWaiter () ; - if (iterator == NULL) break ; - TEVENT (NotifyAll - Transfer1) ; - ++Tally ; + iterator = DequeueWaiter(); + if (iterator == NULL) break; + TEVENT(NotifyAll - Transfer1); + ++Tally; // Disposition - what might we do with iterator ? // a. add it directly to the EntryList - either tail or head. // b. push it onto the front of the _cxq. // For now we use (a). - guarantee (iterator->TState == ObjectWaiter::TS_WAIT, "invariant") ; - guarantee (iterator->_notified == 0, "invariant") ; - iterator->_notified = 1 ; + guarantee(iterator->TState == ObjectWaiter::TS_WAIT, "invariant"); + guarantee(iterator->_notified == 0, "invariant"); + iterator->_notified = 1; Thread * Self = THREAD; iterator->_notifier_tid = Self->osthread()->thread_id(); if (Policy != 4) { - iterator->TState = ObjectWaiter::TS_ENTER ; + iterator->TState = ObjectWaiter::TS_ENTER; } - ObjectWaiter * List = _EntryList ; + ObjectWaiter * List = _EntryList; if (List != NULL) { - assert (List->_prev == NULL, "invariant") ; - assert (List->TState == ObjectWaiter::TS_ENTER, "invariant") ; - assert (List != iterator, "invariant") ; + assert(List->_prev == NULL, "invariant"); + assert(List->TState == ObjectWaiter::TS_ENTER, "invariant"); + assert(List != iterator, "invariant"); } if (Policy == 0) { // prepend to EntryList if (List == NULL) { - iterator->_next = iterator->_prev = NULL ; - _EntryList = iterator ; + iterator->_next = iterator->_prev = NULL; + _EntryList = iterator; } else { - List->_prev = iterator ; - iterator->_next = List ; - iterator->_prev = NULL ; - _EntryList = iterator ; + List->_prev = iterator; + iterator->_next = List; + iterator->_prev = NULL; + _EntryList = iterator; } } else if (Policy == 1) { // append to EntryList if (List == NULL) { - iterator->_next = iterator->_prev = NULL ; - _EntryList = iterator ; + iterator->_next = iterator->_prev = NULL; + _EntryList = iterator; } else { // CONSIDER: finding the tail currently requires a linear-time walk of // the EntryList. We can make tail access constant-time by converting to // a CDLL instead of using our current DLL. - ObjectWaiter * Tail ; - for (Tail = List ; Tail->_next != NULL ; Tail = Tail->_next) ; - assert (Tail != NULL && Tail->_next == NULL, "invariant") ; - Tail->_next = iterator ; - iterator->_prev = Tail ; - iterator->_next = NULL ; + ObjectWaiter * Tail; + for (Tail = List; Tail->_next != NULL; Tail = Tail->_next); + assert(Tail != NULL && Tail->_next == NULL, "invariant"); + Tail->_next = iterator; + iterator->_prev = Tail; + iterator->_next = NULL; } } else if (Policy == 2) { // prepend to cxq // prepend to cxq - iterator->TState = ObjectWaiter::TS_CXQ ; + iterator->TState = ObjectWaiter::TS_CXQ; for (;;) { - ObjectWaiter * Front = _cxq ; - iterator->_next = Front ; + ObjectWaiter * Front = _cxq; + iterator->_next = Front; if (Atomic::cmpxchg_ptr (iterator, &_cxq, Front) == Front) { - break ; + break; } } } else if (Policy == 3) { // append to cxq - iterator->TState = ObjectWaiter::TS_CXQ ; + iterator->TState = ObjectWaiter::TS_CXQ; for (;;) { - ObjectWaiter * Tail ; - Tail = _cxq ; + ObjectWaiter * Tail; + Tail = _cxq; if (Tail == NULL) { - iterator->_next = NULL ; + iterator->_next = NULL; if (Atomic::cmpxchg_ptr (iterator, &_cxq, NULL) == NULL) { - break ; + break; } } else { - while (Tail->_next != NULL) Tail = Tail->_next ; - Tail->_next = iterator ; - iterator->_prev = Tail ; - iterator->_next = NULL ; - break ; + while (Tail->_next != NULL) Tail = Tail->_next; + Tail->_next = iterator; + iterator->_prev = Tail; + iterator->_next = NULL; + break; } } } else { - ParkEvent * ev = iterator->_event ; - iterator->TState = ObjectWaiter::TS_RUN ; - OrderAccess::fence() ; - ev->unpark() ; + ParkEvent * ev = iterator->_event; + iterator->TState = ObjectWaiter::TS_RUN; + OrderAccess::fence(); + ev->unpark(); } if (Policy < 4) { @@ -1895,10 +1895,10 @@ void ObjectMonitor::notifyAll(TRAPS) { // critical section. } - Thread::SpinRelease (&_WaitSetLock) ; + Thread::SpinRelease(&_WaitSetLock); if (Tally != 0 && ObjectMonitor::_sync_Notifications != NULL) { - ObjectMonitor::_sync_Notifications->inc(Tally) ; + ObjectMonitor::_sync_Notifications->inc(Tally); } } @@ -1968,8 +1968,8 @@ void ObjectMonitor::notifyAll(TRAPS) { // not spinning. // -intptr_t ObjectMonitor::SpinCallbackArgument = 0 ; -int (*ObjectMonitor::SpinCallbackFunction)(intptr_t, int) = NULL ; +intptr_t ObjectMonitor::SpinCallbackArgument = 0; +int (*ObjectMonitor::SpinCallbackFunction)(intptr_t, int) = NULL; // Spinning: Fixed frequency (100%), vary duration @@ -1977,28 +1977,28 @@ int (*ObjectMonitor::SpinCallbackFunction)(intptr_t, int) = NULL ; int ObjectMonitor::TrySpin_VaryDuration (Thread * Self) { // Dumb, brutal spin. Good for comparative measurements against adaptive spinning. - int ctr = Knob_FixedSpin ; + int ctr = Knob_FixedSpin; if (ctr != 0) { while (--ctr >= 0) { - if (TryLock (Self) > 0) return 1 ; - SpinPause () ; + if (TryLock(Self) > 0) return 1; + SpinPause(); } - return 0 ; + return 0; } - for (ctr = Knob_PreSpin + 1; --ctr >= 0 ; ) { + for (ctr = Knob_PreSpin + 1; --ctr >= 0;) { if (TryLock(Self) > 0) { // Increase _SpinDuration ... // Note that we don't clamp SpinDuration precisely at SpinLimit. // Raising _SpurDuration to the poverty line is key. - int x = _SpinDuration ; + int x = _SpinDuration; if (x < Knob_SpinLimit) { - if (x < Knob_Poverty) x = Knob_Poverty ; - _SpinDuration = x + Knob_BonusB ; + if (x < Knob_Poverty) x = Knob_Poverty; + _SpinDuration = x + Knob_BonusB; } - return 1 ; + return 1; } - SpinPause () ; + SpinPause(); } // Admission control - verify preconditions for spinning @@ -2015,37 +2015,37 @@ int ObjectMonitor::TrySpin_VaryDuration (Thread * Self) { // This takes us into the realm of 1-out-of-N spinning, where we // hold the duration constant but vary the frequency. - ctr = _SpinDuration ; - if (ctr < Knob_SpinBase) ctr = Knob_SpinBase ; - if (ctr <= 0) return 0 ; + ctr = _SpinDuration; + if (ctr < Knob_SpinBase) ctr = Knob_SpinBase; + if (ctr <= 0) return 0; - if (Knob_SuccRestrict && _succ != NULL) return 0 ; + if (Knob_SuccRestrict && _succ != NULL) return 0; if (Knob_OState && NotRunnable (Self, (Thread *) _owner)) { - TEVENT (Spin abort - notrunnable [TOP]); - return 0 ; + TEVENT(Spin abort - notrunnable [TOP]); + return 0; } - int MaxSpin = Knob_MaxSpinners ; + int MaxSpin = Knob_MaxSpinners; if (MaxSpin >= 0) { if (_Spinner > MaxSpin) { - TEVENT (Spin abort -- too many spinners) ; - return 0 ; + TEVENT(Spin abort -- too many spinners); + return 0; } // Slightly racy, but benign ... - Adjust (&_Spinner, 1) ; + Adjust(&_Spinner, 1); } // We're good to spin ... spin ingress. // CONSIDER: use Prefetch::write() to avoid RTS->RTO upgrades // when preparing to LD...CAS _owner, etc and the CAS is likely // to succeed. - int hits = 0 ; - int msk = 0 ; - int caspty = Knob_CASPenalty ; - int oxpty = Knob_OXPenalty ; - int sss = Knob_SpinSetSucc ; - if (sss && _succ == NULL ) _succ = Self ; - Thread * prv = NULL ; + int hits = 0; + int msk = 0; + int caspty = Knob_CASPenalty; + int oxpty = Knob_OXPenalty; + int sss = Knob_SpinSetSucc; + if (sss && _succ == NULL) _succ = Self; + Thread * prv = NULL; // There are three ways to exit the following loop: // 1. A successful spin where this thread has acquired the lock. @@ -2065,18 +2065,18 @@ int ObjectMonitor::TrySpin_VaryDuration (Thread * Self) { // We periodically check to see if there's a safepoint pending. if ((ctr & 0xFF) == 0) { if (SafepointSynchronize::do_call_back()) { - TEVENT (Spin: safepoint) ; - goto Abort ; // abrupt spin egress + TEVENT(Spin: safepoint); + goto Abort; // abrupt spin egress } - if (Knob_UsePause & 1) SpinPause () ; + if (Knob_UsePause & 1) SpinPause(); - int (*scb)(intptr_t,int) = SpinCallbackFunction ; + int (*scb)(intptr_t,int) = SpinCallbackFunction; if (hits > 50 && scb != NULL) { - int abend = (*scb)(SpinCallbackArgument, 0) ; + int abend = (*scb)(SpinCallbackArgument, 0); } } - if (Knob_UsePause & 2) SpinPause() ; + if (Knob_UsePause & 2) SpinPause(); // Exponential back-off ... Stay off the bus to reduce coherency traffic. // This is useful on classic SMP systems, but is of less utility on @@ -2093,12 +2093,12 @@ int ObjectMonitor::TrySpin_VaryDuration (Thread * Self) { // coherency bandwidth. Relatedly, if we _oversample _owner we // can inadvertently interfere with the the ST m->owner=null. // executed by the lock owner. - if (ctr & msk) continue ; - ++hits ; + if (ctr & msk) continue; + ++hits; if ((hits & 0xF) == 0) { // The 0xF, above, corresponds to the exponent. // Consider: (msk+1)|msk - msk = ((msk << 2)|3) & BackOffMask ; + msk = ((msk << 2)|3) & BackOffMask; } // Probe _owner with TATAS @@ -2111,16 +2111,16 @@ int ObjectMonitor::TrySpin_VaryDuration (Thread * Self) { // the spin without prejudice or apply a "penalty" to the // spin count-down variable "ctr", reducing it by 100, say. - Thread * ox = (Thread *) _owner ; + Thread * ox = (Thread *) _owner; if (ox == NULL) { - ox = (Thread *) Atomic::cmpxchg_ptr (Self, &_owner, NULL) ; + ox = (Thread *) Atomic::cmpxchg_ptr(Self, &_owner, NULL); if (ox == NULL) { // The CAS succeeded -- this thread acquired ownership // Take care of some bookkeeping to exit spin state. if (sss && _succ == Self) { - _succ = NULL ; + _succ = NULL; } - if (MaxSpin > 0) Adjust (&_Spinner, -1) ; + if (MaxSpin > 0) Adjust(&_Spinner, -1); // Increase _SpinDuration : // The spin was successful (profitable) so we tend toward @@ -2129,12 +2129,12 @@ int ObjectMonitor::TrySpin_VaryDuration (Thread * Self) { // If we acquired the lock early in the spin cycle it // makes sense to increase _SpinDuration proportionally. // Note that we don't clamp SpinDuration precisely at SpinLimit. - int x = _SpinDuration ; + int x = _SpinDuration; if (x < Knob_SpinLimit) { - if (x < Knob_Poverty) x = Knob_Poverty ; - _SpinDuration = x + Knob_Bonus ; + if (x < Knob_Poverty) x = Knob_Poverty; + _SpinDuration = x + Knob_Bonus; } - return 1 ; + return 1; } // The CAS failed ... we can take any of the following actions: @@ -2142,61 +2142,61 @@ int ObjectMonitor::TrySpin_VaryDuration (Thread * Self) { // * exit spin with prejudice -- goto Abort; // * exit spin without prejudice. // * Since CAS is high-latency, retry again immediately. - prv = ox ; - TEVENT (Spin: cas failed) ; - if (caspty == -2) break ; - if (caspty == -1) goto Abort ; - ctr -= caspty ; - continue ; + prv = ox; + TEVENT(Spin: cas failed); + if (caspty == -2) break; + if (caspty == -1) goto Abort; + ctr -= caspty; + continue; } // Did lock ownership change hands ? - if (ox != prv && prv != NULL ) { - TEVENT (spin: Owner changed) - if (oxpty == -2) break ; - if (oxpty == -1) goto Abort ; - ctr -= oxpty ; + if (ox != prv && prv != NULL) { + TEVENT(spin: Owner changed) + if (oxpty == -2) break; + if (oxpty == -1) goto Abort; + ctr -= oxpty; } - prv = ox ; + prv = ox; // Abort the spin if the owner is not executing. // The owner must be executing in order to drop the lock. // Spinning while the owner is OFFPROC is idiocy. // Consider: ctr -= RunnablePenalty ; if (Knob_OState && NotRunnable (Self, ox)) { - TEVENT (Spin abort - notrunnable); - goto Abort ; + TEVENT(Spin abort - notrunnable); + goto Abort; } - if (sss && _succ == NULL ) _succ = Self ; + if (sss && _succ == NULL) _succ = Self; } // Spin failed with prejudice -- reduce _SpinDuration. // TODO: Use an AIMD-like policy to adjust _SpinDuration. // AIMD is globally stable. - TEVENT (Spin failure) ; + TEVENT(Spin failure); { - int x = _SpinDuration ; + int x = _SpinDuration; if (x > 0) { // Consider an AIMD scheme like: x -= (x >> 3) + 100 // This is globally sample and tends to damp the response. - x -= Knob_Penalty ; - if (x < 0) x = 0 ; - _SpinDuration = x ; + x -= Knob_Penalty; + if (x < 0) x = 0; + _SpinDuration = x; } } Abort: - if (MaxSpin >= 0) Adjust (&_Spinner, -1) ; + if (MaxSpin >= 0) Adjust(&_Spinner, -1); if (sss && _succ == Self) { - _succ = NULL ; + _succ = NULL; // Invariant: after setting succ=null a contending thread // must recheck-retry _owner before parking. This usually happens // in the normal usage of TrySpin(), but it's safest // to make TrySpin() as foolproof as possible. - OrderAccess::fence() ; - if (TryLock(Self) > 0) return 1 ; + OrderAccess::fence(); + if (TryLock(Self) > 0) return 1; } - return 0 ; + return 0; } // NotRunnable() -- informed spinning @@ -2240,9 +2240,9 @@ int ObjectMonitor::TrySpin_VaryDuration (Thread * Self) { int ObjectMonitor::NotRunnable (Thread * Self, Thread * ox) { // Check either OwnerIsThread or ox->TypeTag == 2BAD. - if (!OwnerIsThread) return 0 ; + if (!OwnerIsThread) return 0; - if (ox == NULL) return 0 ; + if (ox == NULL) return 0; // Avoid transitive spinning ... // Say T1 spins or blocks trying to acquire L. T1._Stalled is set to L. @@ -2251,17 +2251,17 @@ int ObjectMonitor::NotRunnable (Thread * Self, Thread * ox) { // This occurs transiently after T1 acquired L but before // T1 managed to clear T1.Stalled. T2 does not need to abort // its spin in this circumstance. - intptr_t BlockedOn = SafeFetchN ((intptr_t *) &ox->_Stalled, intptr_t(1)) ; + intptr_t BlockedOn = SafeFetchN((intptr_t *) &ox->_Stalled, intptr_t(1)); - if (BlockedOn == 1) return 1 ; + if (BlockedOn == 1) return 1; if (BlockedOn != 0) { - return BlockedOn != intptr_t(this) && _owner == ox ; + return BlockedOn != intptr_t(this) && _owner == ox; } - assert (sizeof(((JavaThread *)ox)->_thread_state == sizeof(int)), "invariant") ; - int jst = SafeFetch32 ((int *) &((JavaThread *) ox)->_thread_state, -1) ; ; + assert(sizeof(((JavaThread *)ox)->_thread_state == sizeof(int)), "invariant"); + int jst = SafeFetch32((int *) &((JavaThread *) ox)->_thread_state, -1);; // consider also: jst != _thread_in_Java -- but that's overspecific. - return jst == _thread_blocked || jst == _thread_in_native ; + return jst == _thread_blocked || jst == _thread_in_native; } @@ -2272,11 +2272,11 @@ ObjectWaiter::ObjectWaiter(Thread* thread) { _next = NULL; _prev = NULL; _notified = 0; - TState = TS_RUN ; + TState = TS_RUN; _thread = thread; - _event = thread->_ParkEvent ; + _event = thread->_ParkEvent; _active = false; - assert (_event != NULL, "invariant") ; + assert(_event != NULL, "invariant"); } void ObjectWaiter::wait_reenter_begin(ObjectMonitor *mon) { @@ -2299,7 +2299,7 @@ inline void ObjectMonitor::AddWaiter(ObjectWaiter* node) { node->_prev = node; node->_next = node; } else { - ObjectWaiter* head = _WaitSet ; + ObjectWaiter* head = _WaitSet; ObjectWaiter* tail = head->_prev; assert(tail->_next == head, "invariant check"); tail->_next = node; @@ -2345,56 +2345,56 @@ inline void ObjectMonitor::DequeueSpecificWaiter(ObjectWaiter* node) { // ----------------------------------------------------------------------------- // PerfData support -PerfCounter * ObjectMonitor::_sync_ContendedLockAttempts = NULL ; -PerfCounter * ObjectMonitor::_sync_FutileWakeups = NULL ; -PerfCounter * ObjectMonitor::_sync_Parks = NULL ; -PerfCounter * ObjectMonitor::_sync_EmptyNotifications = NULL ; -PerfCounter * ObjectMonitor::_sync_Notifications = NULL ; -PerfCounter * ObjectMonitor::_sync_PrivateA = NULL ; -PerfCounter * ObjectMonitor::_sync_PrivateB = NULL ; -PerfCounter * ObjectMonitor::_sync_SlowExit = NULL ; -PerfCounter * ObjectMonitor::_sync_SlowEnter = NULL ; -PerfCounter * ObjectMonitor::_sync_SlowNotify = NULL ; -PerfCounter * ObjectMonitor::_sync_SlowNotifyAll = NULL ; -PerfCounter * ObjectMonitor::_sync_FailedSpins = NULL ; -PerfCounter * ObjectMonitor::_sync_SuccessfulSpins = NULL ; -PerfCounter * ObjectMonitor::_sync_MonInCirculation = NULL ; -PerfCounter * ObjectMonitor::_sync_MonScavenged = NULL ; -PerfCounter * ObjectMonitor::_sync_Inflations = NULL ; -PerfCounter * ObjectMonitor::_sync_Deflations = NULL ; -PerfLongVariable * ObjectMonitor::_sync_MonExtant = NULL ; +PerfCounter * ObjectMonitor::_sync_ContendedLockAttempts = NULL; +PerfCounter * ObjectMonitor::_sync_FutileWakeups = NULL; +PerfCounter * ObjectMonitor::_sync_Parks = NULL; +PerfCounter * ObjectMonitor::_sync_EmptyNotifications = NULL; +PerfCounter * ObjectMonitor::_sync_Notifications = NULL; +PerfCounter * ObjectMonitor::_sync_PrivateA = NULL; +PerfCounter * ObjectMonitor::_sync_PrivateB = NULL; +PerfCounter * ObjectMonitor::_sync_SlowExit = NULL; +PerfCounter * ObjectMonitor::_sync_SlowEnter = NULL; +PerfCounter * ObjectMonitor::_sync_SlowNotify = NULL; +PerfCounter * ObjectMonitor::_sync_SlowNotifyAll = NULL; +PerfCounter * ObjectMonitor::_sync_FailedSpins = NULL; +PerfCounter * ObjectMonitor::_sync_SuccessfulSpins = NULL; +PerfCounter * ObjectMonitor::_sync_MonInCirculation = NULL; +PerfCounter * ObjectMonitor::_sync_MonScavenged = NULL; +PerfCounter * ObjectMonitor::_sync_Inflations = NULL; +PerfCounter * ObjectMonitor::_sync_Deflations = NULL; +PerfLongVariable * ObjectMonitor::_sync_MonExtant = NULL; // One-shot global initialization for the sync subsystem. // We could also defer initialization and initialize on-demand // the first time we call inflate(). Initialization would // be protected - like so many things - by the MonitorCache_lock. -void ObjectMonitor::Initialize () { - static int InitializationCompleted = 0 ; - assert (InitializationCompleted == 0, "invariant") ; - InitializationCompleted = 1 ; +void ObjectMonitor::Initialize() { + static int InitializationCompleted = 0; + assert(InitializationCompleted == 0, "invariant"); + InitializationCompleted = 1; if (UsePerfData) { - EXCEPTION_MARK ; + EXCEPTION_MARK; #define NEWPERFCOUNTER(n) {n = PerfDataManager::create_counter(SUN_RT, #n, PerfData::U_Events,CHECK); } #define NEWPERFVARIABLE(n) {n = PerfDataManager::create_variable(SUN_RT, #n, PerfData::U_Events,CHECK); } - NEWPERFCOUNTER(_sync_Inflations) ; - NEWPERFCOUNTER(_sync_Deflations) ; - NEWPERFCOUNTER(_sync_ContendedLockAttempts) ; - NEWPERFCOUNTER(_sync_FutileWakeups) ; - NEWPERFCOUNTER(_sync_Parks) ; - NEWPERFCOUNTER(_sync_EmptyNotifications) ; - NEWPERFCOUNTER(_sync_Notifications) ; - NEWPERFCOUNTER(_sync_SlowEnter) ; - NEWPERFCOUNTER(_sync_SlowExit) ; - NEWPERFCOUNTER(_sync_SlowNotify) ; - NEWPERFCOUNTER(_sync_SlowNotifyAll) ; - NEWPERFCOUNTER(_sync_FailedSpins) ; - NEWPERFCOUNTER(_sync_SuccessfulSpins) ; - NEWPERFCOUNTER(_sync_PrivateA) ; - NEWPERFCOUNTER(_sync_PrivateB) ; - NEWPERFCOUNTER(_sync_MonInCirculation) ; - NEWPERFCOUNTER(_sync_MonScavenged) ; - NEWPERFVARIABLE(_sync_MonExtant) ; + NEWPERFCOUNTER(_sync_Inflations); + NEWPERFCOUNTER(_sync_Deflations); + NEWPERFCOUNTER(_sync_ContendedLockAttempts); + NEWPERFCOUNTER(_sync_FutileWakeups); + NEWPERFCOUNTER(_sync_Parks); + NEWPERFCOUNTER(_sync_EmptyNotifications); + NEWPERFCOUNTER(_sync_Notifications); + NEWPERFCOUNTER(_sync_SlowEnter); + NEWPERFCOUNTER(_sync_SlowExit); + NEWPERFCOUNTER(_sync_SlowNotify); + NEWPERFCOUNTER(_sync_SlowNotifyAll); + NEWPERFCOUNTER(_sync_FailedSpins); + NEWPERFCOUNTER(_sync_SuccessfulSpins); + NEWPERFCOUNTER(_sync_PrivateA); + NEWPERFCOUNTER(_sync_PrivateB); + NEWPERFCOUNTER(_sync_MonInCirculation); + NEWPERFCOUNTER(_sync_MonScavenged); + NEWPERFVARIABLE(_sync_MonExtant); #undef NEWPERFCOUNTER } } @@ -2414,33 +2414,33 @@ void ObjectMonitor::ctAsserts() { static char * kvGet (char * kvList, const char * Key) { - if (kvList == NULL) return NULL ; - size_t n = strlen (Key) ; - char * Search ; - for (Search = kvList ; *Search ; Search += strlen(Search) + 1) { + if (kvList == NULL) return NULL; + size_t n = strlen(Key); + char * Search; + for (Search = kvList; *Search; Search += strlen(Search) + 1) { if (strncmp (Search, Key, n) == 0) { - if (Search[n] == '=') return Search + n + 1 ; - if (Search[n] == 0) return (char *) "1" ; + if (Search[n] == '=') return Search + n + 1; + if (Search[n] == 0) return(char *) "1"; } } - return NULL ; + return NULL; } static int kvGetInt (char * kvList, const char * Key, int Default) { - char * v = kvGet (kvList, Key) ; - int rslt = v ? ::strtol (v, NULL, 0) : Default ; + char * v = kvGet(kvList, Key); + int rslt = v ? ::strtol(v, NULL, 0) : Default; if (Knob_ReportSettings && v != NULL) { ::printf (" SyncKnob: %s %d(%d)\n", Key, rslt, Default) ; - ::fflush (stdout) ; + ::fflush(stdout); } - return rslt ; + return rslt; } -void ObjectMonitor::DeferredInitialize () { - if (InitDone > 0) return ; +void ObjectMonitor::DeferredInitialize() { + if (InitDone > 0) return; if (Atomic::cmpxchg (-1, &InitDone, 0) != 0) { - while (InitDone != 1) ; - return ; + while (InitDone != 1); + return; } // One-shot global initialization ... @@ -2449,68 +2449,68 @@ void ObjectMonitor::DeferredInitialize () { // SyncKnobs consist of = pairs in the style // of environment variables. Start by converting ':' to NUL. - if (SyncKnobs == NULL) SyncKnobs = "" ; + if (SyncKnobs == NULL) SyncKnobs = ""; - size_t sz = strlen (SyncKnobs) ; - char * knobs = (char *) malloc (sz + 2) ; + size_t sz = strlen(SyncKnobs); + char * knobs = (char *) malloc(sz + 2); if (knobs == NULL) { - vm_exit_out_of_memory (sz + 2, OOM_MALLOC_ERROR, "Parse SyncKnobs") ; - guarantee (0, "invariant") ; + vm_exit_out_of_memory(sz + 2, OOM_MALLOC_ERROR, "Parse SyncKnobs"); + guarantee(0, "invariant"); } - strcpy (knobs, SyncKnobs) ; - knobs[sz+1] = 0 ; - for (char * p = knobs ; *p ; p++) { - if (*p == ':') *p = 0 ; + strcpy(knobs, SyncKnobs); + knobs[sz+1] = 0; + for (char * p = knobs; *p; p++) { + if (*p == ':') *p = 0; } #define SETKNOB(x) { Knob_##x = kvGetInt (knobs, #x, Knob_##x); } - SETKNOB(ReportSettings) ; - SETKNOB(Verbose) ; - SETKNOB(FixedSpin) ; - SETKNOB(SpinLimit) ; - SETKNOB(SpinBase) ; + SETKNOB(ReportSettings); + SETKNOB(Verbose); + SETKNOB(FixedSpin); + SETKNOB(SpinLimit); + SETKNOB(SpinBase); SETKNOB(SpinBackOff); - SETKNOB(CASPenalty) ; - SETKNOB(OXPenalty) ; - SETKNOB(LogSpins) ; - SETKNOB(SpinSetSucc) ; - SETKNOB(SuccEnabled) ; - SETKNOB(SuccRestrict) ; - SETKNOB(Penalty) ; - SETKNOB(Bonus) ; - SETKNOB(BonusB) ; - SETKNOB(Poverty) ; - SETKNOB(SpinAfterFutile) ; - SETKNOB(UsePause) ; - SETKNOB(SpinEarly) ; - SETKNOB(OState) ; - SETKNOB(MaxSpinners) ; - SETKNOB(PreSpin) ; - SETKNOB(ExitPolicy) ; + SETKNOB(CASPenalty); + SETKNOB(OXPenalty); + SETKNOB(LogSpins); + SETKNOB(SpinSetSucc); + SETKNOB(SuccEnabled); + SETKNOB(SuccRestrict); + SETKNOB(Penalty); + SETKNOB(Bonus); + SETKNOB(BonusB); + SETKNOB(Poverty); + SETKNOB(SpinAfterFutile); + SETKNOB(UsePause); + SETKNOB(SpinEarly); + SETKNOB(OState); + SETKNOB(MaxSpinners); + SETKNOB(PreSpin); + SETKNOB(ExitPolicy); SETKNOB(QMode); - SETKNOB(ResetEvent) ; - SETKNOB(MoveNotifyee) ; - SETKNOB(FastHSSEC) ; + SETKNOB(ResetEvent); + SETKNOB(MoveNotifyee); + SETKNOB(FastHSSEC); #undef SETKNOB if (os::is_MP()) { - BackOffMask = (1 << Knob_SpinBackOff) - 1 ; - if (Knob_ReportSettings) ::printf ("BackOffMask=%X\n", BackOffMask) ; + BackOffMask = (1 << Knob_SpinBackOff) - 1; + if (Knob_ReportSettings) ::printf("BackOffMask=%X\n", BackOffMask); // CONSIDER: BackOffMask = ROUNDUP_NEXT_POWER2 (ncpus-1) } else { - Knob_SpinLimit = 0 ; - Knob_SpinBase = 0 ; - Knob_PreSpin = 0 ; - Knob_FixedSpin = -1 ; + Knob_SpinLimit = 0; + Knob_SpinBase = 0; + Knob_PreSpin = 0; + Knob_FixedSpin = -1; } if (Knob_LogSpins == 0) { - ObjectMonitor::_sync_FailedSpins = NULL ; + ObjectMonitor::_sync_FailedSpins = NULL; } - free (knobs) ; - OrderAccess::fence() ; - InitDone = 1 ; + free(knobs); + OrderAccess::fence(); + InitDone = 1; } #ifndef PRODUCT diff --git a/hotspot/src/share/vm/runtime/objectMonitor.hpp b/hotspot/src/share/vm/runtime/objectMonitor.hpp index 5a2756826cb..9feaf7b8a90 100644 --- a/hotspot/src/share/vm/runtime/objectMonitor.hpp +++ b/hotspot/src/share/vm/runtime/objectMonitor.hpp @@ -37,17 +37,17 @@ class ObjectWaiter : public StackObj { public: - enum TStates { TS_UNDEF, TS_READY, TS_RUN, TS_WAIT, TS_ENTER, TS_CXQ } ; - enum Sorted { PREPEND, APPEND, SORTED } ; + enum TStates { TS_UNDEF, TS_READY, TS_RUN, TS_WAIT, TS_ENTER, TS_CXQ }; + enum Sorted { PREPEND, APPEND, SORTED }; ObjectWaiter * volatile _next; ObjectWaiter * volatile _prev; Thread* _thread; jlong _notifier_tid; ParkEvent * _event; - volatile int _notified ; - volatile TStates TState ; - Sorted _Sorted ; // List placement disposition - bool _active ; // Contention monitoring is enabled + volatile int _notified; + volatile TStates TState; + Sorted _Sorted; // List placement disposition + bool _active; // Contention monitoring is enabled public: ObjectWaiter(Thread* thread); @@ -92,19 +92,19 @@ class ObjectMonitor { static int owner_offset_in_bytes() { return offset_of(ObjectMonitor, _owner); } static int count_offset_in_bytes() { return offset_of(ObjectMonitor, _count); } static int recursions_offset_in_bytes() { return offset_of(ObjectMonitor, _recursions); } - static int cxq_offset_in_bytes() { return offset_of(ObjectMonitor, _cxq) ; } - static int succ_offset_in_bytes() { return offset_of(ObjectMonitor, _succ) ; } + static int cxq_offset_in_bytes() { return offset_of(ObjectMonitor, _cxq); } + static int succ_offset_in_bytes() { return offset_of(ObjectMonitor, _succ); } static int EntryList_offset_in_bytes() { return offset_of(ObjectMonitor, _EntryList); } static int FreeNext_offset_in_bytes() { return offset_of(ObjectMonitor, FreeNext); } - static int WaitSet_offset_in_bytes() { return offset_of(ObjectMonitor, _WaitSet) ; } - static int Responsible_offset_in_bytes() { return offset_of(ObjectMonitor, _Responsible);} + static int WaitSet_offset_in_bytes() { return offset_of(ObjectMonitor, _WaitSet); } + static int Responsible_offset_in_bytes() { return offset_of(ObjectMonitor, _Responsible); } static int Spinner_offset_in_bytes() { return offset_of(ObjectMonitor, _Spinner); } public: // Eventually we'll make provisions for multiple callbacks, but // now one will suffice. - static int (*SpinCallbackFunction)(intptr_t, int) ; - static intptr_t SpinCallbackArgument ; + static int (*SpinCallbackFunction)(intptr_t, int); + static intptr_t SpinCallbackArgument; public: @@ -115,7 +115,7 @@ class ObjectMonitor { // TODO-FIXME: merge _count and _waiters. // TODO-FIXME: assert _owner == null implies _recursions = 0 // TODO-FIXME: assert _WaitSet != null implies _count > 0 - return _count|_waiters|intptr_t(_owner)|intptr_t(_cxq)|intptr_t(_EntryList ) ; + return _count|_waiters|intptr_t(_owner)|intptr_t(_cxq)|intptr_t(_EntryList); } intptr_t is_entered(Thread* current) const; @@ -127,7 +127,7 @@ class ObjectMonitor { intptr_t count() const; void set_count(intptr_t count); - intptr_t contentions() const ; + intptr_t contentions() const; intptr_t recursions() const { return _recursions; } // JVM/DI GetMonitorInfo() needs this @@ -145,15 +145,15 @@ class ObjectMonitor { _object = NULL; _owner = NULL; _WaitSet = NULL; - _WaitSetLock = 0 ; - _Responsible = NULL ; - _succ = NULL ; - _cxq = NULL ; - FreeNext = NULL ; - _EntryList = NULL ; - _SpinFreq = 0 ; - _SpinClock = 0 ; - OwnerIsThread = 0 ; + _WaitSetLock = 0; + _Responsible = NULL; + _succ = NULL; + _cxq = NULL; + FreeNext = NULL; + _EntryList = NULL; + _SpinFreq = 0; + _SpinClock = 0; + OwnerIsThread = 0; _previous_owner_tid = 0; } @@ -164,20 +164,20 @@ class ObjectMonitor { } private: - void Recycle () { + void Recycle() { // TODO: add stronger asserts ... // _cxq == 0 _succ == NULL _owner == NULL _waiters == 0 // _count == 0 EntryList == NULL // _recursions == 0 _WaitSet == NULL // TODO: assert (is_busy()|_recursions) == 0 - _succ = NULL ; - _EntryList = NULL ; - _cxq = NULL ; - _WaitSet = NULL ; - _recursions = 0 ; - _SpinFreq = 0 ; - _SpinClock = 0 ; - OwnerIsThread = 0 ; + _succ = NULL; + _EntryList = NULL; + _cxq = NULL; + _WaitSet = NULL; + _recursions = 0; + _SpinFreq = 0; + _SpinClock = 0; + OwnerIsThread = 0; } public: @@ -194,7 +194,7 @@ public: void print(); #endif - bool try_enter (TRAPS) ; + bool try_enter(TRAPS); void enter(TRAPS); void exit(bool not_suspended, TRAPS); void wait(jlong millis, bool interruptable, TRAPS); @@ -206,22 +206,22 @@ public: void reenter(intptr_t recursions, TRAPS); private: - void AddWaiter (ObjectWaiter * waiter) ; + void AddWaiter(ObjectWaiter * waiter); static void DeferredInitialize(); - ObjectWaiter * DequeueWaiter () ; - void DequeueSpecificWaiter (ObjectWaiter * waiter) ; - void EnterI (TRAPS) ; - void ReenterI (Thread * Self, ObjectWaiter * SelfNode) ; - void UnlinkAfterAcquire (Thread * Self, ObjectWaiter * SelfNode) ; - int TryLock (Thread * Self) ; - int NotRunnable (Thread * Self, Thread * Owner) ; - int TrySpin_Fixed (Thread * Self) ; - int TrySpin_VaryFrequency (Thread * Self) ; - int TrySpin_VaryDuration (Thread * Self) ; - void ctAsserts () ; - void ExitEpilog (Thread * Self, ObjectWaiter * Wakee) ; - bool ExitSuspendEquivalent (JavaThread * Self) ; + ObjectWaiter * DequeueWaiter(); + void DequeueSpecificWaiter(ObjectWaiter * waiter); + void EnterI(TRAPS); + void ReenterI(Thread * Self, ObjectWaiter * SelfNode); + void UnlinkAfterAcquire(Thread * Self, ObjectWaiter * SelfNode); + int TryLock(Thread * Self); + int NotRunnable(Thread * Self, Thread * Owner); + int TrySpin_Fixed(Thread * Self); + int TrySpin_VaryFrequency(Thread * Self); + int TrySpin_VaryDuration(Thread * Self); + void ctAsserts(); + void ExitEpilog(Thread * Self, ObjectWaiter * Wakee); + bool ExitSuspendEquivalent(JavaThread * Self); void post_monitor_wait_event(EventJavaMonitorWait * event, jlong notifier_tid, jlong timeout, @@ -240,7 +240,7 @@ public: volatile markOop _header; // displaced object header word - mark void* volatile _object; // backward object pointer - strong root - double SharingPad [1] ; // temp to reduce false sharing + double SharingPad[1]; // temp to reduce false sharing // All the following fields must be machine word aligned // The VM assumes write ordering wrt these fields, which can be @@ -251,22 +251,22 @@ public: volatile jlong _previous_owner_tid; // thread id of the previous owner of the monitor volatile intptr_t _recursions; // recursion count, 0 for first entry private: - int OwnerIsThread ; // _owner is (Thread *) vs SP/BasicLock - ObjectWaiter * volatile _cxq ; // LL of recently-arrived threads blocked on entry. + int OwnerIsThread; // _owner is (Thread *) vs SP/BasicLock + ObjectWaiter * volatile _cxq; // LL of recently-arrived threads blocked on entry. // The list is actually composed of WaitNodes, acting // as proxies for Threads. protected: - ObjectWaiter * volatile _EntryList ; // Threads blocked on entry or reentry. + ObjectWaiter * volatile _EntryList; // Threads blocked on entry or reentry. private: - Thread * volatile _succ ; // Heir presumptive thread - used for futile wakeup throttling - Thread * volatile _Responsible ; - int _PromptDrain ; // rqst to drain cxq into EntryList ASAP + Thread * volatile _succ; // Heir presumptive thread - used for futile wakeup throttling + Thread * volatile _Responsible; + int _PromptDrain; // rqst to drain cxq into EntryList ASAP - volatile int _Spinner ; // for exit->spinner handoff optimization - volatile int _SpinFreq ; // Spin 1-out-of-N attempts: success rate - volatile int _SpinClock ; - volatile int _SpinDuration ; - volatile intptr_t _SpinState ; // MCS/CLH list of spinners + volatile int _Spinner; // for exit->spinner handoff optimization + volatile int _SpinFreq; // Spin 1-out-of-N attempts: success rate + volatile int _SpinClock; + volatile int _SpinDuration; + volatile intptr_t _SpinState; // MCS/CLH list of spinners // TODO-FIXME: _count, _waiters and _recursions should be of // type int, or int32_t but not intptr_t. There's no reason @@ -284,30 +284,30 @@ public: volatile int _WaitSetLock; // protects Wait Queue - simple spinlock public: - int _QMix ; // Mixed prepend queue discipline - ObjectMonitor * FreeNext ; // Free list linkage - intptr_t StatA, StatsB ; + int _QMix; // Mixed prepend queue discipline + ObjectMonitor * FreeNext; // Free list linkage + intptr_t StatA, StatsB; public: - static void Initialize () ; - static PerfCounter * _sync_ContendedLockAttempts ; - static PerfCounter * _sync_FutileWakeups ; - static PerfCounter * _sync_Parks ; - static PerfCounter * _sync_EmptyNotifications ; - static PerfCounter * _sync_Notifications ; - static PerfCounter * _sync_SlowEnter ; - static PerfCounter * _sync_SlowExit ; - static PerfCounter * _sync_SlowNotify ; - static PerfCounter * _sync_SlowNotifyAll ; - static PerfCounter * _sync_FailedSpins ; - static PerfCounter * _sync_SuccessfulSpins ; - static PerfCounter * _sync_PrivateA ; - static PerfCounter * _sync_PrivateB ; - static PerfCounter * _sync_MonInCirculation ; - static PerfCounter * _sync_MonScavenged ; - static PerfCounter * _sync_Inflations ; - static PerfCounter * _sync_Deflations ; - static PerfLongVariable * _sync_MonExtant ; + static void Initialize(); + static PerfCounter * _sync_ContendedLockAttempts; + static PerfCounter * _sync_FutileWakeups; + static PerfCounter * _sync_Parks; + static PerfCounter * _sync_EmptyNotifications; + static PerfCounter * _sync_Notifications; + static PerfCounter * _sync_SlowEnter; + static PerfCounter * _sync_SlowExit; + static PerfCounter * _sync_SlowNotify; + static PerfCounter * _sync_SlowNotifyAll; + static PerfCounter * _sync_FailedSpins; + static PerfCounter * _sync_SuccessfulSpins; + static PerfCounter * _sync_PrivateA; + static PerfCounter * _sync_PrivateB; + static PerfCounter * _sync_MonInCirculation; + static PerfCounter * _sync_MonScavenged; + static PerfCounter * _sync_Inflations; + static PerfCounter * _sync_Deflations; + static PerfLongVariable * _sync_MonExtant; public: static int Knob_Verbose; @@ -329,7 +329,7 @@ public: #undef TEVENT #define TEVENT(nom) {if (SyncVerbose) FEVENT(nom); } -#define FEVENT(nom) { static volatile int ctr = 0 ; int v = ++ctr ; if ((v & (v-1)) == 0) { ::printf (#nom " : %d \n", v); ::fflush(stdout); }} +#define FEVENT(nom) { static volatile int ctr = 0; int v = ++ctr; if ((v & (v-1)) == 0) { ::printf (#nom " : %d \n", v); ::fflush(stdout); }} #undef TEVENT #define TEVENT(nom) {;} diff --git a/hotspot/src/share/vm/runtime/os.cpp b/hotspot/src/share/vm/runtime/os.cpp index 04c008431c7..dc5d664989b 100644 --- a/hotspot/src/share/vm/runtime/os.cpp +++ b/hotspot/src/share/vm/runtime/os.cpp @@ -32,6 +32,9 @@ #include "gc_implementation/shared/vmGCOperations.hpp" #include "interpreter/interpreter.hpp" #include "memory/allocation.inline.hpp" +#ifdef ASSERT +#include "memory/guardedMemory.hpp" +#endif #include "oops/oop.inline.hpp" #include "prims/jvm.h" #include "prims/jvm_misc.hpp" @@ -523,121 +526,20 @@ char *os::strdup(const char *str, MEMFLAGS flags) { } - -#ifdef ASSERT -#define space_before (MallocCushion + sizeof(double)) -#define space_after MallocCushion -#define size_addr_from_base(p) (size_t*)(p + space_before - sizeof(size_t)) -#define size_addr_from_obj(p) ((size_t*)p - 1) -// MallocCushion: size of extra cushion allocated around objects with +UseMallocOnly -// NB: cannot be debug variable, because these aren't set from the command line until -// *after* the first few allocs already happened -#define MallocCushion 16 -#else -#define space_before 0 -#define space_after 0 -#define size_addr_from_base(p) should not use w/o ASSERT -#define size_addr_from_obj(p) should not use w/o ASSERT -#define MallocCushion 0 -#endif #define paranoid 0 /* only set to 1 if you suspect checking code has bug */ #ifdef ASSERT -inline size_t get_size(void* obj) { - size_t size = *size_addr_from_obj(obj); - if (size < 0) { - fatal(err_msg("free: size field of object #" PTR_FORMAT " was overwritten (" - SIZE_FORMAT ")", obj, size)); - } - return size; -} -u_char* find_cushion_backwards(u_char* start) { - u_char* p = start; - while (p[ 0] != badResourceValue || p[-1] != badResourceValue || - p[-2] != badResourceValue || p[-3] != badResourceValue) p--; - // ok, we have four consecutive marker bytes; find start - u_char* q = p - 4; - while (*q == badResourceValue) q--; - return q + 1; -} - -u_char* find_cushion_forwards(u_char* start) { - u_char* p = start; - while (p[0] != badResourceValue || p[1] != badResourceValue || - p[2] != badResourceValue || p[3] != badResourceValue) p++; - // ok, we have four consecutive marker bytes; find end of cushion - u_char* q = p + 4; - while (*q == badResourceValue) q++; - return q - MallocCushion; -} - -void print_neighbor_blocks(void* ptr) { - // find block allocated before ptr (not entirely crash-proof) - if (MallocCushion < 4) { - tty->print_cr("### cannot find previous block (MallocCushion < 4)"); - return; - } - u_char* start_of_this_block = (u_char*)ptr - space_before; - u_char* end_of_prev_block_data = start_of_this_block - space_after -1; - // look for cushion in front of prev. block - u_char* start_of_prev_block = find_cushion_backwards(end_of_prev_block_data); - ptrdiff_t size = *size_addr_from_base(start_of_prev_block); - u_char* obj = start_of_prev_block + space_before; - if (size <= 0 ) { - // start is bad; may have been confused by OS data in between objects - // search one more backwards - start_of_prev_block = find_cushion_backwards(start_of_prev_block); - size = *size_addr_from_base(start_of_prev_block); - obj = start_of_prev_block + space_before; - } - - if (start_of_prev_block + space_before + size + space_after == start_of_this_block) { - tty->print_cr("### previous object: " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", obj, size); - } else { - tty->print_cr("### previous object (not sure if correct): " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", obj, size); - } - - // now find successor block - u_char* start_of_next_block = (u_char*)ptr + *size_addr_from_obj(ptr) + space_after; - start_of_next_block = find_cushion_forwards(start_of_next_block); - u_char* next_obj = start_of_next_block + space_before; - ptrdiff_t next_size = *size_addr_from_base(start_of_next_block); - if (start_of_next_block[0] == badResourceValue && - start_of_next_block[1] == badResourceValue && - start_of_next_block[2] == badResourceValue && - start_of_next_block[3] == badResourceValue) { - tty->print_cr("### next object: " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", next_obj, next_size); - } else { - tty->print_cr("### next object (not sure if correct): " PTR_FORMAT " (" SSIZE_FORMAT " bytes)", next_obj, next_size); +static void verify_memory(void* ptr) { + GuardedMemory guarded(ptr); + if (!guarded.verify_guards()) { + tty->print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees); + tty->print_cr("## memory stomp:"); + guarded.print_on(tty); + fatal("memory stomping error"); } } - -void report_heap_error(void* memblock, void* bad, const char* where) { - tty->print_cr("## nof_mallocs = " UINT64_FORMAT ", nof_frees = " UINT64_FORMAT, os::num_mallocs, os::num_frees); - tty->print_cr("## memory stomp: byte at " PTR_FORMAT " %s object " PTR_FORMAT, bad, where, memblock); - print_neighbor_blocks(memblock); - fatal("memory stomping error"); -} - -void verify_block(void* memblock) { - size_t size = get_size(memblock); - if (MallocCushion) { - u_char* ptr = (u_char*)memblock - space_before; - for (int i = 0; i < MallocCushion; i++) { - if (ptr[i] != badResourceValue) { - report_heap_error(memblock, ptr+i, "in front of"); - } - } - u_char* end = (u_char*)memblock + size + space_after; - for (int j = -MallocCushion; j < 0; j++) { - if (end[j] != badResourceValue) { - report_heap_error(memblock, end+j, "after"); - } - } - } -} #endif // @@ -686,16 +588,18 @@ void* os::malloc(size_t size, MEMFLAGS memflags, address caller) { size = 1; } - const size_t alloc_size = size + space_before + space_after; - +#ifndef ASSERT + const size_t alloc_size = size; +#else + const size_t alloc_size = GuardedMemory::get_total_size(size); if (size > alloc_size) { // Check for rollover. return NULL; } +#endif NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap()); u_char* ptr; - if (MallocMaxTestWords > 0) { ptr = testMalloc(alloc_size); } else { @@ -703,28 +607,26 @@ void* os::malloc(size_t size, MEMFLAGS memflags, address caller) { } #ifdef ASSERT - if (ptr == NULL) return NULL; - if (MallocCushion) { - for (u_char* p = ptr; p < ptr + MallocCushion; p++) *p = (u_char)badResourceValue; - u_char* end = ptr + space_before + size; - for (u_char* pq = ptr+MallocCushion; pq < end; pq++) *pq = (u_char)uninitBlockPad; - for (u_char* q = end; q < end + MallocCushion; q++) *q = (u_char)badResourceValue; + if (ptr == NULL) { + return NULL; } - // put size just before data - *size_addr_from_base(ptr) = size; + // Wrap memory with guard + GuardedMemory guarded(ptr, size); + ptr = guarded.get_user_ptr(); #endif - u_char* memblock = ptr + space_before; - if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) { - tty->print_cr("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, memblock); + if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) { + tty->print_cr("os::malloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr); breakpoint(); } - debug_only(if (paranoid) verify_block(memblock)); - if (PrintMalloc && tty != NULL) tty->print_cr("os::malloc " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, memblock); + debug_only(if (paranoid) verify_memory(ptr)); + if (PrintMalloc && tty != NULL) { + tty->print_cr("os::malloc " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr); + } - // we do not track MallocCushion memory - MemTracker::record_malloc((address)memblock, size, memflags, caller == 0 ? CALLER_PC : caller); + // we do not track guard memory + MemTracker::record_malloc((address)ptr, size, memflags, caller == 0 ? CALLER_PC : caller); - return memblock; + return ptr; } @@ -743,27 +645,32 @@ void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, address caller return ptr; #else if (memblock == NULL) { - return malloc(size, memflags, (caller == 0 ? CALLER_PC : caller)); + return os::malloc(size, memflags, (caller == 0 ? CALLER_PC : caller)); } if ((intptr_t)memblock == (intptr_t)MallocCatchPtr) { tty->print_cr("os::realloc caught " PTR_FORMAT, memblock); breakpoint(); } - verify_block(memblock); + verify_memory(memblock); NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap()); - if (size == 0) return NULL; + if (size == 0) { + return NULL; + } // always move the block - void* ptr = malloc(size, memflags, caller == 0 ? CALLER_PC : caller); - if (PrintMalloc) tty->print_cr("os::remalloc " SIZE_FORMAT " bytes, " PTR_FORMAT " --> " PTR_FORMAT, size, memblock, ptr); + void* ptr = os::malloc(size, memflags, caller == 0 ? CALLER_PC : caller); + if (PrintMalloc) { + tty->print_cr("os::remalloc " SIZE_FORMAT " bytes, " PTR_FORMAT " --> " PTR_FORMAT, size, memblock, ptr); + } // Copy to new memory if malloc didn't fail if ( ptr != NULL ) { - memcpy(ptr, memblock, MIN2(size, get_size(memblock))); - if (paranoid) verify_block(ptr); + GuardedMemory guarded(memblock); + memcpy(ptr, memblock, MIN2(size, guarded.get_user_size())); + if (paranoid) verify_memory(ptr); if ((intptr_t)ptr == (intptr_t)MallocCatchPtr) { tty->print_cr("os::realloc caught, " SIZE_FORMAT " bytes --> " PTR_FORMAT, size, ptr); breakpoint(); } - free(memblock); + os::free(memblock); } return ptr; #endif @@ -771,6 +678,7 @@ void* os::realloc(void *memblock, size_t size, MEMFLAGS memflags, address caller void os::free(void *memblock, MEMFLAGS memflags) { + address trackp = (address) memblock; NOT_PRODUCT(inc_stat_counter(&num_frees, 1)); #ifdef ASSERT if (memblock == NULL) return; @@ -778,34 +686,20 @@ void os::free(void *memblock, MEMFLAGS memflags) { if (tty != NULL) tty->print_cr("os::free caught " PTR_FORMAT, memblock); breakpoint(); } - verify_block(memblock); + verify_memory(memblock); NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap()); - // Added by detlefs. - if (MallocCushion) { - u_char* ptr = (u_char*)memblock - space_before; - for (u_char* p = ptr; p < ptr + MallocCushion; p++) { - guarantee(*p == badResourceValue, - "Thing freed should be malloc result."); - *p = (u_char)freeBlockPad; - } - size_t size = get_size(memblock); - inc_stat_counter(&free_bytes, size); - u_char* end = ptr + space_before + size; - for (u_char* q = end; q < end + MallocCushion; q++) { - guarantee(*q == badResourceValue, - "Thing freed should be malloc result."); - *q = (u_char)freeBlockPad; - } - if (PrintMalloc && tty != NULL) + + GuardedMemory guarded(memblock); + size_t size = guarded.get_user_size(); + inc_stat_counter(&free_bytes, size); + memblock = guarded.release_for_freeing(); + if (PrintMalloc && tty != NULL) { fprintf(stderr, "os::free " SIZE_FORMAT " bytes --> " PTR_FORMAT "\n", size, (uintptr_t)memblock); - } else if (PrintMalloc && tty != NULL) { - // tty->print_cr("os::free %p", memblock); - fprintf(stderr, "os::free " PTR_FORMAT "\n", (uintptr_t)memblock); } #endif - MemTracker::record_free((address)memblock, memflags); + MemTracker::record_free(trackp, memflags); - ::free((char*)memblock - space_before); + ::free(memblock); } void os::init_random(long initval) { diff --git a/hotspot/src/share/vm/runtime/reflection.cpp b/hotspot/src/share/vm/runtime/reflection.cpp index 872d73c72e8..cc35fea494b 100644 --- a/hotspot/src/share/vm/runtime/reflection.cpp +++ b/hotspot/src/share/vm/runtime/reflection.cpp @@ -410,49 +410,6 @@ oop Reflection::array_component_type(oop mirror, TRAPS) { } -bool Reflection::reflect_check_access(Klass* field_class, AccessFlags acc, Klass* target_class, bool is_method_invoke, TRAPS) { - // field_class : declaring class - // acc : declared field access - // target_class : for protected - - // Check if field or method is accessible to client. Throw an - // IllegalAccessException and return false if not. - - // The "client" is the class associated with the nearest real frame - // getCallerClass already skips Method.invoke frames, so pass 0 in - // that case (same as classic). - ResourceMark rm(THREAD); - assert(THREAD->is_Java_thread(), "sanity check"); - Klass* client_class = ((JavaThread *)THREAD)->security_get_caller_class(is_method_invoke ? 0 : 1); - - if (client_class != field_class) { - if (!verify_class_access(client_class, field_class, false) - || !verify_field_access(client_class, - field_class, - field_class, - acc, - false)) { - THROW_(vmSymbols::java_lang_IllegalAccessException(), false); - } - } - - // Additional test for protected members: JLS 6.6.2 - - if (acc.is_protected()) { - if (target_class != client_class) { - if (!is_same_class_package(client_class, field_class)) { - if (!target_class->is_subclass_of(client_class)) { - THROW_(vmSymbols::java_lang_IllegalAccessException(), false); - } - } - } - } - - // Passed all tests - return true; -} - - bool Reflection::verify_class_access(Klass* current_class, Klass* new_class, bool classloader_only) { // Verify that current_class can access new_class. If the classloader_only // flag is set, we automatically allow any accesses in which current_class @@ -463,10 +420,9 @@ bool Reflection::verify_class_access(Klass* current_class, Klass* new_class, boo is_same_class_package(current_class, new_class)) { return true; } - // New (1.4) reflection implementation. Allow all accesses from - // sun/reflect/MagicAccessorImpl subclasses to succeed trivially. - if ( JDK_Version::is_gte_jdk14x_version() - && current_class->is_subclass_of(SystemDictionary::reflect_MagicAccessorImpl_klass())) { + // Allow all accesses from sun/reflect/MagicAccessorImpl subclasses to + // succeed trivially. + if (current_class->is_subclass_of(SystemDictionary::reflect_MagicAccessorImpl_klass())) { return true; } @@ -567,10 +523,9 @@ bool Reflection::verify_field_access(Klass* current_class, return true; } - // New (1.4) reflection implementation. Allow all accesses from - // sun/reflect/MagicAccessorImpl subclasses to succeed trivially. - if ( JDK_Version::is_gte_jdk14x_version() - && current_class->is_subclass_of(SystemDictionary::reflect_MagicAccessorImpl_klass())) { + // Allow all accesses from sun/reflect/MagicAccessorImpl subclasses to + // succeed trivially. + if (current_class->is_subclass_of(SystemDictionary::reflect_MagicAccessorImpl_klass())) { return true; } @@ -707,12 +662,10 @@ Handle Reflection::new_type(Symbol* signature, KlassHandle k, TRAPS) { oop Reflection::new_method(methodHandle method, bool for_constant_pool_access, TRAPS) { - // In jdk1.2.x, getMethods on an interface erroneously includes , thus the complicated assert. - // Also allow sun.reflect.ConstantPool to refer to methods as java.lang.reflect.Methods. + // Allow sun.reflect.ConstantPool to refer to methods as java.lang.reflect.Methods. assert(!method()->is_initializer() || - (for_constant_pool_access && method()->is_static()) || - (method()->name() == vmSymbols::class_initializer_name() - && method()->method_holder()->is_interface() && JDK_Version::is_jdk12x_version()), "should call new_constructor instead"); + (for_constant_pool_access && method()->is_static()), + "should call new_constructor instead"); instanceKlassHandle holder (THREAD, method->method_holder()); int slot = method->method_idnum(); @@ -978,22 +931,6 @@ oop Reflection::invoke(instanceKlassHandle klass, methodHandle reflected_method, reflected_method->signature())); } - // In the JDK 1.4 reflection implementation, the security check is - // done at the Java level - if (!JDK_Version::is_gte_jdk14x_version()) { - - // Access checking (unless overridden by Method) - if (!override) { - if (!(klass->is_public() && reflected_method->is_public())) { - bool access = Reflection::reflect_check_access(klass(), reflected_method->access_flags(), target_klass(), is_method_invoke, CHECK_NULL); - if (!access) { - return NULL; // exception - } - } - } - - } // !Universe::is_gte_jdk14x_version() - assert(ptypes->is_objArray(), "just checking"); int args_len = args.is_null() ? 0 : args->length(); // Check number of arguments diff --git a/hotspot/src/share/vm/runtime/reflection.hpp b/hotspot/src/share/vm/runtime/reflection.hpp index 5757cfc39f5..593ff7ecc49 100644 --- a/hotspot/src/share/vm/runtime/reflection.hpp +++ b/hotspot/src/share/vm/runtime/reflection.hpp @@ -44,9 +44,6 @@ class FieldStream; class Reflection: public AllStatic { private: - // Access checking - static bool reflect_check_access(Klass* field_class, AccessFlags acc, Klass* target_class, bool is_method_invoke, TRAPS); - // Conversion static Klass* basic_type_mirror_to_arrayklass(oop basic_type_mirror, TRAPS); static oop basic_type_arrayklass_to_mirror(Klass* basic_type_arrayklass, TRAPS); diff --git a/hotspot/src/share/vm/runtime/reflectionUtils.cpp b/hotspot/src/share/vm/runtime/reflectionUtils.cpp index 2ec82abc91a..331d5a750a0 100644 --- a/hotspot/src/share/vm/runtime/reflectionUtils.cpp +++ b/hotspot/src/share/vm/runtime/reflectionUtils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -76,15 +76,10 @@ void FilteredFieldsMap::initialize() { int offset; offset = java_lang_Throwable::get_backtrace_offset(); _filtered_fields->append(new FilteredField(SystemDictionary::Throwable_klass(), offset)); - // The latest version of vm may be used with old jdk. - if (JDK_Version::is_gte_jdk16x_version()) { - // The following class fields do not exist in - // previous version of jdk. - offset = sun_reflect_ConstantPool::oop_offset(); - _filtered_fields->append(new FilteredField(SystemDictionary::reflect_ConstantPool_klass(), offset)); - offset = sun_reflect_UnsafeStaticFieldAccessorImpl::base_offset(); - _filtered_fields->append(new FilteredField(SystemDictionary::reflect_UnsafeStaticFieldAccessorImpl_klass(), offset)); - } + offset = sun_reflect_ConstantPool::oop_offset(); + _filtered_fields->append(new FilteredField(SystemDictionary::reflect_ConstantPool_klass(), offset)); + offset = sun_reflect_UnsafeStaticFieldAccessorImpl::base_offset(); + _filtered_fields->append(new FilteredField(SystemDictionary::reflect_UnsafeStaticFieldAccessorImpl_klass(), offset)); } int FilteredFieldStream::field_count() { diff --git a/hotspot/src/share/vm/runtime/serviceThread.cpp b/hotspot/src/share/vm/runtime/serviceThread.cpp index 3c1224abb2c..eb7cb4a439c 100644 --- a/hotspot/src/share/vm/runtime/serviceThread.cpp +++ b/hotspot/src/share/vm/runtime/serviceThread.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,8 +41,7 @@ void ServiceThread::initialize() { instanceKlassHandle klass (THREAD, SystemDictionary::Thread_klass()); instanceHandle thread_oop = klass->allocate_instance_handle(CHECK); - const char* name = JDK_Version::is_gte_jdk17x_version() ? - "Service Thread" : "Low Memory Detector"; + const char* name = "Service Thread"; Handle string = java_lang_String::create_from_str(name, CHECK); diff --git a/hotspot/src/share/vm/runtime/sharedRuntime.cpp b/hotspot/src/share/vm/runtime/sharedRuntime.cpp index fad31fd02f1..efd8be473b3 100644 --- a/hotspot/src/share/vm/runtime/sharedRuntime.cpp +++ b/hotspot/src/share/vm/runtime/sharedRuntime.cpp @@ -198,13 +198,13 @@ void SharedRuntime::trace_ic_miss(address at) { void SharedRuntime::print_ic_miss_histogram() { if (ICMissHistogram) { - tty->print_cr ("IC Miss Histogram:"); + tty->print_cr("IC Miss Histogram:"); int tot_misses = 0; for (int i = 0; i < _ICmiss_index; i++) { tty->print_cr(" at: " INTPTR_FORMAT " nof: %d", _ICmiss_at[i], _ICmiss_count[i]); tot_misses += _ICmiss_count[i]; } - tty->print_cr ("Total IC misses: %7d", tot_misses); + tty->print_cr("Total IC misses: %7d", tot_misses); } } #endif // PRODUCT @@ -266,7 +266,7 @@ JRT_LEAF(jfloat, SharedRuntime::frem(jfloat x, jfloat y)) xbits.f = x; ybits.f = y; // x Mod Infinity == x unless x is infinity - if ( ((xbits.i & float_sign_mask) != float_infinity) && + if (((xbits.i & float_sign_mask) != float_infinity) && ((ybits.i & float_sign_mask) == float_infinity) ) { return x; } @@ -281,7 +281,7 @@ JRT_LEAF(jdouble, SharedRuntime::drem(jdouble x, jdouble y)) xbits.d = x; ybits.d = y; // x Mod Infinity == x unless x is infinity - if ( ((xbits.l & double_sign_mask) != double_infinity) && + if (((xbits.l & double_sign_mask) != double_infinity) && ((ybits.l & double_sign_mask) == double_infinity) ) { return x; } @@ -537,13 +537,13 @@ address SharedRuntime::get_poll_stub(address pc) { CodeBlob *cb = CodeCache::find_blob(pc); // Should be an nmethod - assert( cb && cb->is_nmethod(), "safepoint polling: pc must refer to an nmethod" ); + assert(cb && cb->is_nmethod(), "safepoint polling: pc must refer to an nmethod"); // Look up the relocation information - assert( ((nmethod*)cb)->is_at_poll_or_poll_return(pc), - "safepoint polling: type must be poll" ); + assert(((nmethod*)cb)->is_at_poll_or_poll_return(pc), + "safepoint polling: type must be poll"); - assert( ((NativeInstruction*)pc)->is_safepoint_poll(), + assert(((NativeInstruction*)pc)->is_safepoint_poll(), "Only polling locations are used for safepoint"); bool at_poll_return = ((nmethod*)cb)->is_at_poll_return(pc); @@ -562,7 +562,7 @@ address SharedRuntime::get_poll_stub(address pc) { stub = SharedRuntime::polling_page_safepoint_handler_blob()->entry_point(); } #ifndef PRODUCT - if( TraceSafepoint ) { + if (TraceSafepoint) { char buf[256]; jio_snprintf(buf, sizeof(buf), "... found polling page %s exception at pc = " @@ -1474,7 +1474,7 @@ methodHandle SharedRuntime::handle_ic_miss_helper(JavaThread *thread, TRAPS) { should_be_mono = true; } else if (inline_cache->is_icholder_call()) { CompiledICHolder* ic_oop = inline_cache->cached_icholder(); - if ( ic_oop != NULL) { + if (ic_oop != NULL) { if (receiver()->klass() == ic_oop->holder_klass()) { // This isn't a real miss. We must have seen that compiled code @@ -1728,7 +1728,7 @@ IRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address cal iter.next(); assert(iter.has_current(), "must have a reloc at java call site"); relocInfo::relocType typ = iter.reloc()->type(); - if ( typ != relocInfo::static_call_type && + if (typ != relocInfo::static_call_type && typ != relocInfo::opt_virtual_call_type && typ != relocInfo::static_stub_type) { return; @@ -1784,7 +1784,7 @@ JRT_ENTRY(void, SharedRuntime::slow_arraycopy_C(oopDesc* src, jint src_pos, // The copy_array mechanism is awkward and could be removed, but // the compilers don't call this function except as a last resort, // so it probably doesn't matter. - src->klass()->copy_array((arrayOopDesc*)src, src_pos, + src->klass()->copy_array((arrayOopDesc*)src, src_pos, (arrayOopDesc*)dest, dest_pos, length, thread); } @@ -1891,8 +1891,8 @@ void SharedRuntime::print_statistics() { ttyLocker ttyl; if (xtty != NULL) xtty->head("statistics type='SharedRuntime'"); - if (_monitor_enter_ctr ) tty->print_cr("%5d monitor enter slow", _monitor_enter_ctr); - if (_monitor_exit_ctr ) tty->print_cr("%5d monitor exit slow", _monitor_exit_ctr); + if (_monitor_enter_ctr) tty->print_cr("%5d monitor enter slow", _monitor_enter_ctr); + if (_monitor_exit_ctr) tty->print_cr("%5d monitor exit slow", _monitor_exit_ctr); if (_throw_null_ctr) tty->print_cr("%5d implicit null throw", _throw_null_ctr); SharedRuntime::print_ic_miss_histogram(); @@ -1905,36 +1905,36 @@ void SharedRuntime::print_statistics() { } // Dump the JRT_ENTRY counters - if( _new_instance_ctr ) tty->print_cr("%5d new instance requires GC", _new_instance_ctr); - if( _new_array_ctr ) tty->print_cr("%5d new array requires GC", _new_array_ctr); - if( _multi1_ctr ) tty->print_cr("%5d multianewarray 1 dim", _multi1_ctr); - if( _multi2_ctr ) tty->print_cr("%5d multianewarray 2 dim", _multi2_ctr); - if( _multi3_ctr ) tty->print_cr("%5d multianewarray 3 dim", _multi3_ctr); - if( _multi4_ctr ) tty->print_cr("%5d multianewarray 4 dim", _multi4_ctr); - if( _multi5_ctr ) tty->print_cr("%5d multianewarray 5 dim", _multi5_ctr); + if (_new_instance_ctr) tty->print_cr("%5d new instance requires GC", _new_instance_ctr); + if (_new_array_ctr) tty->print_cr("%5d new array requires GC", _new_array_ctr); + if (_multi1_ctr) tty->print_cr("%5d multianewarray 1 dim", _multi1_ctr); + if (_multi2_ctr) tty->print_cr("%5d multianewarray 2 dim", _multi2_ctr); + if (_multi3_ctr) tty->print_cr("%5d multianewarray 3 dim", _multi3_ctr); + if (_multi4_ctr) tty->print_cr("%5d multianewarray 4 dim", _multi4_ctr); + if (_multi5_ctr) tty->print_cr("%5d multianewarray 5 dim", _multi5_ctr); - tty->print_cr("%5d inline cache miss in compiled", _ic_miss_ctr ); - tty->print_cr("%5d wrong method", _wrong_method_ctr ); - tty->print_cr("%5d unresolved static call site", _resolve_static_ctr ); - tty->print_cr("%5d unresolved virtual call site", _resolve_virtual_ctr ); - tty->print_cr("%5d unresolved opt virtual call site", _resolve_opt_virtual_ctr ); + tty->print_cr("%5d inline cache miss in compiled", _ic_miss_ctr); + tty->print_cr("%5d wrong method", _wrong_method_ctr); + tty->print_cr("%5d unresolved static call site", _resolve_static_ctr); + tty->print_cr("%5d unresolved virtual call site", _resolve_virtual_ctr); + tty->print_cr("%5d unresolved opt virtual call site", _resolve_opt_virtual_ctr); - if( _mon_enter_stub_ctr ) tty->print_cr("%5d monitor enter stub", _mon_enter_stub_ctr ); - if( _mon_exit_stub_ctr ) tty->print_cr("%5d monitor exit stub", _mon_exit_stub_ctr ); - if( _mon_enter_ctr ) tty->print_cr("%5d monitor enter slow", _mon_enter_ctr ); - if( _mon_exit_ctr ) tty->print_cr("%5d monitor exit slow", _mon_exit_ctr ); - if( _partial_subtype_ctr) tty->print_cr("%5d slow partial subtype", _partial_subtype_ctr ); - if( _jbyte_array_copy_ctr ) tty->print_cr("%5d byte array copies", _jbyte_array_copy_ctr ); - if( _jshort_array_copy_ctr ) tty->print_cr("%5d short array copies", _jshort_array_copy_ctr ); - if( _jint_array_copy_ctr ) tty->print_cr("%5d int array copies", _jint_array_copy_ctr ); - if( _jlong_array_copy_ctr ) tty->print_cr("%5d long array copies", _jlong_array_copy_ctr ); - if( _oop_array_copy_ctr ) tty->print_cr("%5d oop array copies", _oop_array_copy_ctr ); - if( _checkcast_array_copy_ctr ) tty->print_cr("%5d checkcast array copies", _checkcast_array_copy_ctr ); - if( _unsafe_array_copy_ctr ) tty->print_cr("%5d unsafe array copies", _unsafe_array_copy_ctr ); - if( _generic_array_copy_ctr ) tty->print_cr("%5d generic array copies", _generic_array_copy_ctr ); - if( _slow_array_copy_ctr ) tty->print_cr("%5d slow array copies", _slow_array_copy_ctr ); - if( _find_handler_ctr ) tty->print_cr("%5d find exception handler", _find_handler_ctr ); - if( _rethrow_ctr ) tty->print_cr("%5d rethrow handler", _rethrow_ctr ); + if (_mon_enter_stub_ctr) tty->print_cr("%5d monitor enter stub", _mon_enter_stub_ctr); + if (_mon_exit_stub_ctr) tty->print_cr("%5d monitor exit stub", _mon_exit_stub_ctr); + if (_mon_enter_ctr) tty->print_cr("%5d monitor enter slow", _mon_enter_ctr); + if (_mon_exit_ctr) tty->print_cr("%5d monitor exit slow", _mon_exit_ctr); + if (_partial_subtype_ctr) tty->print_cr("%5d slow partial subtype", _partial_subtype_ctr); + if (_jbyte_array_copy_ctr) tty->print_cr("%5d byte array copies", _jbyte_array_copy_ctr); + if (_jshort_array_copy_ctr) tty->print_cr("%5d short array copies", _jshort_array_copy_ctr); + if (_jint_array_copy_ctr) tty->print_cr("%5d int array copies", _jint_array_copy_ctr); + if (_jlong_array_copy_ctr) tty->print_cr("%5d long array copies", _jlong_array_copy_ctr); + if (_oop_array_copy_ctr) tty->print_cr("%5d oop array copies", _oop_array_copy_ctr); + if (_checkcast_array_copy_ctr) tty->print_cr("%5d checkcast array copies", _checkcast_array_copy_ctr); + if (_unsafe_array_copy_ctr) tty->print_cr("%5d unsafe array copies", _unsafe_array_copy_ctr); + if (_generic_array_copy_ctr) tty->print_cr("%5d generic array copies", _generic_array_copy_ctr); + if (_slow_array_copy_ctr) tty->print_cr("%5d slow array copies", _slow_array_copy_ctr); + if (_find_handler_ctr) tty->print_cr("%5d find exception handler", _find_handler_ctr); + if (_rethrow_ctr) tty->print_cr("%5d rethrow handler", _rethrow_ctr); AdapterHandlerLibrary::print_statistics(); @@ -1997,7 +1997,7 @@ class MethodArityHistogram { MethodArityHistogram() { MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); _max_arity = _max_size = 0; - for (int i = 0; i < MAX_ARITY; i++) _arity_histogram[i] = _size_histogram [i] = 0; + for (int i = 0; i < MAX_ARITY; i++) _arity_histogram[i] = _size_histogram[i] = 0; CodeCache::nmethods_do(add_method_to_histogram); print_histogram(); } @@ -2062,7 +2062,7 @@ class AdapterFingerPrint : public CHeapObj { // These are correct for the current system but someday it might be // necessary to make this mapping platform dependent. static int adapter_encoding(BasicType in) { - switch(in) { + switch (in) { case T_BOOLEAN: case T_BYTE: case T_SHORT: @@ -2479,7 +2479,7 @@ AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(methodHandle method) { tty->print_cr("i2c argument handler #%d for: %s %s (%d bytes generated)", _adapters->number_of_entries(), (method->is_static() ? "static" : "receiver"), method->signature()->as_C_string(), insts_size); - tty->print_cr("c2i argument handler starts at %p",entry->get_c2i_entry()); + tty->print_cr("c2i argument handler starts at %p", entry->get_c2i_entry()); if (Verbose || PrintStubCode) { address first_pc = entry->base_address(); if (first_pc != NULL) { @@ -2504,7 +2504,7 @@ AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(methodHandle method) { new_adapter->name(), fingerprint->as_string(), new_adapter->content_begin()); - Forte::register_stub(blob_id, new_adapter->content_begin(),new_adapter->content_end()); + Forte::register_stub(blob_id, new_adapter->content_begin(), new_adapter->content_end()); if (JvmtiExport::should_post_dynamic_code_generated()) { JvmtiExport::post_dynamic_code_generated(blob_id, new_adapter->content_begin(), new_adapter->content_end()); @@ -2605,12 +2605,12 @@ void AdapterHandlerLibrary::create_native_wrapper(methodHandle method) { BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_args_passed); VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed); int i=0; - if( !method->is_static() ) // Pass in receiver first + if (!method->is_static()) // Pass in receiver first sig_bt[i++] = T_OBJECT; SignatureStream ss(method->signature()); - for( ; !ss.at_return_type(); ss.next()) { + for (; !ss.at_return_type(); ss.next()) { sig_bt[i++] = ss.type(); // Collect remaining bits of signature - if( ss.type() == T_LONG || ss.type() == T_DOUBLE ) + if (ss.type() == T_LONG || ss.type() == T_DOUBLE) sig_bt[i++] = T_VOID; // Longs & doubles take 2 Java slots } assert(i == total_args_passed, ""); @@ -2762,10 +2762,10 @@ void SharedRuntime::convert_ints_to_longints(int i2l_argcnt, int& in_args_count, case T_SHORT: case T_INT: // Convert (bt) to (T_LONG,bt). - new_in_sig_bt[argcnt ] = T_LONG; + new_in_sig_bt[argcnt] = T_LONG; new_in_sig_bt[argcnt+1] = bt; assert(reg.first()->is_valid() && !reg.second()->is_valid(), ""); - new_in_regs[argcnt ].set2(reg.first()); + new_in_regs[argcnt].set2(reg.first()); new_in_regs[argcnt+1].set_bad(); argcnt++; break; @@ -2808,17 +2808,17 @@ VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, int len = (int)strlen(s); s++; len--; // Skip opening paren char *t = s+len; - while( *(--t) != ')' ) ; // Find close paren + while (*(--t) != ')'); // Find close paren - BasicType *sig_bt = NEW_RESOURCE_ARRAY( BasicType, 256 ); - VMRegPair *regs = NEW_RESOURCE_ARRAY( VMRegPair, 256 ); + BasicType *sig_bt = NEW_RESOURCE_ARRAY(BasicType, 256); + VMRegPair *regs = NEW_RESOURCE_ARRAY(VMRegPair, 256); int cnt = 0; if (has_receiver) { sig_bt[cnt++] = T_OBJECT; // Receiver is argument 0; not in signature } - while( s < t ) { - switch( *s++ ) { // Switch on signature character + while (s < t) { + switch (*s++) { // Switch on signature character case 'B': sig_bt[cnt++] = T_BYTE; break; case 'C': sig_bt[cnt++] = T_CHAR; break; case 'D': sig_bt[cnt++] = T_DOUBLE; sig_bt[cnt++] = T_VOID; break; @@ -2829,16 +2829,16 @@ VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, case 'Z': sig_bt[cnt++] = T_BOOLEAN; break; case 'V': sig_bt[cnt++] = T_VOID; break; case 'L': // Oop - while( *s++ != ';' ) ; // Skip signature + while (*s++ != ';'); // Skip signature sig_bt[cnt++] = T_OBJECT; break; case '[': { // Array do { // Skip optional size - while( *s >= '0' && *s <= '9' ) s++; - } while( *s++ == '[' ); // Nested arrays? + while (*s >= '0' && *s <= '9') s++; + } while (*s++ == '['); // Nested arrays? // Skip element type - if( s[-1] == 'L' ) - while( *s++ != ';' ) ; // Skip signature + if (s[-1] == 'L') + while (*s++ != ';'); // Skip signature sig_bt[cnt++] = T_ARRAY; break; } @@ -2850,7 +2850,7 @@ VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, sig_bt[cnt++] = T_OBJECT; } - assert( cnt < 256, "grow table size" ); + assert(cnt < 256, "grow table size"); int comp_args_on_stack; comp_args_on_stack = java_calling_convention(sig_bt, regs, cnt, true); @@ -2861,12 +2861,12 @@ VMRegPair *SharedRuntime::find_callee_arguments(Symbol* sig, bool has_receiver, if (comp_args_on_stack) { for (int i = 0; i < cnt; i++) { VMReg reg1 = regs[i].first(); - if( reg1->is_stack()) { + if (reg1->is_stack()) { // Yuck reg1 = reg1->bias(out_preserve_stack_slots()); } VMReg reg2 = regs[i].second(); - if( reg2->is_stack()) { + if (reg2->is_stack()) { // Yuck reg2 = reg2->bias(out_preserve_stack_slots()); } @@ -2904,15 +2904,15 @@ JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *thread) ) // frame accessor methods and be platform independent. frame fr = thread->last_frame(); - assert( fr.is_interpreted_frame(), "" ); - assert( fr.interpreter_frame_expression_stack_size()==0, "only handle empty stacks" ); + assert(fr.is_interpreted_frame(), ""); + assert(fr.interpreter_frame_expression_stack_size()==0, "only handle empty stacks"); // Figure out how many monitors are active. int active_monitor_count = 0; - for( BasicObjectLock *kptr = fr.interpreter_frame_monitor_end(); + for (BasicObjectLock *kptr = fr.interpreter_frame_monitor_end(); kptr < fr.interpreter_frame_monitor_begin(); kptr = fr.next_monitor_in_interpreter_frame(kptr) ) { - if( kptr->obj() != NULL ) active_monitor_count++; + if (kptr->obj() != NULL) active_monitor_count++; } // QQQ we could place number of active monitors in the array so that compiled code @@ -2926,17 +2926,17 @@ JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *thread) ) // Copy the locals. Order is preserved so that loading of longs works. // Since there's no GC I can copy the oops blindly. - assert( sizeof(HeapWord)==sizeof(intptr_t), "fix this code"); + assert(sizeof(HeapWord)==sizeof(intptr_t), "fix this code"); Copy::disjoint_words((HeapWord*)fr.interpreter_frame_local_at(max_locals-1), (HeapWord*)&buf[0], max_locals); // Inflate locks. Copy the displaced headers. Be careful, there can be holes. int i = max_locals; - for( BasicObjectLock *kptr2 = fr.interpreter_frame_monitor_end(); + for (BasicObjectLock *kptr2 = fr.interpreter_frame_monitor_end(); kptr2 < fr.interpreter_frame_monitor_begin(); kptr2 = fr.next_monitor_in_interpreter_frame(kptr2) ) { - if( kptr2->obj() != NULL) { // Avoid 'holes' in the monitor array + if (kptr2->obj() != NULL) { // Avoid 'holes' in the monitor array BasicLock *lock = kptr2->lock(); // Inflate so the displaced header becomes position-independent if (lock->displaced_header()->is_unlocked()) @@ -2946,20 +2946,20 @@ JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *thread) ) buf[i++] = cast_from_oop(kptr2->obj()); } } - assert( i - max_locals == active_monitor_count*2, "found the expected number of monitors" ); + assert(i - max_locals == active_monitor_count*2, "found the expected number of monitors"); return buf; JRT_END JRT_LEAF(void, SharedRuntime::OSR_migration_end( intptr_t* buf) ) - FREE_C_HEAP_ARRAY(intptr_t,buf, mtCode); + FREE_C_HEAP_ARRAY(intptr_t, buf, mtCode); JRT_END bool AdapterHandlerLibrary::contains(CodeBlob* b) { AdapterHandlerTableIterator iter(_adapters); while (iter.has_next()) { AdapterHandlerEntry* a = iter.next(); - if ( b == CodeCache::find_blob(a->get_i2c_entry()) ) return true; + if (b == CodeCache::find_blob(a->get_i2c_entry())) return true; } return false; } diff --git a/hotspot/src/share/vm/runtime/sharedRuntime.hpp b/hotspot/src/share/vm/runtime/sharedRuntime.hpp index c28c469d0e8..a6d4dfd704d 100644 --- a/hotspot/src/share/vm/runtime/sharedRuntime.hpp +++ b/hotspot/src/share/vm/runtime/sharedRuntime.hpp @@ -217,7 +217,7 @@ class SharedRuntime: AllStatic { static UncommonTrapBlob* uncommon_trap_blob() { return _uncommon_trap_blob; } #endif // COMPILER2 - static address get_resolve_opt_virtual_call_stub(){ + static address get_resolve_opt_virtual_call_stub() { assert(_resolve_opt_virtual_call_blob != NULL, "oops"); return _resolve_opt_virtual_call_blob->entry_point(); } @@ -253,7 +253,7 @@ class SharedRuntime: AllStatic { // bytecode tracing is only used by the TraceBytecodes static intptr_t trace_bytecode(JavaThread* thread, intptr_t preserve_this_value, intptr_t tos, intptr_t tos2) PRODUCT_RETURN0; - static oop retrieve_receiver( Symbol* sig, frame caller ); + static oop retrieve_receiver(Symbol* sig, frame caller); static void register_finalizer(JavaThread* thread, oopDesc* obj); @@ -446,8 +446,8 @@ class SharedRuntime: AllStatic { static bool is_wide_vector(int size); // Save and restore a native result - static void save_native_result(MacroAssembler *_masm, BasicType ret_type, int frame_slots ); - static void restore_native_result(MacroAssembler *_masm, BasicType ret_type, int frame_slots ); + static void save_native_result(MacroAssembler *_masm, BasicType ret_type, int frame_slots); + static void restore_native_result(MacroAssembler *_masm, BasicType ret_type, int frame_slots); // Generate a native wrapper for a given method. The method takes arguments // in the Java compiled code convention, marshals them to the native @@ -463,7 +463,7 @@ class SharedRuntime: AllStatic { int compile_id, BasicType* sig_bt, VMRegPair* regs, - BasicType ret_type ); + BasicType ret_type); // Block before entering a JNI critical method static void block_for_jni_critical(JavaThread* thread); diff --git a/hotspot/src/share/vm/runtime/sharedRuntimeTrig.cpp b/hotspot/src/share/vm/runtime/sharedRuntimeTrig.cpp index 1691bdf7690..84f35aa9317 100644 --- a/hotspot/src/share/vm/runtime/sharedRuntimeTrig.cpp +++ b/hotspot/src/share/vm/runtime/sharedRuntimeTrig.cpp @@ -26,6 +26,7 @@ #include "prims/jni.h" #include "runtime/interfaceSupport.hpp" #include "runtime/sharedRuntime.hpp" +#include "runtime/sharedRuntimeMath.hpp" // This file contains copies of the fdlibm routines used by // StrictMath. It turns out that it is almost always required to use @@ -36,35 +37,6 @@ // pointer out to libjava.so in SharedRuntime speeds these routines up // by roughly 15% on both Win32/x86 and Solaris/SPARC. -// Enabling optimizations in this file causes incorrect code to be -// generated; can not figure out how to turn down optimization for one -// file in the IDE on Windows -#ifdef WIN32 -# pragma optimize ( "", off ) -#endif - -/* The above workaround now causes more problems with the latest MS compiler. - * Visual Studio 2010's /GS option tries to guard against buffer overruns. - * /GS is on by default if you specify optimizations, which we do globally - * via /W3 /O2. However the above selective turning off of optimizations means - * that /GS issues a warning "4748". And since we treat warnings as errors (/WX) - * then the compilation fails. There are several possible solutions - * (1) Remove that pragma above as obsolete with VS2010 - requires testing. - * (2) Stop treating warnings as errors - would be a backward step - * (3) Disable /GS - may help performance but you lose the security checks - * (4) Disable the warning with "#pragma warning( disable : 4748 )" - * (5) Disable planting the code with __declspec(safebuffers) - * I've opted for (5) although we should investigate the local performance - * benefits of (1) and global performance benefit of (3). - */ -#if defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1600)) -#define SAFEBUF __declspec(safebuffers) -#else -#define SAFEBUF -#endif - -#include "runtime/sharedRuntimeMath.hpp" - /* * __kernel_rem_pio2(x,y,e0,nx,prec,ipio2) * double x[],y[]; int e0,nx,prec; int ipio2[]; @@ -201,7 +173,7 @@ one = 1.0, two24B = 1.67772160000000000000e+07, /* 0x41700000, 0x00000000 */ twon24 = 5.96046447753906250000e-08; /* 0x3E700000, 0x00000000 */ -static SAFEBUF int __kernel_rem_pio2(double *x, double *y, int e0, int nx, int prec, const int *ipio2) { +static int __kernel_rem_pio2(double *x, double *y, int e0, int nx, int prec, const int *ipio2) { int jz,jx,jv,jp,jk,carry,n,iq[20],i,j,k,m,q0,ih; double z,fw,f[20],fq[20],q[20]; @@ -417,7 +389,7 @@ pio2_2t = 2.02226624879595063154e-21, /* 0x3BA3198A, 0x2E037073 */ pio2_3 = 2.02226624871116645580e-21, /* 0x3BA3198A, 0x2E000000 */ pio2_3t = 8.47842766036889956997e-32; /* 0x397B839A, 0x252049C1 */ -static SAFEBUF int __ieee754_rem_pio2(double x, double *y) { +static int __ieee754_rem_pio2(double x, double *y) { double z,w,t,r,fn; double tx[3]; int e0,i,j,nx,n,ix,hx,i0; @@ -916,8 +888,3 @@ JRT_LEAF(jdouble, SharedRuntime::dtan(jdouble x)) -1 -- n odd */ } JRT_END - - -#ifdef WIN32 -# pragma optimize ( "", on ) -#endif diff --git a/hotspot/src/share/vm/runtime/synchronizer.cpp b/hotspot/src/share/vm/runtime/synchronizer.cpp index 62bd1ab9139..7af5fe72b62 100644 --- a/hotspot/src/share/vm/runtime/synchronizer.cpp +++ b/hotspot/src/share/vm/runtime/synchronizer.cpp @@ -120,15 +120,15 @@ int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) { } #define NINFLATIONLOCKS 256 -static volatile intptr_t InflationLocks [NINFLATIONLOCKS] ; +static volatile intptr_t InflationLocks[NINFLATIONLOCKS]; -ObjectMonitor * ObjectSynchronizer::gBlockList = NULL ; -ObjectMonitor * volatile ObjectSynchronizer::gFreeList = NULL ; -ObjectMonitor * volatile ObjectSynchronizer::gOmInUseList = NULL ; +ObjectMonitor * ObjectSynchronizer::gBlockList = NULL; +ObjectMonitor * volatile ObjectSynchronizer::gFreeList = NULL; +ObjectMonitor * volatile ObjectSynchronizer::gOmInUseList = NULL; int ObjectSynchronizer::gOmInUseCount = 0; -static volatile intptr_t ListLock = 0 ; // protects global monitor free-list cache -static volatile int MonitorFreeCount = 0 ; // # on gFreeList -static volatile int MonitorPopulation = 0 ; // # Extant -- in circulation +static volatile intptr_t ListLock = 0; // protects global monitor free-list cache +static volatile int MonitorFreeCount = 0; // # on gFreeList +static volatile int MonitorPopulation = 0; // # Extant -- in circulation #define CHAINMARKER (cast_to_oop(-1)) // ----------------------------------------------------------------------------- @@ -152,43 +152,43 @@ void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock, bool attempt_re assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); } - slow_enter (obj, lock, THREAD) ; + slow_enter(obj, lock, THREAD); } void ObjectSynchronizer::fast_exit(oop object, BasicLock* lock, TRAPS) { assert(!object->mark()->has_bias_pattern(), "should not see bias pattern here"); // if displaced header is null, the previous enter is recursive enter, no-op markOop dhw = lock->displaced_header(); - markOop mark ; + markOop mark; if (dhw == NULL) { // Recursive stack-lock. // Diagnostics -- Could be: stack-locked, inflating, inflated. - mark = object->mark() ; - assert (!mark->is_neutral(), "invariant") ; + mark = object->mark(); + assert(!mark->is_neutral(), "invariant"); if (mark->has_locker() && mark != markOopDesc::INFLATING()) { - assert(THREAD->is_lock_owned((address)mark->locker()), "invariant") ; + assert(THREAD->is_lock_owned((address)mark->locker()), "invariant"); } if (mark->has_monitor()) { - ObjectMonitor * m = mark->monitor() ; - assert(((oop)(m->object()))->mark() == mark, "invariant") ; - assert(m->is_entered(THREAD), "invariant") ; + ObjectMonitor * m = mark->monitor(); + assert(((oop)(m->object()))->mark() == mark, "invariant"); + assert(m->is_entered(THREAD), "invariant"); } - return ; + return; } - mark = object->mark() ; + mark = object->mark(); // If the object is stack-locked by the current thread, try to // swing the displaced header from the box back to the mark. if (mark == (markOop) lock) { - assert (dhw->is_neutral(), "invariant") ; + assert(dhw->is_neutral(), "invariant"); if ((markOop) Atomic::cmpxchg_ptr (dhw, object->mark_addr(), mark) == mark) { - TEVENT (fast_exit: release stacklock) ; + TEVENT(fast_exit: release stacklock); return; } } - ObjectSynchronizer::inflate(THREAD, object)->exit (true, THREAD) ; + ObjectSynchronizer::inflate(THREAD, object)->exit(true, THREAD); } // ----------------------------------------------------------------------------- @@ -205,8 +205,8 @@ void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) { // be visible <= the ST performed by the CAS. lock->set_displaced_header(mark); if (mark == (markOop) Atomic::cmpxchg_ptr(lock, obj()->mark_addr(), mark)) { - TEVENT (slow_enter: release stacklock) ; - return ; + TEVENT(slow_enter: release stacklock); + return; } // Fall through to inflate() ... } else @@ -220,8 +220,8 @@ void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) { #if 0 // The following optimization isn't particularly useful. if (mark->has_monitor() && mark->monitor()->is_entered(THREAD)) { - lock->set_displaced_header (NULL) ; - return ; + lock->set_displaced_header(NULL); + return; } #endif @@ -238,7 +238,7 @@ void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) { // failed in the interpreter/compiler code. Simply use the heavy // weight monitor should be ok, unless someone find otherwise. void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) { - fast_exit (object, lock, THREAD) ; + fast_exit(object, lock, THREAD); } // ----------------------------------------------------------------------------- @@ -254,7 +254,7 @@ void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) { // 5) lock lock2 // NOTE: must use heavy weight monitor to handle complete_exit/reenter() intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) { - TEVENT (complete_exit) ; + TEVENT(complete_exit); if (UseBiasedLocking) { BiasedLocking::revoke_and_rebias(obj, false, THREAD); assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); @@ -267,7 +267,7 @@ intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) { // NOTE: must use heavy weight monitor to handle complete_exit/reenter() void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) { - TEVENT (reenter) ; + TEVENT(reenter); if (UseBiasedLocking) { BiasedLocking::revoke_and_rebias(obj, false, THREAD); assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); @@ -282,7 +282,7 @@ void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) { // NOTE: must use heavy weight monitor to handle jni monitor enter void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) { // possible entry from jni enter // the current locking is from JNI instead of Java code - TEVENT (jni_enter) ; + TEVENT(jni_enter); if (UseBiasedLocking) { BiasedLocking::revoke_and_rebias(obj, false, THREAD); assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); @@ -306,7 +306,7 @@ bool ObjectSynchronizer::jni_try_enter(Handle obj, Thread* THREAD) { // NOTE: must use heavy weight monitor to handle jni monitor exit void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) { - TEVENT (jni_exit) ; + TEVENT(jni_exit); if (UseBiasedLocking) { Handle h_obj(THREAD, obj); BiasedLocking::revoke_and_rebias(h_obj, false, THREAD); @@ -332,7 +332,7 @@ ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) { _obj = obj; if (_dolock) { - TEVENT (ObjectLocker) ; + TEVENT(ObjectLocker); ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread); } @@ -354,7 +354,7 @@ int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) { assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); } if (millis < 0) { - TEVENT (wait - throw IAX) ; + TEVENT(wait - throw IAX); THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); } ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj()); @@ -374,10 +374,10 @@ void ObjectSynchronizer::waitUninterruptibly (Handle obj, jlong millis, TRAPS) { assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); } if (millis < 0) { - TEVENT (wait - throw IAX) ; + TEVENT(wait - throw IAX); THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); } - ObjectSynchronizer::inflate(THREAD, obj()) -> wait(millis, false, THREAD) ; + ObjectSynchronizer::inflate(THREAD, obj()) -> wait(millis, false, THREAD); } void ObjectSynchronizer::notify(Handle obj, TRAPS) { @@ -428,31 +428,31 @@ void ObjectSynchronizer::notifyall(Handle obj, TRAPS) { struct SharedGlobals { // These are highly shared mostly-read variables. // To avoid false-sharing they need to be the sole occupants of a $ line. - double padPrefix [8]; - volatile int stwRandom ; - volatile int stwCycle ; + double padPrefix[8]; + volatile int stwRandom; + volatile int stwCycle; // Hot RW variables -- Sequester to avoid false-sharing - double padSuffix [16]; - volatile int hcSequence ; - double padFinal [8] ; -} ; + double padSuffix[16]; + volatile int hcSequence; + double padFinal[8]; +}; -static SharedGlobals GVars ; -static int MonitorScavengeThreshold = 1000000 ; -static volatile int ForceMonitorScavenge = 0 ; // Scavenge required and pending +static SharedGlobals GVars; +static int MonitorScavengeThreshold = 1000000; +static volatile int ForceMonitorScavenge = 0; // Scavenge required and pending static markOop ReadStableMark (oop obj) { - markOop mark = obj->mark() ; + markOop mark = obj->mark(); if (!mark->is_being_inflated()) { - return mark ; // normal fast-path return + return mark; // normal fast-path return } - int its = 0 ; + int its = 0; for (;;) { - markOop mark = obj->mark() ; + markOop mark = obj->mark(); if (!mark->is_being_inflated()) { - return mark ; // normal fast-path return + return mark; // normal fast-path return } // The object is being inflated by some other thread. @@ -465,11 +465,11 @@ static markOop ReadStableMark (oop obj) { // TODO: add inflation contention performance counters. // TODO: restrict the aggregate number of spinners. - ++its ; + ++its; if (its > 10000 || !os::is_MP()) { if (its & 1) { - os::NakedYield() ; - TEVENT (Inflate: INFLATING - yield) ; + os::NakedYield(); + TEVENT(Inflate: INFLATING - yield); } else { // Note that the following code attenuates the livelock problem but is not // a complete remedy. A more complete solution would require that the inflating @@ -486,26 +486,26 @@ static markOop ReadStableMark (oop obj) { // then for each thread on the list, set the flag and unpark() the thread. // This is conceptually similar to muxAcquire-muxRelease, except that muxRelease // wakes at most one thread whereas we need to wake the entire list. - int ix = (cast_from_oop(obj) >> 5) & (NINFLATIONLOCKS-1) ; - int YieldThenBlock = 0 ; - assert (ix >= 0 && ix < NINFLATIONLOCKS, "invariant") ; - assert ((NINFLATIONLOCKS & (NINFLATIONLOCKS-1)) == 0, "invariant") ; - Thread::muxAcquire (InflationLocks + ix, "InflationLock") ; + int ix = (cast_from_oop(obj) >> 5) & (NINFLATIONLOCKS-1); + int YieldThenBlock = 0; + assert(ix >= 0 && ix < NINFLATIONLOCKS, "invariant"); + assert((NINFLATIONLOCKS & (NINFLATIONLOCKS-1)) == 0, "invariant"); + Thread::muxAcquire(InflationLocks + ix, "InflationLock"); while (obj->mark() == markOopDesc::INFLATING()) { // Beware: NakedYield() is advisory and has almost no effect on some platforms // so we periodically call Self->_ParkEvent->park(1). // We use a mixed spin/yield/block mechanism. if ((YieldThenBlock++) >= 16) { - Thread::current()->_ParkEvent->park(1) ; + Thread::current()->_ParkEvent->park(1); } else { - os::NakedYield() ; + os::NakedYield(); } } - Thread::muxRelease (InflationLocks + ix ) ; - TEVENT (Inflate: INFLATING - yield/park) ; + Thread::muxRelease(InflationLocks + ix); + TEVENT(Inflate: INFLATING - yield/park); } } else { - SpinPause() ; // SMP-polite spinning + SpinPause(); // SMP-polite spinning } } } @@ -529,48 +529,48 @@ static markOop ReadStableMark (oop obj) { // static inline intptr_t get_next_hash(Thread * Self, oop obj) { - intptr_t value = 0 ; + intptr_t value = 0; if (hashCode == 0) { // This form uses an unguarded global Park-Miller RNG, // so it's possible for two threads to race and generate the same RNG. // On MP system we'll have lots of RW access to a global, so the // mechanism induces lots of coherency traffic. - value = os::random() ; + value = os::random(); } else if (hashCode == 1) { // This variation has the property of being stable (idempotent) // between STW operations. This can be useful in some of the 1-0 // synchronization schemes. - intptr_t addrBits = cast_from_oop(obj) >> 3 ; - value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ; + intptr_t addrBits = cast_from_oop(obj) >> 3; + value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom; } else if (hashCode == 2) { - value = 1 ; // for sensitivity testing + value = 1; // for sensitivity testing } else if (hashCode == 3) { - value = ++GVars.hcSequence ; + value = ++GVars.hcSequence; } else if (hashCode == 4) { - value = cast_from_oop(obj) ; + value = cast_from_oop(obj); } else { // Marsaglia's xor-shift scheme with thread-specific state // This is probably the best overall implementation -- we'll // likely make this the default in future releases. - unsigned t = Self->_hashStateX ; - t ^= (t << 11) ; - Self->_hashStateX = Self->_hashStateY ; - Self->_hashStateY = Self->_hashStateZ ; - Self->_hashStateZ = Self->_hashStateW ; - unsigned v = Self->_hashStateW ; - v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ; - Self->_hashStateW = v ; - value = v ; + unsigned t = Self->_hashStateX; + t ^= (t << 11); + Self->_hashStateX = Self->_hashStateY; + Self->_hashStateY = Self->_hashStateZ; + Self->_hashStateZ = Self->_hashStateW; + unsigned v = Self->_hashStateW; + v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)); + Self->_hashStateW = v; + value = v; } value &= markOopDesc::hash_mask; - if (value == 0) value = 0xBAD ; - assert (value != markOopDesc::no_hash, "invariant") ; - TEVENT (hashCode: GENERATE) ; + if (value == 0) value = 0xBAD; + assert(value != markOopDesc::no_hash, "invariant"); + TEVENT(hashCode: GENERATE); return value; } // @@ -585,25 +585,25 @@ intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) { // thread-local storage. if (obj->mark()->has_bias_pattern()) { // Box and unbox the raw reference just in case we cause a STW safepoint. - Handle hobj (Self, obj) ; + Handle hobj(Self, obj); // Relaxing assertion for bug 6320749. - assert (Universe::verify_in_progress() || + assert(Universe::verify_in_progress() || !SafepointSynchronize::is_at_safepoint(), "biases should not be seen by VM thread here"); BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current()); - obj = hobj() ; + obj = hobj(); assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); } } // hashCode() is a heap mutator ... // Relaxing assertion for bug 6320749. - assert (Universe::verify_in_progress() || - !SafepointSynchronize::is_at_safepoint(), "invariant") ; - assert (Universe::verify_in_progress() || - Self->is_Java_thread() , "invariant") ; - assert (Universe::verify_in_progress() || - ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ; + assert(Universe::verify_in_progress() || + !SafepointSynchronize::is_at_safepoint(), "invariant"); + assert(Universe::verify_in_progress() || + Self->is_Java_thread() , "invariant"); + assert(Universe::verify_in_progress() || + ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant"); ObjectMonitor* monitor = NULL; markOop temp, test; @@ -611,7 +611,7 @@ intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) { markOop mark = ReadStableMark (obj); // object should remain ineligible for biased locking - assert (!mark->has_bias_pattern(), "invariant") ; + assert(!mark->has_bias_pattern(), "invariant"); if (mark->is_neutral()) { hash = mark->hash(); // this is a normal header @@ -631,7 +631,7 @@ intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) { } else if (mark->has_monitor()) { monitor = mark->monitor(); temp = monitor->header(); - assert (temp->is_neutral(), "invariant") ; + assert(temp->is_neutral(), "invariant"); hash = temp->hash(); if (hash) { return hash; @@ -639,7 +639,7 @@ intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) { // Skip to the following code to reduce code size } else if (Self->is_lock_owned((address)mark->locker())) { temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned - assert (temp->is_neutral(), "invariant") ; + assert(temp->is_neutral(), "invariant"); hash = temp->hash(); // by current thread, check if the displaced if (hash) { // header contains hash code return hash; @@ -659,20 +659,20 @@ intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) { monitor = ObjectSynchronizer::inflate(Self, obj); // Load displaced header and check it has hash code mark = monitor->header(); - assert (mark->is_neutral(), "invariant") ; + assert(mark->is_neutral(), "invariant"); hash = mark->hash(); if (hash == 0) { hash = get_next_hash(Self, obj); temp = mark->copy_set_hash(hash); // merge hash code into header - assert (temp->is_neutral(), "invariant") ; + assert(temp->is_neutral(), "invariant"); test = (markOop) Atomic::cmpxchg_ptr(temp, monitor, mark); if (test != mark) { // The only update to the header in the monitor (outside GC) // is install the hash code. If someone add new usage of // displaced header, please update this code hash = test->hash(); - assert (test->is_neutral(), "invariant") ; - assert (hash != 0, "Trivial unexpected object/monitor header usage."); + assert(test->is_neutral(), "invariant"); + assert(hash != 0, "Trivial unexpected object/monitor header usage."); } } // We finally get the hash @@ -682,7 +682,7 @@ intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) { // Deprecated -- use FastHashCode() instead. intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) { - return FastHashCode (Thread::current(), obj()) ; + return FastHashCode(Thread::current(), obj()); } @@ -696,7 +696,7 @@ bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread, assert(thread == JavaThread::current(), "Can only be called on current thread"); oop obj = h_obj(); - markOop mark = ReadStableMark (obj) ; + markOop mark = ReadStableMark(obj); // Uncontended case, header points to stack if (mark->has_locker()) { @@ -705,7 +705,7 @@ bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread, // Contended case, header points to ObjectMonitor (tagged pointer) if (mark->has_monitor()) { ObjectMonitor* monitor = mark->monitor(); - return monitor->is_entered(thread) != 0 ; + return monitor->is_entered(thread) != 0; } // Unlocked case, header in place assert(mark->is_neutral(), "sanity check"); @@ -721,8 +721,8 @@ ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership (JavaThread *self, Handle h_obj) { // The caller must beware this method can revoke bias, and // revocation can result in a safepoint. - assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ; - assert (self->thread_state() != _thread_blocked , "invariant") ; + assert(!SafepointSynchronize::is_at_safepoint(), "invariant"); + assert(self->thread_state() != _thread_blocked , "invariant"); // Possible mark states: neutral, biased, stack-locked, inflated @@ -735,7 +735,7 @@ ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership assert(self == JavaThread::current(), "Can only be called on current thread"); oop obj = h_obj(); - markOop mark = ReadStableMark (obj) ; + markOop mark = ReadStableMark(obj); // CASE: stack-locked. Mark points to a BasicLock on the owner's stack. if (mark->has_locker()) { @@ -747,15 +747,15 @@ ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership // The Object:ObjectMonitor relationship is stable as long as we're // not at a safepoint. if (mark->has_monitor()) { - void * owner = mark->monitor()->_owner ; - if (owner == NULL) return owner_none ; + void * owner = mark->monitor()->_owner; + if (owner == NULL) return owner_none; return (owner == self || self->is_lock_owned((address)owner)) ? owner_self : owner_other; } // CASE: neutral assert(mark->is_neutral(), "sanity check"); - return owner_none ; // it's unlocked + return owner_none; // it's unlocked } // FIXME: jvmti should call this @@ -772,7 +772,7 @@ JavaThread* ObjectSynchronizer::get_lock_owner(Handle h_obj, bool doLock) { oop obj = h_obj(); address owner = NULL; - markOop mark = ReadStableMark (obj) ; + markOop mark = ReadStableMark(obj); // Uncontended case, header points to stack if (mark->has_locker()) { @@ -819,7 +819,7 @@ void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) { // Get the next block in the block list. static inline ObjectMonitor* next(ObjectMonitor* block) { assert(block->object() == CHAINMARKER, "must be a block header"); - block = block->FreeNext ; + block = block->FreeNext; assert(block == NULL || block->object() == CHAINMARKER, "must be a block header"); return block; } @@ -887,17 +887,17 @@ static void InduceScavenge (Thread * Self, const char * Whence) { if (ForceMonitorScavenge == 0 && Atomic::xchg (1, &ForceMonitorScavenge) == 0) { if (ObjectMonitor::Knob_Verbose) { ::printf ("Monitor scavenge - Induced STW @%s (%d)\n", Whence, ForceMonitorScavenge) ; - ::fflush(stdout) ; + ::fflush(stdout); } // Induce a 'null' safepoint to scavenge monitors // Must VM_Operation instance be heap allocated as the op will be enqueue and posted // to the VMthread and have a lifespan longer than that of this activation record. // The VMThread will delete the op when completed. - VMThread::execute (new VM_ForceAsyncSafepoint()) ; + VMThread::execute(new VM_ForceAsyncSafepoint()); if (ObjectMonitor::Knob_Verbose) { ::printf ("Monitor scavenge - STW posted @%s (%d)\n", Whence, ForceMonitorScavenge) ; - ::fflush(stdout) ; + ::fflush(stdout); } } } @@ -923,9 +923,9 @@ ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) { // number of objectMonitors in circulation as well as the STW // scavenge costs. As usual, we lean toward time in space-time // tradeoffs. - const int MAXPRIVATE = 1024 ; + const int MAXPRIVATE = 1024; for (;;) { - ObjectMonitor * m ; + ObjectMonitor * m; // 1: try to allocate from the thread's local omFreeList. // Threads will attempt to allocate first from their local list, then @@ -933,21 +933,21 @@ ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) { // attempt to instantiate new monitors. Thread-local free lists take // heat off the ListLock and improve allocation latency, as well as reducing // coherency traffic on the shared global list. - m = Self->omFreeList ; + m = Self->omFreeList; if (m != NULL) { - Self->omFreeList = m->FreeNext ; - Self->omFreeCount -- ; + Self->omFreeList = m->FreeNext; + Self->omFreeCount--; // CONSIDER: set m->FreeNext = BAD -- diagnostic hygiene - guarantee (m->object() == NULL, "invariant") ; + guarantee(m->object() == NULL, "invariant"); if (MonitorInUseLists) { m->FreeNext = Self->omInUseList; Self->omInUseList = m; - Self->omInUseCount ++; + Self->omInUseCount++; // verifyInUse(Self); } else { m->FreeNext = NULL; } - return m ; + return m; } // 2: try to allocate from the global gFreeList @@ -959,27 +959,27 @@ ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) { // Reprovision the thread's omFreeList. // Use bulk transfers to reduce the allocation rate and heat // on various locks. - Thread::muxAcquire (&ListLock, "omAlloc") ; - for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL; ) { - MonitorFreeCount --; - ObjectMonitor * take = gFreeList ; - gFreeList = take->FreeNext ; - guarantee (take->object() == NULL, "invariant") ; - guarantee (!take->is_busy(), "invariant") ; - take->Recycle() ; - omRelease (Self, take, false) ; + Thread::muxAcquire(&ListLock, "omAlloc"); + for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL;) { + MonitorFreeCount--; + ObjectMonitor * take = gFreeList; + gFreeList = take->FreeNext; + guarantee(take->object() == NULL, "invariant"); + guarantee(!take->is_busy(), "invariant"); + take->Recycle(); + omRelease(Self, take, false); } - Thread::muxRelease (&ListLock) ; - Self->omFreeProvision += 1 + (Self->omFreeProvision/2) ; - if (Self->omFreeProvision > MAXPRIVATE ) Self->omFreeProvision = MAXPRIVATE ; - TEVENT (omFirst - reprovision) ; + Thread::muxRelease(&ListLock); + Self->omFreeProvision += 1 + (Self->omFreeProvision/2); + if (Self->omFreeProvision > MAXPRIVATE) Self->omFreeProvision = MAXPRIVATE; + TEVENT(omFirst - reprovision); - const int mx = MonitorBound ; + const int mx = MonitorBound; if (mx > 0 && (MonitorPopulation-MonitorFreeCount) > mx) { // We can't safely induce a STW safepoint from omAlloc() as our thread // state may not be appropriate for such activities and callers may hold // naked oops, so instead we defer the action. - InduceScavenge (Self, "omAlloc") ; + InduceScavenge(Self, "omAlloc"); } continue; } @@ -987,14 +987,14 @@ ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) { // 3: allocate a block of new ObjectMonitors // Both the local and global free lists are empty -- resort to malloc(). // In the current implementation objectMonitors are TSM - immortal. - assert (_BLOCKSIZE > 1, "invariant") ; + assert(_BLOCKSIZE > 1, "invariant"); ObjectMonitor * temp = new ObjectMonitor[_BLOCKSIZE]; // NOTE: (almost) no way to recover if allocation failed. // We might be able to induce a STW safepoint and scavenge enough // objectMonitors to permit progress. if (temp == NULL) { - vm_exit_out_of_memory (sizeof (ObjectMonitor[_BLOCKSIZE]), OOM_MALLOC_ERROR, + vm_exit_out_of_memory(sizeof (ObjectMonitor[_BLOCKSIZE]), OOM_MALLOC_ERROR, "Allocate ObjectMonitors"); } @@ -1006,12 +1006,12 @@ ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) { // linkage should be reconsidered. A better implementation would // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; } - for (int i = 1; i < _BLOCKSIZE ; i++) { + for (int i = 1; i < _BLOCKSIZE; i++) { temp[i].FreeNext = &temp[i+1]; } // terminate the last monitor as the end of list - temp[_BLOCKSIZE - 1].FreeNext = NULL ; + temp[_BLOCKSIZE - 1].FreeNext = NULL; // Element [0] is reserved for global list linkage temp[0].set_object(CHAINMARKER); @@ -1022,7 +1022,7 @@ ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) { // Acquire the ListLock to manipulate BlockList and FreeList. // An Oyama-Taura-Yonezawa scheme might be more efficient. - Thread::muxAcquire (&ListLock, "omAlloc [2]") ; + Thread::muxAcquire(&ListLock, "omAlloc [2]"); MonitorPopulation += _BLOCKSIZE-1; MonitorFreeCount += _BLOCKSIZE-1; @@ -1033,10 +1033,10 @@ ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) { gBlockList = temp; // Add the new string of objectMonitors to the global free list - temp[_BLOCKSIZE - 1].FreeNext = gFreeList ; + temp[_BLOCKSIZE - 1].FreeNext = gFreeList; gFreeList = temp + 1; - Thread::muxRelease (&ListLock) ; - TEVENT (Allocate block of monitors) ; + Thread::muxRelease(&ListLock); + TEVENT(Allocate block of monitors); } } @@ -1049,12 +1049,12 @@ ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) { // void ObjectSynchronizer::omRelease (Thread * Self, ObjectMonitor * m, bool fromPerThreadAlloc) { - guarantee (m->object() == NULL, "invariant") ; + guarantee(m->object() == NULL, "invariant"); // Remove from omInUseList if (MonitorInUseLists && fromPerThreadAlloc) { ObjectMonitor* curmidinuse = NULL; - for (ObjectMonitor* mid = Self->omInUseList; mid != NULL; ) { + for (ObjectMonitor* mid = Self->omInUseList; mid != NULL;) { if (m == mid) { // extract from per-thread in-use-list if (mid == Self->omInUseList) { @@ -1062,7 +1062,7 @@ void ObjectSynchronizer::omRelease (Thread * Self, ObjectMonitor * m, bool fromP } else if (curmidinuse != NULL) { curmidinuse->FreeNext = mid->FreeNext; // maintain the current thread inuselist } - Self->omInUseCount --; + Self->omInUseCount--; // verifyInUse(Self); break; } else { @@ -1073,9 +1073,9 @@ void ObjectSynchronizer::omRelease (Thread * Self, ObjectMonitor * m, bool fromP } // FreeNext is used for both onInUseList and omFreeList, so clear old before setting new - m->FreeNext = Self->omFreeList ; - Self->omFreeList = m ; - Self->omFreeCount ++ ; + m->FreeNext = Self->omFreeList; + Self->omFreeList = m; + Self->omFreeCount++; } // Return the monitors of a moribund thread's local free list to @@ -1099,25 +1099,25 @@ void ObjectSynchronizer::omRelease (Thread * Self, ObjectMonitor * m, bool fromP // operator. void ObjectSynchronizer::omFlush (Thread * Self) { - ObjectMonitor * List = Self->omFreeList ; // Null-terminated SLL - Self->omFreeList = NULL ; - ObjectMonitor * Tail = NULL ; + ObjectMonitor * List = Self->omFreeList; // Null-terminated SLL + Self->omFreeList = NULL; + ObjectMonitor * Tail = NULL; int Tally = 0; if (List != NULL) { - ObjectMonitor * s ; - for (s = List ; s != NULL ; s = s->FreeNext) { - Tally ++ ; - Tail = s ; - guarantee (s->object() == NULL, "invariant") ; - guarantee (!s->is_busy(), "invariant") ; - s->set_owner (NULL) ; // redundant but good hygiene - TEVENT (omFlush - Move one) ; + ObjectMonitor * s; + for (s = List; s != NULL; s = s->FreeNext) { + Tally++; + Tail = s; + guarantee(s->object() == NULL, "invariant"); + guarantee(!s->is_busy(), "invariant"); + s->set_owner(NULL); // redundant but good hygiene + TEVENT(omFlush - Move one); } - guarantee (Tail != NULL && List != NULL, "invariant") ; + guarantee(Tail != NULL && List != NULL, "invariant"); } ObjectMonitor * InUseList = Self->omInUseList; - ObjectMonitor * InUseTail = NULL ; + ObjectMonitor * InUseTail = NULL; int InUseTally = 0; if (InUseList != NULL) { Self->omInUseList = NULL; @@ -1129,13 +1129,13 @@ void ObjectSynchronizer::omFlush (Thread * Self) { // TODO debug assert(Self->omInUseCount == InUseTally, "inuse count off"); Self->omInUseCount = 0; - guarantee (InUseTail != NULL && InUseList != NULL, "invariant"); + guarantee(InUseTail != NULL && InUseList != NULL, "invariant"); } - Thread::muxAcquire (&ListLock, "omFlush") ; + Thread::muxAcquire(&ListLock, "omFlush"); if (Tail != NULL) { - Tail->FreeNext = gFreeList ; - gFreeList = List ; + Tail->FreeNext = gFreeList; + gFreeList = List; MonitorFreeCount += Tally; } @@ -1145,8 +1145,8 @@ void ObjectSynchronizer::omFlush (Thread * Self) { gOmInUseCount += InUseTally; } - Thread::muxRelease (&ListLock) ; - TEVENT (omFlush) ; + Thread::muxRelease(&ListLock); + TEVENT(omFlush); } // Fast path code shared by multiple functions @@ -1168,12 +1168,12 @@ ObjectMonitor* ObjectSynchronizer::inflate_helper(oop obj) { ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) { // Inflate mutates the heap ... // Relaxing assertion for bug 6320749. - assert (Universe::verify_in_progress() || - !SafepointSynchronize::is_at_safepoint(), "invariant") ; + assert(Universe::verify_in_progress() || + !SafepointSynchronize::is_at_safepoint(), "invariant"); for (;;) { - const markOop mark = object->mark() ; - assert (!mark->has_bias_pattern(), "invariant") ; + const markOop mark = object->mark(); + assert(!mark->has_bias_pattern(), "invariant"); // The mark can be in one of the following states: // * Inflated - just return @@ -1184,11 +1184,11 @@ ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) { // CASE: inflated if (mark->has_monitor()) { - ObjectMonitor * inf = mark->monitor() ; - assert (inf->header()->is_neutral(), "invariant"); - assert (inf->object() == object, "invariant") ; - assert (ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid"); - return inf ; + ObjectMonitor * inf = mark->monitor(); + assert(inf->header()->is_neutral(), "invariant"); + assert(inf->object() == object, "invariant"); + assert(ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid"); + return inf; } // CASE: inflation in progress - inflating over a stack-lock. @@ -1198,9 +1198,9 @@ ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) { // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish. // We could always eliminate polling by parking the thread on some auxiliary list. if (mark == markOopDesc::INFLATING()) { - TEVENT (Inflate: spin while INFLATING) ; - ReadStableMark(object) ; - continue ; + TEVENT(Inflate: spin while INFLATING); + ReadStableMark(object); + continue; } // CASE: stack-locked @@ -1223,20 +1223,20 @@ ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) { // See the comments in omAlloc(). if (mark->has_locker()) { - ObjectMonitor * m = omAlloc (Self) ; + ObjectMonitor * m = omAlloc(Self); // Optimistically prepare the objectmonitor - anticipate successful CAS // We do this before the CAS in order to minimize the length of time // in which INFLATING appears in the mark. m->Recycle(); - m->_Responsible = NULL ; - m->OwnerIsThread = 0 ; - m->_recursions = 0 ; - m->_SpinDuration = ObjectMonitor::Knob_SpinLimit ; // Consider: maintain by type/class + m->_Responsible = NULL; + m->OwnerIsThread = 0; + m->_recursions = 0; + m->_SpinDuration = ObjectMonitor::Knob_SpinLimit; // Consider: maintain by type/class - markOop cmp = (markOop) Atomic::cmpxchg_ptr (markOopDesc::INFLATING(), object->mark_addr(), mark) ; + markOop cmp = (markOop) Atomic::cmpxchg_ptr(markOopDesc::INFLATING(), object->mark_addr(), mark); if (cmp != mark) { - omRelease (Self, m, true) ; - continue ; // Interference -- just retry + omRelease(Self, m, true); + continue; // Interference -- just retry } // We've successfully installed INFLATING (0) into the mark-word. @@ -1269,11 +1269,11 @@ ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) { // The owner can't die or unwind past the lock while our INFLATING // object is in the mark. Furthermore the owner can't complete // an unlock on the object, either. - markOop dmw = mark->displaced_mark_helper() ; - assert (dmw->is_neutral(), "invariant") ; + markOop dmw = mark->displaced_mark_helper(); + assert(dmw->is_neutral(), "invariant"); // Setup monitor fields to proper values -- prepare the monitor - m->set_header(dmw) ; + m->set_header(dmw); // Optimization: if the mark->locker stack address is associated // with this thread we could simply set m->_owner = Self and @@ -1286,13 +1286,13 @@ ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) { // Must preserve store ordering. The monitor state must // be stable at the time of publishing the monitor address. - guarantee (object->mark() == markOopDesc::INFLATING(), "invariant") ; + guarantee(object->mark() == markOopDesc::INFLATING(), "invariant"); object->release_set_mark(markOopDesc::encode(m)); // Hopefully the performance counters are allocated on distinct cache lines // to avoid false sharing on MP systems ... - if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc() ; - TEVENT(Inflate: overwrite stacklock) ; + if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc(); + TEVENT(Inflate: overwrite stacklock); if (TraceMonitorInflation) { if (object->is_instance()) { ResourceMark rm; @@ -1301,7 +1301,7 @@ ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) { object->klass()->external_name()); } } - return m ; + return m; } // CASE: neutral @@ -1314,26 +1314,26 @@ ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) { // An inflateTry() method that we could call from fast_enter() and slow_enter() // would be useful. - assert (mark->is_neutral(), "invariant"); - ObjectMonitor * m = omAlloc (Self) ; + assert(mark->is_neutral(), "invariant"); + ObjectMonitor * m = omAlloc(Self); // prepare m for installation - set monitor to initial state m->Recycle(); m->set_header(mark); m->set_owner(NULL); m->set_object(object); - m->OwnerIsThread = 1 ; - m->_recursions = 0 ; - m->_Responsible = NULL ; - m->_SpinDuration = ObjectMonitor::Knob_SpinLimit ; // consider: keep metastats by type/class + m->OwnerIsThread = 1; + m->_recursions = 0; + m->_Responsible = NULL; + m->_SpinDuration = ObjectMonitor::Knob_SpinLimit; // consider: keep metastats by type/class if (Atomic::cmpxchg_ptr (markOopDesc::encode(m), object->mark_addr(), mark) != mark) { - m->set_object (NULL) ; - m->set_owner (NULL) ; - m->OwnerIsThread = 0 ; - m->Recycle() ; - omRelease (Self, m, true) ; - m = NULL ; - continue ; + m->set_object(NULL); + m->set_owner(NULL); + m->OwnerIsThread = 0; + m->Recycle(); + omRelease(Self, m, true); + m = NULL; + continue; // interference - the markword changed - just retry. // The state-transitions are one-way, so there's no chance of // live-lock -- "Inflated" is an absorbing state. @@ -1341,8 +1341,8 @@ ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) { // Hopefully the performance counters are allocated on distinct // cache lines to avoid false sharing on MP systems ... - if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc() ; - TEVENT(Inflate: overwrite neutral) ; + if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc(); + TEVENT(Inflate: overwrite neutral); if (TraceMonitorInflation) { if (object->is_instance()) { ResourceMark rm; @@ -1351,7 +1351,7 @@ ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) { object->klass()->external_name()); } } - return m ; + return m; } } @@ -1391,7 +1391,7 @@ ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) { enum ManifestConstants { ClearResponsibleAtSTW = 0, MaximumRecheckInterval = 1000 -} ; +}; // Deflate a single monitor if not in use // Return true if deflated, false if in use @@ -1399,18 +1399,18 @@ bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj, ObjectMonitor** FreeHeadp, ObjectMonitor** FreeTailp) { bool deflated; // Normal case ... The monitor is associated with obj. - guarantee (obj->mark() == markOopDesc::encode(mid), "invariant") ; - guarantee (mid == obj->mark()->monitor(), "invariant"); - guarantee (mid->header()->is_neutral(), "invariant"); + guarantee(obj->mark() == markOopDesc::encode(mid), "invariant"); + guarantee(mid == obj->mark()->monitor(), "invariant"); + guarantee(mid->header()->is_neutral(), "invariant"); if (mid->is_busy()) { - if (ClearResponsibleAtSTW) mid->_Responsible = NULL ; + if (ClearResponsibleAtSTW) mid->_Responsible = NULL; deflated = false; } else { // Deflate the monitor if it is no longer being used // It's idle - scavenge and return to the global free list // plain old deflation ... - TEVENT (deflate_idle_monitors - scavenge1) ; + TEVENT(deflate_idle_monitors - scavenge1); if (TraceMonitorInflation) { if (obj->is_instance()) { ResourceMark rm; @@ -1423,7 +1423,7 @@ bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj, obj->release_set_mark(mid->header()); mid->clear(); - assert (mid->object() == NULL, "invariant") ; + assert(mid->object() == NULL, "invariant"); // Move the object to the working free list defined by FreeHead,FreeTail. if (*FreeHeadp == NULL) *FreeHeadp = mid; @@ -1446,7 +1446,7 @@ int ObjectSynchronizer::walk_monitor_list(ObjectMonitor** listheadp, ObjectMonitor* curmidinuse = NULL; int deflatedcount = 0; - for (mid = *listheadp; mid != NULL; ) { + for (mid = *listheadp; mid != NULL;) { oop obj = (oop) mid->object(); bool deflated = false; if (obj != NULL) { @@ -1473,19 +1473,19 @@ int ObjectSynchronizer::walk_monitor_list(ObjectMonitor** listheadp, void ObjectSynchronizer::deflate_idle_monitors() { assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); - int nInuse = 0 ; // currently associated with objects - int nInCirculation = 0 ; // extant - int nScavenged = 0 ; // reclaimed + int nInuse = 0; // currently associated with objects + int nInCirculation = 0; // extant + int nScavenged = 0; // reclaimed bool deflated = false; - ObjectMonitor * FreeHead = NULL ; // Local SLL of scavenged monitors - ObjectMonitor * FreeTail = NULL ; + ObjectMonitor * FreeHead = NULL; // Local SLL of scavenged monitors + ObjectMonitor * FreeTail = NULL; - TEVENT (deflate_idle_monitors) ; + TEVENT(deflate_idle_monitors); // Prevent omFlush from changing mids in Thread dtor's during deflation // And in case the vm thread is acquiring a lock during a safepoint // See e.g. 6320749 - Thread::muxAcquire (&ListLock, "scavenge - return") ; + Thread::muxAcquire(&ListLock, "scavenge - return"); if (MonitorInUseLists) { int inUse = 0; @@ -1510,8 +1510,8 @@ void ObjectSynchronizer::deflate_idle_monitors() { } else for (ObjectMonitor* block = gBlockList; block != NULL; block = next(block)) { // Iterate over all extant monitors - Scavenge all idle monitors. assert(block->object() == CHAINMARKER, "must be a block header"); - nInCirculation += _BLOCKSIZE ; - for (int i = 1 ; i < _BLOCKSIZE; i++) { + nInCirculation += _BLOCKSIZE; + for (int i = 1; i < _BLOCKSIZE; i++) { ObjectMonitor* mid = &block[i]; oop obj = (oop) mid->object(); @@ -1520,16 +1520,16 @@ void ObjectSynchronizer::deflate_idle_monitors() { // The monitor should either be a thread-specific private // free list or the global free list. // obj == NULL IMPLIES mid->is_busy() == 0 - guarantee (!mid->is_busy(), "invariant") ; - continue ; + guarantee(!mid->is_busy(), "invariant"); + continue; } deflated = deflate_monitor(mid, obj, &FreeHead, &FreeTail); if (deflated) { - mid->FreeNext = NULL ; - nScavenged ++ ; + mid->FreeNext = NULL; + nScavenged++; } else { - nInuse ++; + nInuse++; } } } @@ -1539,31 +1539,31 @@ void ObjectSynchronizer::deflate_idle_monitors() { // Consider: audit gFreeList to ensure that MonitorFreeCount and list agree. if (ObjectMonitor::Knob_Verbose) { - ::printf ("Deflate: InCirc=%d InUse=%d Scavenged=%d ForceMonitorScavenge=%d : pop=%d free=%d\n", + ::printf("Deflate: InCirc=%d InUse=%d Scavenged=%d ForceMonitorScavenge=%d : pop=%d free=%d\n", nInCirculation, nInuse, nScavenged, ForceMonitorScavenge, - MonitorPopulation, MonitorFreeCount) ; - ::fflush(stdout) ; + MonitorPopulation, MonitorFreeCount); + ::fflush(stdout); } ForceMonitorScavenge = 0; // Reset // Move the scavenged monitors back to the global free list. if (FreeHead != NULL) { - guarantee (FreeTail != NULL && nScavenged > 0, "invariant") ; - assert (FreeTail->FreeNext == NULL, "invariant") ; + guarantee(FreeTail != NULL && nScavenged > 0, "invariant"); + assert(FreeTail->FreeNext == NULL, "invariant"); // constant-time list splice - prepend scavenged segment to gFreeList - FreeTail->FreeNext = gFreeList ; - gFreeList = FreeHead ; + FreeTail->FreeNext = gFreeList; + gFreeList = FreeHead; } - Thread::muxRelease (&ListLock) ; + Thread::muxRelease(&ListLock); - if (ObjectMonitor::_sync_Deflations != NULL) ObjectMonitor::_sync_Deflations->inc(nScavenged) ; + if (ObjectMonitor::_sync_Deflations != NULL) ObjectMonitor::_sync_Deflations->inc(nScavenged); if (ObjectMonitor::_sync_MonExtant != NULL) ObjectMonitor::_sync_MonExtant ->set_value(nInCirculation); // TODO: Add objectMonitor leak detection. // Audit/inventory the objectMonitors -- make sure they're all accounted for. - GVars.stwRandom = os::random() ; - GVars.stwCycle ++ ; + GVars.stwRandom = os::random(); + GVars.stwCycle++; } // Monitor cleanup on JavaThread::exit @@ -1601,7 +1601,7 @@ public: void ObjectSynchronizer::release_monitors_owned_by_thread(TRAPS) { assert(THREAD == JavaThread::current(), "must be current Java thread"); - No_Safepoint_Verifier nsv ; + No_Safepoint_Verifier nsv; ReleaseJavaMonitorsClosure rjmc(THREAD); Thread::muxAcquire(&ListLock, "release_monitors_owned_by_thread"); ObjectSynchronizer::monitors_iterate(&rjmc); diff --git a/hotspot/src/share/vm/runtime/synchronizer.hpp b/hotspot/src/share/vm/runtime/synchronizer.hpp index 4f95b31350d..bf3959be688 100644 --- a/hotspot/src/share/vm/runtime/synchronizer.hpp +++ b/hotspot/src/share/vm/runtime/synchronizer.hpp @@ -75,7 +75,7 @@ class ObjectSynchronizer : AllStatic { // Special internal-use-only method for use by JVM infrastructure // that needs to wait() on a java-level object but that can't risk // throwing unexpected InterruptedExecutionExceptions. - static void waitUninterruptibly (Handle obj, jlong Millis, Thread * THREAD) ; + static void waitUninterruptibly(Handle obj, jlong Millis, Thread * THREAD); // used by classloading to free classloader object lock, // wait on an internal lock, and reclaim original lock @@ -85,9 +85,9 @@ class ObjectSynchronizer : AllStatic { // thread-specific and global objectMonitor free list accessors // static void verifyInUse (Thread * Self) ; too slow for general assert/debug - static ObjectMonitor * omAlloc (Thread * Self) ; - static void omRelease (Thread * Self, ObjectMonitor * m, bool FromPerThreadAlloc) ; - static void omFlush (Thread * Self) ; + static ObjectMonitor * omAlloc(Thread * Self); + static void omRelease(Thread * Self, ObjectMonitor * m, bool FromPerThreadAlloc); + static void omFlush(Thread * Self); // Inflate light weight monitor to heavy weight monitor static ObjectMonitor* inflate(Thread * Self, oop obj); @@ -97,7 +97,7 @@ class ObjectSynchronizer : AllStatic { // Returns the identity hash value for an oop // NOTE: It may cause monitor inflation static intptr_t identity_hash_value_for(Handle obj); - static intptr_t FastHashCode (Thread * Self, oop obj) ; + static intptr_t FastHashCode(Thread * Self, oop obj); // java.lang.Thread support static bool current_thread_holds_lock(JavaThread* thread, Handle h_obj); @@ -124,7 +124,7 @@ class ObjectSynchronizer : AllStatic { static void verify() PRODUCT_RETURN; static int verify_objmon_isinpool(ObjectMonitor *addr) PRODUCT_RETURN0; - static void RegisterSpinCallback (int (*)(intptr_t, int), intptr_t) ; + static void RegisterSpinCallback(int(*)(intptr_t, int), intptr_t); private: enum { _BLOCKSIZE = 128 }; @@ -155,7 +155,7 @@ class ObjectLocker : public StackObj { // Monitor behavior void wait (TRAPS) { ObjectSynchronizer::wait (_obj, 0, CHECK); } // wait forever void notify_all(TRAPS) { ObjectSynchronizer::notifyall(_obj, CHECK); } - void waitUninterruptibly (TRAPS) { ObjectSynchronizer::waitUninterruptibly (_obj, 0, CHECK);} + void waitUninterruptibly (TRAPS) { ObjectSynchronizer::waitUninterruptibly (_obj, 0, CHECK); } // complete_exit gives up lock completely, returning recursion count // reenter reclaims lock with original recursion count intptr_t complete_exit(TRAPS) { return ObjectSynchronizer::complete_exit(_obj, CHECK_0); } diff --git a/hotspot/src/share/vm/runtime/thread.cpp b/hotspot/src/share/vm/runtime/thread.cpp index e9e9d22f197..7031620a283 100644 --- a/hotspot/src/share/vm/runtime/thread.cpp +++ b/hotspot/src/share/vm/runtime/thread.cpp @@ -225,11 +225,11 @@ Thread::Thread() { _current_pending_monitor_is_from_java = true; _current_waiting_monitor = NULL; _num_nested_signal = 0; - omFreeList = NULL ; - omFreeCount = 0 ; - omFreeProvision = 32 ; - omInUseList = NULL ; - omInUseCount = 0 ; + omFreeList = NULL; + omFreeCount = 0; + omFreeProvision = 32; + omInUseList = NULL; + omInUseCount = 0; #ifdef ASSERT _visited_for_critical_count = false; @@ -239,15 +239,15 @@ Thread::Thread() { _suspend_flags = 0; // thread-specific hashCode stream generator state - Marsaglia shift-xor form - _hashStateX = os::random() ; - _hashStateY = 842502087 ; - _hashStateZ = 0x8767 ; // (int)(3579807591LL & 0xffff) ; - _hashStateW = 273326509 ; + _hashStateX = os::random(); + _hashStateY = 842502087; + _hashStateZ = 0x8767; // (int)(3579807591LL & 0xffff) ; + _hashStateW = 273326509; - _OnTrap = 0 ; - _schedctl = NULL ; - _Stalled = 0 ; - _TypeTag = 0x2BAD ; + _OnTrap = 0; + _schedctl = NULL; + _Stalled = 0; + _TypeTag = 0x2BAD; // Many of the following fields are effectively final - immutable // Note that nascent threads can't use the Native Monitor-Mutex @@ -256,10 +256,10 @@ Thread::Thread() { // we might instead use a stack of ParkEvents that we could provision on-demand. // The stack would act as a cache to avoid calls to ParkEvent::Allocate() // and ::Release() - _ParkEvent = ParkEvent::Allocate (this) ; - _SleepEvent = ParkEvent::Allocate (this) ; - _MutexEvent = ParkEvent::Allocate (this) ; - _MuxEvent = ParkEvent::Allocate (this) ; + _ParkEvent = ParkEvent::Allocate(this); + _SleepEvent = ParkEvent::Allocate(this); + _MutexEvent = ParkEvent::Allocate(this); + _MuxEvent = ParkEvent::Allocate(this); #ifdef CHECK_UNHANDLED_OOPS if (CheckUnhandledOops) { @@ -314,7 +314,7 @@ void Thread::record_stack_base_and_size() { Thread::~Thread() { // Reclaim the objectmonitors from the omFreeList of the moribund thread. - ObjectSynchronizer::omFlush (this) ; + ObjectSynchronizer::omFlush(this); EVENT_THREAD_DESTRUCT(this); @@ -342,10 +342,10 @@ Thread::~Thread() { // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads. // We NULL out the fields for good hygiene. - ParkEvent::Release (_ParkEvent) ; _ParkEvent = NULL ; - ParkEvent::Release (_SleepEvent) ; _SleepEvent = NULL ; - ParkEvent::Release (_MutexEvent) ; _MutexEvent = NULL ; - ParkEvent::Release (_MuxEvent) ; _MuxEvent = NULL ; + ParkEvent::Release(_ParkEvent); _ParkEvent = NULL; + ParkEvent::Release(_SleepEvent); _SleepEvent = NULL; + ParkEvent::Release(_MutexEvent); _MutexEvent = NULL; + ParkEvent::Release(_MuxEvent); _MuxEvent = NULL; delete handle_area(); delete metadata_handles(); @@ -844,7 +844,7 @@ void Thread::print_on(outputStream* st) const { // Thread::print_on_error() is called by fatal error handler. Don't use // any lock or allocate memory. void Thread::print_on_error(outputStream* st, char* buf, int buflen) const { - if (is_VM_thread()) st->print("VMThread"); + if (is_VM_thread()) st->print("VMThread"); else if (is_Compiler_thread()) st->print("CompilerThread"); else if (is_Java_thread()) st->print("JavaThread"); else if (is_GC_task_thread()) st->print("GCTaskThread"); @@ -867,7 +867,7 @@ void Thread::print_owned_locks_on(outputStream* st) const { st->print(" (no locks) "); } else { st->print_cr(" Locks owned:"); - while(cur) { + while (cur) { cur->print_on(st); cur = cur->next(); } @@ -877,7 +877,7 @@ void Thread::print_owned_locks_on(outputStream* st) const { static int ref_use_count = 0; bool Thread::owns_locks_but_compiled_lock() const { - for(Monitor *cur = _owned_locks; cur; cur = cur->next()) { + for (Monitor *cur = _owned_locks; cur; cur = cur->next()) { if (cur != Compile_lock) return true; } return false; @@ -904,12 +904,12 @@ void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) { && !Universe::is_bootstrapping()) { // Make sure we do not hold any locks that the VM thread also uses. // This could potentially lead to deadlocks - for(Monitor *cur = _owned_locks; cur; cur = cur->next()) { + for (Monitor *cur = _owned_locks; cur; cur = cur->next()) { // Threads_lock is special, since the safepoint synchronization will not start before this is // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock, // since it is used to transfer control between JavaThreads and the VMThread // Do not *exclude* any locks unless you are absolutely sure it is correct. Ask someone else first! - if ( (cur->allow_vm_block() && + if ((cur->allow_vm_block() && cur != Threads_lock && cur != Compile_lock && // Temporary: should not be necessary when we get separate compilation cur != VMOperationRequest_lock && @@ -1291,9 +1291,9 @@ void WatcherThread::run() { this->record_stack_base_and_size(); this->initialize_thread_local_storage(); this->set_active_handles(JNIHandleBlock::allocate_block()); - while(!_should_terminate) { - assert(watcher_thread() == Thread::current(), "thread consistency check"); - assert(watcher_thread() == this, "thread consistency check"); + while (!_should_terminate) { + assert(watcher_thread() == Thread::current(), "thread consistency check"); + assert(watcher_thread() == this, "thread consistency check"); // Calculate how long it'll be until the next PeriodicTask work // should be done, and sleep that amount of time. @@ -1370,7 +1370,7 @@ void WatcherThread::stop() { // it is ok to take late safepoints here, if needed MutexLocker mu(Terminator_lock); - while(watcher_thread() != NULL) { + while (watcher_thread() != NULL) { // This wait should make safepoint checks, wait without a timeout, // and wait as a suspend-equivalent condition. // @@ -1448,13 +1448,14 @@ void JavaThread::initialize() { _thread_stat = new ThreadStatistics(); _blocked_on_compilation = false; _jni_active_critical = 0; + _pending_jni_exception_check_fn = NULL; _do_not_unlock_if_synchronized = false; _cached_monitor_info = NULL; - _parker = Parker::Allocate(this) ; + _parker = Parker::Allocate(this); #ifndef PRODUCT _jmp_ring_index = 0; - for (int ji = 0 ; ji < jump_ring_buffer_size ; ji++ ) { + for (int ji = 0; ji < jump_ring_buffer_size; ji++) { record_jump(NULL, NULL, NULL, 0); } #endif /* PRODUCT */ @@ -1591,7 +1592,7 @@ JavaThread::~JavaThread() { // JSR166 -- return the parker to the free list Parker::Release(_parker); - _parker = NULL ; + _parker = NULL; // Free any remaining previous UnrollBlock vframeArray* old_array = vframe_array_last(); @@ -1717,7 +1718,7 @@ static void ensure_join(JavaThread* thread) { // For any new cleanup additions, please check to see if they need to be applied to // cleanup_failed_attach_current_thread as well. void JavaThread::exit(bool destroy_vm, ExitType exit_type) { - assert(this == JavaThread::current(), "thread consistency check"); + assert(this == JavaThread::current(), "thread consistency check"); HandleMark hm(this); Handle uncaught_exception(this, this->pending_exception()); @@ -1738,55 +1739,26 @@ void JavaThread::exit(bool destroy_vm, ExitType exit_type) { CLEAR_PENDING_EXCEPTION; } - // FIXIT: The is_null check is only so it works better on JDK1.2 VM's. This - // has to be fixed by a runtime query method - if (!destroy_vm || JDK_Version::is_jdk12x_version()) { - // JSR-166: change call from from ThreadGroup.uncaughtException to - // java.lang.Thread.dispatchUncaughtException + if (!destroy_vm) { if (uncaught_exception.not_null()) { - Handle group(this, java_lang_Thread::threadGroup(threadObj())); - { - EXCEPTION_MARK; - // Check if the method Thread.dispatchUncaughtException() exists. If so - // call it. Otherwise we have an older library without the JSR-166 changes, - // so call ThreadGroup.uncaughtException() - KlassHandle recvrKlass(THREAD, threadObj->klass()); - CallInfo callinfo; - KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass()); - LinkResolver::resolve_virtual_call(callinfo, threadObj, recvrKlass, thread_klass, - vmSymbols::dispatchUncaughtException_name(), - vmSymbols::throwable_void_signature(), - KlassHandle(), false, false, THREAD); + EXCEPTION_MARK; + // Call method Thread.dispatchUncaughtException(). + KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass()); + JavaValue result(T_VOID); + JavaCalls::call_virtual(&result, + threadObj, thread_klass, + vmSymbols::dispatchUncaughtException_name(), + vmSymbols::throwable_void_signature(), + uncaught_exception, + THREAD); + if (HAS_PENDING_EXCEPTION) { + ResourceMark rm(this); + jio_fprintf(defaultStream::error_stream(), + "\nException: %s thrown from the UncaughtExceptionHandler" + " in thread \"%s\"\n", + pending_exception()->klass()->external_name(), + get_thread_name()); CLEAR_PENDING_EXCEPTION; - methodHandle method = callinfo.selected_method(); - if (method.not_null()) { - JavaValue result(T_VOID); - JavaCalls::call_virtual(&result, - threadObj, thread_klass, - vmSymbols::dispatchUncaughtException_name(), - vmSymbols::throwable_void_signature(), - uncaught_exception, - THREAD); - } else { - KlassHandle thread_group(THREAD, SystemDictionary::ThreadGroup_klass()); - JavaValue result(T_VOID); - JavaCalls::call_virtual(&result, - group, thread_group, - vmSymbols::uncaughtException_name(), - vmSymbols::thread_throwable_void_signature(), - threadObj, // Arg 1 - uncaught_exception, // Arg 2 - THREAD); - } - if (HAS_PENDING_EXCEPTION) { - ResourceMark rm(this); - jio_fprintf(defaultStream::error_stream(), - "\nException: %s thrown from the UncaughtExceptionHandler" - " in thread \"%s\"\n", - pending_exception()->klass()->external_name(), - get_thread_name()); - CLEAR_PENDING_EXCEPTION; - } } } @@ -2086,7 +2058,7 @@ void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) { if (TraceExceptions) { ResourceMark rm; tty->print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", this); - if (has_last_Java_frame() ) { + if (has_last_Java_frame()) { frame f = last_frame(); tty->print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", f.pc(), f.sp()); } @@ -2330,11 +2302,11 @@ int JavaThread::java_suspend_self() { void JavaThread::verify_not_published() { if (!Threads_lock->owned_by_self()) { MutexLockerEx ml(Threads_lock, Mutex::_no_safepoint_check_flag); - assert( !Threads::includes(this), + assert(!Threads::includes(this), "java thread shouldn't have been published yet!"); } else { - assert( !Threads::includes(this), + assert(!Threads::includes(this), "java thread shouldn't have been published yet!"); } } @@ -2403,7 +2375,7 @@ void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread thread->clear_deopt_suspend(); RegisterMap map(thread, false); frame f = thread->last_frame(); - while ( f.id() != thread->must_deopt_id() && ! f.is_first_frame()) { + while (f.id() != thread->must_deopt_id() && ! f.is_first_frame()) { f = f.sender(&map); } if (f.id() == thread->must_deopt_id()) { @@ -2527,8 +2499,8 @@ void JavaThread::enable_stack_yellow_zone() { // We need to adjust it to work correctly with guard_memory() address base = stack_yellow_zone_base() - stack_yellow_zone_size(); - guarantee(base < stack_base(),"Error calculating stack yellow zone"); - guarantee(base < os::current_stack_pointer(),"Error calculating stack yellow zone"); + guarantee(base < stack_base(), "Error calculating stack yellow zone"); + guarantee(base < os::current_stack_pointer(), "Error calculating stack yellow zone"); if (os::guard_memory((char *) base, stack_yellow_zone_size())) { _stack_guard_state = stack_guard_enabled; @@ -2563,10 +2535,10 @@ void JavaThread::enable_stack_red_zone() { assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); address base = stack_red_zone_base() - stack_red_zone_size(); - guarantee(base < stack_base(),"Error calculating stack red zone"); - guarantee(base < os::current_stack_pointer(),"Error calculating stack red zone"); + guarantee(base < stack_base(), "Error calculating stack red zone"); + guarantee(base < os::current_stack_pointer(), "Error calculating stack red zone"); - if(!os::guard_memory((char *) base, stack_red_zone_size())) { + if (!os::guard_memory((char *) base, stack_red_zone_size())) { warning("Attempt to guard stack red zone failed."); } } @@ -2585,7 +2557,7 @@ void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) { // ignore is there is no stack if (!has_last_Java_frame()) return; // traverse the stack frames. Starts from top frame. - for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { + for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { frame* fr = fst.current(); f(fr, fst.register_map()); } @@ -2601,8 +2573,8 @@ void JavaThread::deoptimize() { bool deopt = false; // Dump stack only if a deopt actually happens. bool only_at = strlen(DeoptimizeOnlyAt) > 0; // Iterate over all frames in the thread and deoptimize - for(; !fst.is_done(); fst.next()) { - if(fst.current()->can_be_deoptimized()) { + for (; !fst.is_done(); fst.next()) { + if (fst.current()->can_be_deoptimized()) { if (only_at) { // Deoptimize only at particular bcis. DeoptimizeOnlyAt @@ -2647,7 +2619,7 @@ void JavaThread::deoptimize() { // Make zombies void JavaThread::make_zombies() { - for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { + for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { if (fst.current()->can_be_deoptimized()) { // it is a Java nmethod nmethod* nm = CodeCache::find_nmethod(fst.current()->pc()); @@ -2662,7 +2634,7 @@ void JavaThread::deoptimized_wrt_marked_nmethods() { if (!has_last_Java_frame()) return; // BiasedLocking needs an updated RegisterMap for the revoke monitors pass StackFrameStream fst(this, UseBiasedLocking); - for(; !fst.is_done(); fst.next()) { + for (; !fst.is_done(); fst.next()) { if (fst.current()->should_be_deoptimized()) { if (LogCompilation && xtty != NULL) { nmethod* nm = fst.current()->cb()->as_nmethod_or_null(); @@ -2722,7 +2694,7 @@ void JavaThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) // Traverse the GCHandles Thread::oops_do(f, cld_f, cf); - assert( (!has_last_Java_frame() && java_call_counter() == 0) || + assert((!has_last_Java_frame() && java_call_counter() == 0) || (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!"); if (has_last_Java_frame()) { @@ -2747,7 +2719,7 @@ void JavaThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) } // Traverse the execution stack - for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { + for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { fst.current()->oops_do(f, cld_f, cf, fst.register_map()); } } @@ -2782,12 +2754,12 @@ void JavaThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) void JavaThread::nmethods_do(CodeBlobClosure* cf) { Thread::nmethods_do(cf); // (super method is a no-op) - assert( (!has_last_Java_frame() && java_call_counter() == 0) || + assert((!has_last_Java_frame() && java_call_counter() == 0) || (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!"); if (has_last_Java_frame()) { // Traverse the execution stack - for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { + for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { fst.current()->nmethods_do(cf); } } @@ -2797,7 +2769,7 @@ void JavaThread::metadata_do(void f(Metadata*)) { Thread::metadata_do(f); if (has_last_Java_frame()) { // Traverse the execution stack to call f() on the methods in the stack - for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { + for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { fst.current()->metadata_do(f); } } else if (is_Compiler_thread()) { @@ -2848,7 +2820,7 @@ void JavaThread::print_on(outputStream *st) const { Thread::print_on(st); // print guess for valid stack memory region (assume 4K pages); helps lock debugging st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12)); - if (thread_oop != NULL && JDK_Version::is_gte_jdk15x_version()) { + if (thread_oop != NULL) { st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop)); } #ifndef PRODUCT @@ -2860,7 +2832,7 @@ void JavaThread::print_on(outputStream *st) const { // Called by fatal error handler. The difference between this and // JavaThread::print() is that we can't grab lock or allocate memory. void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const { - st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen)); + st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen)); oop thread_obj = threadObj(); if (thread_obj != NULL) { if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon"); @@ -3043,7 +3015,7 @@ void JavaThread::print_stack_on(outputStream* st) { RegisterMap reg_map(this); vframe* start_vf = last_java_vframe(®_map); int count = 0; - for (vframe* f = start_vf; f; f = f->sender() ) { + for (vframe* f = start_vf; f; f = f->sender()) { if (f->is_java_frame()) { javaVFrame* jvf = javaVFrame::cast(f); java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci()); @@ -3099,9 +3071,9 @@ void JavaThread::popframe_free_preserved_args() { void JavaThread::trace_frames() { tty->print_cr("[Describe stack]"); int frame_no = 1; - for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { + for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { tty->print(" %d. ", frame_no++); - fst.current()->print_value_on(tty,this); + fst.current()->print_value_on(tty, this); tty->cr(); } } @@ -3152,7 +3124,7 @@ void JavaThread::print_frame_layout(int depth, bool validate_only) { PRESERVE_EXCEPTION_MARK; FrameValues values; int frame_no = 0; - for(StackFrameStream fst(this, false); !fst.is_done(); fst.next()) { + for (StackFrameStream fst(this, false); !fst.is_done(); fst.next()) { fst.current()->describe(values, ++frame_no); if (depth == frame_no) break; } @@ -3168,7 +3140,7 @@ void JavaThread::print_frame_layout(int depth, bool validate_only) { void JavaThread::trace_stack_from(vframe* start_vf) { ResourceMark rm; int vframe_no = 1; - for (vframe* f = start_vf; f; f = f->sender() ) { + for (vframe* f = start_vf; f; f = f->sender()) { if (f->is_java_frame()) { javaVFrame::cast(f)->print_activation(vframe_no++); } else { @@ -3197,7 +3169,7 @@ void JavaThread::trace_stack() { javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) { assert(reg_map != NULL, "a map must be given"); frame f = last_frame(); - for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender() ) { + for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) { if (vf->is_java_frame()) return javaVFrame::cast(vf); } return NULL; @@ -3319,7 +3291,7 @@ void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) { // The VM preresolves methods to these classes. Make sure that they get initialized initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK); - initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK); + initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK); call_initializeSystemClass(CHECK); // get the Java runtime name after java.lang.System is initialized @@ -3453,7 +3425,7 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { main_thread->create_stack_guard_pages(); // Initialize Java-Level synchronization subsystem - ObjectMonitor::Initialize() ; + ObjectMonitor::Initialize(); // Second phase of bootstrapping, VM is about entering multi-thread mode MemTracker::bootstrap_multi_thread(); @@ -3501,7 +3473,7 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { } } - assert (Universe::is_fully_initialized(), "not initialized"); + assert(Universe::is_fully_initialized(), "not initialized"); if (VerifyDuringStartup) { // Make sure we're starting with a clean slate. VM_Verify verify_op; @@ -3927,7 +3899,7 @@ bool Threads::destroy_vm() { #endif // Wait until we are the last non-daemon thread to execute { MutexLocker nu(Threads_lock); - while (Threads::number_of_non_daemon_threads() > 1 ) + while (Threads::number_of_non_daemon_threads() > 1) // This wait should make safepoint checks, wait without a timeout, // and wait as a suspend-equivalent condition. // @@ -3948,15 +3920,8 @@ bool Threads::destroy_vm() { } os::wait_for_keypress_at_exit(); - if (JDK_Version::is_jdk12x_version()) { - // We are the last thread running, so check if finalizers should be run. - // For 1.3 or later this is done in thread->invoke_shutdown_hooks() - HandleMark rm(thread); - Universe::run_finalizers_on_exit(); - } else { - // run Java level shutdown hooks - thread->invoke_shutdown_hooks(); - } + // run Java level shutdown hooks + thread->invoke_shutdown_hooks(); before_exit(thread); @@ -3968,14 +3933,8 @@ bool Threads::destroy_vm() { // GC vm_operations can get caught at the safepoint, and the // heap is unparseable if they are caught. Grab the Heap_lock // to prevent this. The GC vm_operations will not be able to - // queue until after the vm thread is dead. - // After this point, we'll never emerge out of the safepoint before - // the VM exits, so concurrent GC threads do not need to be explicitly - // stopped; they remain inactive until the process exits. - // Note: some concurrent G1 threads may be running during a safepoint, - // but these will not be accessing the heap, just some G1-specific side - // data structures that are not accessed by any other threads but them - // after this point in a terminal safepoint. + // queue until after the vm thread is dead. After this point, + // we'll never emerge out of the safepoint before the VM exits. MutexLocker ml(Heap_lock); @@ -4113,7 +4072,7 @@ void Threads::remove(JavaThread* p) { bool Threads::includes(JavaThread* p) { assert(Threads_lock->is_locked(), "sanity check"); ALL_JAVA_THREADS(q) { - if (q == p ) { + if (q == p) { return true; } } @@ -4398,43 +4357,43 @@ void Threads::print_on_error(outputStream* st, Thread* current, char* buf, int b // cache-coherency traffic. -typedef volatile int SpinLockT ; +typedef volatile int SpinLockT; void Thread::SpinAcquire (volatile int * adr, const char * LockName) { if (Atomic::cmpxchg (1, adr, 0) == 0) { - return ; // normal fast-path return + return; // normal fast-path return } // Slow-path : We've encountered contention -- Spin/Yield/Block strategy. - TEVENT (SpinAcquire - ctx) ; - int ctr = 0 ; - int Yields = 0 ; + TEVENT(SpinAcquire - ctx); + int ctr = 0; + int Yields = 0; for (;;) { while (*adr != 0) { - ++ctr ; + ++ctr; if ((ctr & 0xFFF) == 0 || !os::is_MP()) { if (Yields > 5) { os::naked_short_sleep(1); } else { - os::NakedYield() ; - ++Yields ; + os::NakedYield(); + ++Yields; } } else { - SpinPause() ; + SpinPause(); } } - if (Atomic::cmpxchg (1, adr, 0) == 0) return ; + if (Atomic::cmpxchg(1, adr, 0) == 0) return; } } void Thread::SpinRelease (volatile int * adr) { - assert (*adr != 0, "invariant") ; - OrderAccess::fence() ; // guarantee at least release consistency. + assert(*adr != 0, "invariant"); + OrderAccess::fence(); // guarantee at least release consistency. // Roach-motel semantics. // It's safe if subsequent LDs and STs float "up" into the critical section, // but prior LDs and STs within the critical section can't be allowed // to reorder or float past the ST that releases the lock. - *adr = 0 ; + *adr = 0; } // muxAcquire and muxRelease: @@ -4487,111 +4446,111 @@ void Thread::SpinRelease (volatile int * adr) { // -typedef volatile intptr_t MutexT ; // Mux Lock-word -enum MuxBits { LOCKBIT = 1 } ; +typedef volatile intptr_t MutexT; // Mux Lock-word +enum MuxBits { LOCKBIT = 1 }; void Thread::muxAcquire (volatile intptr_t * Lock, const char * LockName) { - intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ; - if (w == 0) return ; + intptr_t w = Atomic::cmpxchg_ptr(LOCKBIT, Lock, 0); + if (w == 0) return; if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { - return ; + return; } - TEVENT (muxAcquire - Contention) ; - ParkEvent * const Self = Thread::current()->_MuxEvent ; - assert ((intptr_t(Self) & LOCKBIT) == 0, "invariant") ; + TEVENT(muxAcquire - Contention); + ParkEvent * const Self = Thread::current()->_MuxEvent; + assert((intptr_t(Self) & LOCKBIT) == 0, "invariant"); for (;;) { - int its = (os::is_MP() ? 100 : 0) + 1 ; + int its = (os::is_MP() ? 100 : 0) + 1; // Optional spin phase: spin-then-park strategy while (--its >= 0) { - w = *Lock ; + w = *Lock; if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { - return ; + return; } } - Self->reset() ; - Self->OnList = intptr_t(Lock) ; + Self->reset(); + Self->OnList = intptr_t(Lock); // The following fence() isn't _strictly necessary as the subsequent // CAS() both serializes execution and ratifies the fetched *Lock value. OrderAccess::fence(); for (;;) { - w = *Lock ; + w = *Lock; if ((w & LOCKBIT) == 0) { if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { - Self->OnList = 0 ; // hygiene - allows stronger asserts - return ; + Self->OnList = 0; // hygiene - allows stronger asserts + return; } - continue ; // Interference -- *Lock changed -- Just retry + continue; // Interference -- *Lock changed -- Just retry } - assert (w & LOCKBIT, "invariant") ; - Self->ListNext = (ParkEvent *) (w & ~LOCKBIT ); - if (Atomic::cmpxchg_ptr (intptr_t(Self)|LOCKBIT, Lock, w) == w) break ; + assert(w & LOCKBIT, "invariant"); + Self->ListNext = (ParkEvent *) (w & ~LOCKBIT); + if (Atomic::cmpxchg_ptr(intptr_t(Self)|LOCKBIT, Lock, w) == w) break; } while (Self->OnList != 0) { - Self->park() ; + Self->park(); } } } void Thread::muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) { - intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ; - if (w == 0) return ; + intptr_t w = Atomic::cmpxchg_ptr(LOCKBIT, Lock, 0); + if (w == 0) return; if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { - return ; + return; } - TEVENT (muxAcquire - Contention) ; - ParkEvent * ReleaseAfter = NULL ; + TEVENT(muxAcquire - Contention); + ParkEvent * ReleaseAfter = NULL; if (ev == NULL) { - ev = ReleaseAfter = ParkEvent::Allocate (NULL) ; + ev = ReleaseAfter = ParkEvent::Allocate(NULL); } - assert ((intptr_t(ev) & LOCKBIT) == 0, "invariant") ; + assert((intptr_t(ev) & LOCKBIT) == 0, "invariant"); for (;;) { - guarantee (ev->OnList == 0, "invariant") ; - int its = (os::is_MP() ? 100 : 0) + 1 ; + guarantee(ev->OnList == 0, "invariant"); + int its = (os::is_MP() ? 100 : 0) + 1; // Optional spin phase: spin-then-park strategy while (--its >= 0) { - w = *Lock ; + w = *Lock; if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { if (ReleaseAfter != NULL) { - ParkEvent::Release (ReleaseAfter) ; + ParkEvent::Release(ReleaseAfter); } - return ; + return; } } - ev->reset() ; - ev->OnList = intptr_t(Lock) ; + ev->reset(); + ev->OnList = intptr_t(Lock); // The following fence() isn't _strictly necessary as the subsequent // CAS() both serializes execution and ratifies the fetched *Lock value. OrderAccess::fence(); for (;;) { - w = *Lock ; + w = *Lock; if ((w & LOCKBIT) == 0) { if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { - ev->OnList = 0 ; + ev->OnList = 0; // We call ::Release while holding the outer lock, thus // artificially lengthening the critical section. // Consider deferring the ::Release() until the subsequent unlock(), // after we've dropped the outer lock. if (ReleaseAfter != NULL) { - ParkEvent::Release (ReleaseAfter) ; + ParkEvent::Release(ReleaseAfter); } - return ; + return; } - continue ; // Interference -- *Lock changed -- Just retry + continue; // Interference -- *Lock changed -- Just retry } - assert (w & LOCKBIT, "invariant") ; - ev->ListNext = (ParkEvent *) (w & ~LOCKBIT ); - if (Atomic::cmpxchg_ptr (intptr_t(ev)|LOCKBIT, Lock, w) == w) break ; + assert(w & LOCKBIT, "invariant"); + ev->ListNext = (ParkEvent *) (w & ~LOCKBIT); + if (Atomic::cmpxchg_ptr(intptr_t(ev)|LOCKBIT, Lock, w) == w) break; } while (ev->OnList != 0) { - ev->park() ; + ev->park(); } } } @@ -4618,22 +4577,22 @@ void Thread::muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) { void Thread::muxRelease (volatile intptr_t * Lock) { for (;;) { - const intptr_t w = Atomic::cmpxchg_ptr (0, Lock, LOCKBIT) ; - assert (w & LOCKBIT, "invariant") ; - if (w == LOCKBIT) return ; - ParkEvent * List = (ParkEvent *) (w & ~LOCKBIT) ; - assert (List != NULL, "invariant") ; - assert (List->OnList == intptr_t(Lock), "invariant") ; - ParkEvent * nxt = List->ListNext ; + const intptr_t w = Atomic::cmpxchg_ptr(0, Lock, LOCKBIT); + assert(w & LOCKBIT, "invariant"); + if (w == LOCKBIT) return; + ParkEvent * List = (ParkEvent *)(w & ~LOCKBIT); + assert(List != NULL, "invariant"); + assert(List->OnList == intptr_t(Lock), "invariant"); + ParkEvent * nxt = List->ListNext; // The following CAS() releases the lock and pops the head element. if (Atomic::cmpxchg_ptr (intptr_t(nxt), Lock, w) != w) { - continue ; + continue; } - List->OnList = 0 ; - OrderAccess::fence() ; - List->unpark () ; - return ; + List->OnList = 0; + OrderAccess::fence(); + List->unpark(); + return; } } diff --git a/hotspot/src/share/vm/runtime/thread.hpp b/hotspot/src/share/vm/runtime/thread.hpp index a5f0a92246d..68c9248dea4 100644 --- a/hotspot/src/share/vm/runtime/thread.hpp +++ b/hotspot/src/share/vm/runtime/thread.hpp @@ -244,7 +244,7 @@ class Thread: public ThreadShadow { // The two classes No_Safepoint_Verifier and No_Allocation_Verifier are used to set these counters. // NOT_PRODUCT(int _allow_safepoint_count;) // If 0, thread allow a safepoint to happen - debug_only (int _allow_allocation_count;) // If 0, the thread is allowed to allocate oops. + debug_only(int _allow_allocation_count;) // If 0, the thread is allowed to allocate oops. // Used by SkipGCALot class. NOT_PRODUCT(bool _skip_gcalot;) // Should we elide gc-a-lot? @@ -593,12 +593,12 @@ public: bool is_inside_jvmti_env_iteration() { return _jvmti_env_iteration_count > 0; } // Code generation - static ByteSize exception_file_offset() { return byte_offset_of(Thread, _exception_file ); } - static ByteSize exception_line_offset() { return byte_offset_of(Thread, _exception_line ); } - static ByteSize active_handles_offset() { return byte_offset_of(Thread, _active_handles ); } + static ByteSize exception_file_offset() { return byte_offset_of(Thread, _exception_file); } + static ByteSize exception_line_offset() { return byte_offset_of(Thread, _exception_line); } + static ByteSize active_handles_offset() { return byte_offset_of(Thread, _active_handles); } - static ByteSize stack_base_offset() { return byte_offset_of(Thread, _stack_base ); } - static ByteSize stack_size_offset() { return byte_offset_of(Thread, _stack_size ); } + static ByteSize stack_base_offset() { return byte_offset_of(Thread, _stack_base); } + static ByteSize stack_size_offset() { return byte_offset_of(Thread, _stack_size); } #define TLAB_FIELD_OFFSET(name) \ static ByteSize tlab_##name##_offset() { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::name##_offset(); } @@ -615,35 +615,35 @@ public: #undef TLAB_FIELD_OFFSET - static ByteSize allocated_bytes_offset() { return byte_offset_of(Thread, _allocated_bytes ); } + static ByteSize allocated_bytes_offset() { return byte_offset_of(Thread, _allocated_bytes); } public: - volatile intptr_t _Stalled ; - volatile int _TypeTag ; - ParkEvent * _ParkEvent ; // for synchronized() - ParkEvent * _SleepEvent ; // for Thread.sleep - ParkEvent * _MutexEvent ; // for native internal Mutex/Monitor - ParkEvent * _MuxEvent ; // for low-level muxAcquire-muxRelease - int NativeSyncRecursion ; // diagnostic + volatile intptr_t _Stalled; + volatile int _TypeTag; + ParkEvent * _ParkEvent; // for synchronized() + ParkEvent * _SleepEvent; // for Thread.sleep + ParkEvent * _MutexEvent; // for native internal Mutex/Monitor + ParkEvent * _MuxEvent; // for low-level muxAcquire-muxRelease + int NativeSyncRecursion; // diagnostic - volatile int _OnTrap ; // Resume-at IP delta - jint _hashStateW ; // Marsaglia Shift-XOR thread-local RNG - jint _hashStateX ; // thread-specific hashCode generator state - jint _hashStateY ; - jint _hashStateZ ; - void * _schedctl ; + volatile int _OnTrap; // Resume-at IP delta + jint _hashStateW; // Marsaglia Shift-XOR thread-local RNG + jint _hashStateX; // thread-specific hashCode generator state + jint _hashStateY; + jint _hashStateZ; + void * _schedctl; - volatile jint rng [4] ; // RNG for spin loop + volatile jint rng[4]; // RNG for spin loop // Low-level leaf-lock primitives used to implement synchronization // and native monitor-mutex infrastructure. // Not for general synchronization use. - static void SpinAcquire (volatile int * Lock, const char * Name) ; - static void SpinRelease (volatile int * Lock) ; - static void muxAcquire (volatile intptr_t * Lock, const char * Name) ; - static void muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) ; - static void muxRelease (volatile intptr_t * Lock) ; + static void SpinAcquire(volatile int * Lock, const char * Name); + static void SpinRelease(volatile int * Lock); + static void muxAcquire(volatile intptr_t * Lock, const char * Name); + static void muxAcquireW(volatile intptr_t * Lock, ParkEvent * ev); + static void muxRelease(volatile intptr_t * Lock); }; // Inline implementation of Thread::current() @@ -915,6 +915,9 @@ class JavaThread: public Thread { // support for JNI critical regions jint _jni_active_critical; // count of entries into JNI critical region + // Checked JNI: function name requires exception check + char* _pending_jni_exception_check_fn; + // For deadlock detection. int _depth_first_number; @@ -930,7 +933,7 @@ class JavaThread: public Thread { intptr_t _instruction; const char* _file; int _line; - } _jmp_ring[ jump_ring_buffer_size ]; + } _jmp_ring[jump_ring_buffer_size]; #endif /* PRODUCT */ #if INCLUDE_ALL_GCS @@ -1333,34 +1336,34 @@ class JavaThread: public Thread { #endif /* PRODUCT */ // For assembly stub generation - static ByteSize threadObj_offset() { return byte_offset_of(JavaThread, _threadObj ); } + static ByteSize threadObj_offset() { return byte_offset_of(JavaThread, _threadObj); } #ifndef PRODUCT - static ByteSize jmp_ring_index_offset() { return byte_offset_of(JavaThread, _jmp_ring_index ); } - static ByteSize jmp_ring_offset() { return byte_offset_of(JavaThread, _jmp_ring ); } + static ByteSize jmp_ring_index_offset() { return byte_offset_of(JavaThread, _jmp_ring_index); } + static ByteSize jmp_ring_offset() { return byte_offset_of(JavaThread, _jmp_ring); } #endif /* PRODUCT */ - static ByteSize jni_environment_offset() { return byte_offset_of(JavaThread, _jni_environment ); } - static ByteSize last_Java_sp_offset() { + static ByteSize jni_environment_offset() { return byte_offset_of(JavaThread, _jni_environment); } + static ByteSize last_Java_sp_offset() { return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_sp_offset(); } - static ByteSize last_Java_pc_offset() { + static ByteSize last_Java_pc_offset() { return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_pc_offset(); } - static ByteSize frame_anchor_offset() { + static ByteSize frame_anchor_offset() { return byte_offset_of(JavaThread, _anchor); } - static ByteSize callee_target_offset() { return byte_offset_of(JavaThread, _callee_target ); } - static ByteSize vm_result_offset() { return byte_offset_of(JavaThread, _vm_result ); } - static ByteSize vm_result_2_offset() { return byte_offset_of(JavaThread, _vm_result_2 ); } - static ByteSize thread_state_offset() { return byte_offset_of(JavaThread, _thread_state ); } - static ByteSize saved_exception_pc_offset() { return byte_offset_of(JavaThread, _saved_exception_pc ); } - static ByteSize osthread_offset() { return byte_offset_of(JavaThread, _osthread ); } - static ByteSize exception_oop_offset() { return byte_offset_of(JavaThread, _exception_oop ); } - static ByteSize exception_pc_offset() { return byte_offset_of(JavaThread, _exception_pc ); } + static ByteSize callee_target_offset() { return byte_offset_of(JavaThread, _callee_target); } + static ByteSize vm_result_offset() { return byte_offset_of(JavaThread, _vm_result); } + static ByteSize vm_result_2_offset() { return byte_offset_of(JavaThread, _vm_result_2); } + static ByteSize thread_state_offset() { return byte_offset_of(JavaThread, _thread_state); } + static ByteSize saved_exception_pc_offset() { return byte_offset_of(JavaThread, _saved_exception_pc); } + static ByteSize osthread_offset() { return byte_offset_of(JavaThread, _osthread); } + static ByteSize exception_oop_offset() { return byte_offset_of(JavaThread, _exception_oop); } + static ByteSize exception_pc_offset() { return byte_offset_of(JavaThread, _exception_pc); } static ByteSize exception_handler_pc_offset() { return byte_offset_of(JavaThread, _exception_handler_pc); } static ByteSize stack_overflow_limit_offset() { return byte_offset_of(JavaThread, _stack_overflow_limit); } static ByteSize is_method_handle_return_offset() { return byte_offset_of(JavaThread, _is_method_handle_return); } - static ByteSize stack_guard_state_offset() { return byte_offset_of(JavaThread, _stack_guard_state ); } - static ByteSize suspend_flags_offset() { return byte_offset_of(JavaThread, _suspend_flags ); } + static ByteSize stack_guard_state_offset() { return byte_offset_of(JavaThread, _stack_guard_state); } + static ByteSize suspend_flags_offset() { return byte_offset_of(JavaThread, _suspend_flags); } static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); } static ByteSize should_post_on_exceptions_flag_offset() { @@ -1400,6 +1403,12 @@ class JavaThread: public Thread { assert(_jni_active_critical >= 0, "JNI critical nesting problem?"); } + // Checked JNI, is the programmer required to check for exceptions, specify which function name + bool is_pending_jni_exception_check() const { return _pending_jni_exception_check_fn != NULL; } + void clear_pending_jni_exception_check() { _pending_jni_exception_check_fn = NULL; } + const char* get_pending_jni_exception_check() const { return _pending_jni_exception_check_fn; } + void set_pending_jni_exception_check(const char* fn_name) { _pending_jni_exception_check_fn = (char*) fn_name; } + // For deadlock detection int depth_first_number() { return _depth_first_number; } void set_depth_first_number(int dfn) { _depth_first_number = dfn; } @@ -1413,7 +1422,7 @@ class JavaThread: public Thread { void remove_monitor_chunk(MonitorChunk* chunk); bool in_deopt_handler() const { return _in_deopt_handler > 0; } void inc_in_deopt_handler() { _in_deopt_handler++; } - void dec_in_deopt_handler() { + void dec_in_deopt_handler() { assert(_in_deopt_handler > 0, "mismatched deopt nesting"); if (_in_deopt_handler > 0) { // robustness _in_deopt_handler--; @@ -1767,7 +1776,7 @@ private: uint _claimed_par_id; public: uint get_claimed_par_id() { return _claimed_par_id; } - void set_claimed_par_id(uint id) { _claimed_par_id = id;} + void set_claimed_par_id(uint id) { _claimed_par_id = id; } }; // Inline implementation of JavaThread::current @@ -1802,7 +1811,7 @@ inline bool JavaThread::stack_yellow_zone_enabled() { inline size_t JavaThread::stack_available(address cur_sp) { // This code assumes java stacks grow down address low_addr; // Limit on the address for deepest stack depth - if ( _stack_guard_state == stack_guard_unused) { + if (_stack_guard_state == stack_guard_unused) { low_addr = stack_base() - stack_size(); } else { low_addr = stack_yellow_zone_base(); diff --git a/hotspot/src/share/vm/runtime/vframe.cpp b/hotspot/src/share/vm/runtime/vframe.cpp index 79da635c443..57900245436 100644 --- a/hotspot/src/share/vm/runtime/vframe.cpp +++ b/hotspot/src/share/vm/runtime/vframe.cpp @@ -480,9 +480,8 @@ void vframeStreamCommon::skip_prefixed_method_and_wrappers() { void vframeStreamCommon::skip_reflection_related_frames() { while (!at_end() && - (JDK_Version::is_gte_jdk14x_version() && (method()->method_holder()->is_subclass_of(SystemDictionary::reflect_MethodAccessorImpl_klass()) || - method()->method_holder()->is_subclass_of(SystemDictionary::reflect_ConstructorAccessorImpl_klass())))) { + method()->method_holder()->is_subclass_of(SystemDictionary::reflect_ConstructorAccessorImpl_klass()))) { next(); } } diff --git a/hotspot/src/share/vm/runtime/vm_operations.cpp b/hotspot/src/share/vm/runtime/vm_operations.cpp index d46e1f775ac..6f27fe3fecc 100644 --- a/hotspot/src/share/vm/runtime/vm_operations.cpp +++ b/hotspot/src/share/vm/runtime/vm_operations.cpp @@ -184,9 +184,7 @@ bool VM_PrintThreads::doit_prologue() { assert(Thread::current()->is_Java_thread(), "just checking"); // Make sure AbstractOwnableSynchronizer is loaded - if (JDK_Version::is_gte_jdk16x_version()) { - java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(JavaThread::current()); - } + java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(JavaThread::current()); // Get Heap_lock if concurrent locks will be dumped if (_print_concurrent_locks) { @@ -225,7 +223,7 @@ bool VM_FindDeadlocks::doit_prologue() { assert(Thread::current()->is_Java_thread(), "just checking"); // Load AbstractOwnableSynchronizer class - if (_concurrent_locks && JDK_Version::is_gte_jdk16x_version()) { + if (_concurrent_locks) { java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(JavaThread::current()); } @@ -283,9 +281,7 @@ bool VM_ThreadDump::doit_prologue() { assert(Thread::current()->is_Java_thread(), "just checking"); // Load AbstractOwnableSynchronizer class before taking thread snapshots - if (JDK_Version::is_gte_jdk16x_version()) { - java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(JavaThread::current()); - } + java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(JavaThread::current()); if (_with_locked_synchronizers) { // Acquire Heap_lock to dump concurrent locks diff --git a/hotspot/src/share/vm/runtime/vm_operations.hpp b/hotspot/src/share/vm/runtime/vm_operations.hpp index 8f2f0ba06f7..4e32a3adfa2 100644 --- a/hotspot/src/share/vm/runtime/vm_operations.hpp +++ b/hotspot/src/share/vm/runtime/vm_operations.hpp @@ -98,6 +98,7 @@ template(LinuxDllLoad) \ template(RotateGCLog) \ template(WhiteBoxOperation) \ + template(ClassLoaderStatsOperation) \ class VM_Operation: public CHeapObj { public: diff --git a/hotspot/src/share/vm/runtime/vm_version.cpp b/hotspot/src/share/vm/runtime/vm_version.cpp index 5df7d221a2b..9fee996f687 100644 --- a/hotspot/src/share/vm/runtime/vm_version.cpp +++ b/hotspot/src/share/vm/runtime/vm_version.cpp @@ -160,8 +160,7 @@ const char* Abstract_VM_Version::vm_vendor() { #ifdef VENDOR return XSTR(VENDOR); #else - return JDK_Version::is_gte_jdk17x_version() ? - "Oracle Corporation" : "Sun Microsystems Inc."; + return "Oracle Corporation"; #endif } @@ -222,20 +221,12 @@ const char* Abstract_VM_Version::internal_vm_info_string() { #ifndef HOTSPOT_BUILD_COMPILER #ifdef _MSC_VER - #if _MSC_VER == 1100 - #define HOTSPOT_BUILD_COMPILER "MS VC++ 5.0" - #elif _MSC_VER == 1200 - #define HOTSPOT_BUILD_COMPILER "MS VC++ 6.0" - #elif _MSC_VER == 1310 - #define HOTSPOT_BUILD_COMPILER "MS VC++ 7.1 (VS2003)" - #elif _MSC_VER == 1400 - #define HOTSPOT_BUILD_COMPILER "MS VC++ 8.0 (VS2005)" - #elif _MSC_VER == 1500 - #define HOTSPOT_BUILD_COMPILER "MS VC++ 9.0 (VS2008)" - #elif _MSC_VER == 1600 + #if _MSC_VER == 1600 #define HOTSPOT_BUILD_COMPILER "MS VC++ 10.0 (VS2010)" #elif _MSC_VER == 1700 #define HOTSPOT_BUILD_COMPILER "MS VC++ 11.0 (VS2012)" + #elif _MSC_VER == 1800 + #define HOTSPOT_BUILD_COMPILER "MS VC++ 12.0 (VS2013)" #else #define HOTSPOT_BUILD_COMPILER "unknown MS VC++:" XSTR(_MSC_VER) #endif diff --git a/hotspot/src/share/vm/services/diagnosticCommand.cpp b/hotspot/src/share/vm/services/diagnosticCommand.cpp index ca031f87963..892e2ce57b6 100644 --- a/hotspot/src/share/vm/services/diagnosticCommand.cpp +++ b/hotspot/src/share/vm/services/diagnosticCommand.cpp @@ -23,6 +23,7 @@ */ #include "precompiled.hpp" +#include "classfile/classLoaderStats.hpp" #include "gc_implementation/shared/vmGCOperations.hpp" #include "runtime/javaCalls.hpp" #include "runtime/os.hpp" @@ -58,6 +59,7 @@ void DCmdRegistrant::register_dcmds(){ #endif // INCLUDE_SERVICES DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl(full_export, true, false)); DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl(full_export, true, false)); + DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl(full_export, true, false)); // Enhanced JMX Agent Support // These commands won't be exported via the DiagnosticCommandMBean until an diff --git a/hotspot/src/share/vm/services/management.cpp b/hotspot/src/share/vm/services/management.cpp index dc901876104..2d6f2ff1d23 100644 --- a/hotspot/src/share/vm/services/management.cpp +++ b/hotspot/src/share/vm/services/management.cpp @@ -1229,10 +1229,8 @@ JVM_ENTRY(jint, jmm_GetThreadInfo(JNIEnv *env, jlongArray ids, jint maxDepth, jo "The length of the given ThreadInfo array does not match the length of the given array of thread IDs", -1); } - if (JDK_Version::is_gte_jdk16x_version()) { - // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots - java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_0); - } + // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots + java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_0); // Must use ThreadDumpResult to store the ThreadSnapshot. // GC may occur after the thread snapshots are taken but before @@ -1303,10 +1301,8 @@ JVM_END JVM_ENTRY(jobjectArray, jmm_DumpThreads(JNIEnv *env, jlongArray thread_ids, jboolean locked_monitors, jboolean locked_synchronizers)) ResourceMark rm(THREAD); - if (JDK_Version::is_gte_jdk16x_version()) { - // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots - java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_NULL); - } + // make sure the AbstractOwnableSynchronizer klass is loaded before taking thread snapshots + java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(CHECK_NULL); typeArrayOop ta = typeArrayOop(JNIHandles::resolve(thread_ids)); int num_threads = (ta != NULL ? ta->length() : 0); diff --git a/hotspot/src/share/vm/services/threadService.cpp b/hotspot/src/share/vm/services/threadService.cpp index 02156a2f3e2..21d87567eed 100644 --- a/hotspot/src/share/vm/services/threadService.cpp +++ b/hotspot/src/share/vm/services/threadService.cpp @@ -665,17 +665,15 @@ void ConcurrentLocksDump::dump_at_safepoint() { // dump all locked concurrent locks assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); - if (JDK_Version::is_gte_jdk16x_version()) { - ResourceMark rm; + ResourceMark rm; - GrowableArray* aos_objects = new GrowableArray(INITIAL_ARRAY_SIZE); + GrowableArray* aos_objects = new GrowableArray(INITIAL_ARRAY_SIZE); - // Find all instances of AbstractOwnableSynchronizer - HeapInspection::find_instances_at_safepoint(SystemDictionary::abstract_ownable_synchronizer_klass(), + // Find all instances of AbstractOwnableSynchronizer + HeapInspection::find_instances_at_safepoint(SystemDictionary::abstract_ownable_synchronizer_klass(), aos_objects); - // Build a map of thread to its owned AQS locks - build_map(aos_objects); - } + // Build a map of thread to its owned AQS locks + build_map(aos_objects); } diff --git a/hotspot/test/runtime/EnclosingMethodAttr/EnclMethTest.jcod b/hotspot/test/runtime/EnclosingMethodAttr/EnclMethTest.jcod new file mode 100644 index 00000000000..956b643b055 --- /dev/null +++ b/hotspot/test/runtime/EnclosingMethodAttr/EnclMethTest.jcod @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * This test has a EnclosingMethod attribute with an illegal + * attribute_length field value of 6. This should cause a + * java.lang.ClassFormatError exception to be thrown. + */ + +class EnclMethTest { + 0xCAFEBABE; + 0; // minor version + 52; // version + [22] { // Constant Pool + ; // first element is empty + Field #3 #14; // #1 at 0x0A + Method #4 #15; // #2 at 0x0F + class #16; // #3 at 0x14 + class #19; // #4 at 0x17 + Utf8 "this$0"; // #5 at 0x1A + Utf8 "La;"; // #6 at 0x23 + Utf8 "Synthetic"; // #7 at 0x29 + Utf8 ""; // #8 at 0x35 + Utf8 "(Ljava/lang/Object;)V"; // #9 at 0x3E + Utf8 "Code"; // #10 at 0x56 + Utf8 "LineNumberTable"; // #11 at 0x5D + Utf8 "SourceFile"; // #12 at 0x6F + Utf8 "a.java"; // #13 at 0x7C + NameAndType #5 #6; // #14 at 0x85 + NameAndType #8 #20; // #15 at 0x8A + Utf8 "EnclMethTest"; // #16 at 0x8F + Utf8 "Loc"; // #17 at 0x9E + Utf8 "InnerClasses"; // #18 at 0xA4 + Utf8 "java/lang/Object"; // #19 at 0xB3 + Utf8 "()V"; // #20 at 0xC6 + Utf8 "EnclosingMethod"; // #21 at 0xCC + } // Constant Pool + + 0x0000; // access + #3;// this_cpx + #4;// super_cpx + + [0] { // Interfaces + } // Interfaces + + [1] { // fields + { // Member at 0xE8 + 0x0000; // access + #5; // name_cpx + #6; // sig_cpx + [1] { // Attributes + Attr(#7, 0) { // Synthetic at 0xF0 + } // end Synthetic + } // Attributes + } // Member + } // fields + + [1] { // methods + { // Member at 0xF8 + 0x0001; // access + #8; // name_cpx + #20; // sig_cpx + [1] { // Attributes + Attr(#10, 17) { // Code at 0x0100 + 2; // max_stack + 2; // max_locals + Bytes[5]{ + 0x2AB70002B1; + }; + [0] { // Traps + } // end Traps + [0] { // Attributes + } // Attributes + } // end Code + } // Attributes + } // Member + } // methods + + [3] { // Attributes + Attr(#12, 2) { // SourceFile at 0x0119 + #13; + } // end SourceFile + ; + Attr(#18, 10) { // InnerClasses at 0x0121 + [1] { // InnerClasses + #3 #0 #17 0; // at 0x0131 + } + } // end InnerClasses + ; + Attr(#21, 6) { // EnclosingMethod at 0x0131 + // invalid length of EnclosingMethod attr: 6 (should be 4) !! + 0x0004000F; + } // end EnclosingMethod + } // Attributes +} // end class EnclMethTest diff --git a/hotspot/test/runtime/EnclosingMethodAttr/EnclMethodAttr.java b/hotspot/test/runtime/EnclosingMethodAttr/EnclMethodAttr.java new file mode 100644 index 00000000000..82b5424813f --- /dev/null +++ b/hotspot/test/runtime/EnclosingMethodAttr/EnclMethodAttr.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8044738 + * @library /testlibrary + * @summary Check attribute_length of EnclosingMethod attribute + * @run main EnclMethodAttr + */ + +import java.io.File; +import com.oracle.java.testlibrary.*; + +public class EnclMethodAttr { + + static final String testsrc = System.getProperty("test.src"); + + public static void main(String args[]) throws Throwable { + System.out.println("Regression test for bug 8044738"); + ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + "-jar", testsrc + File.separator + "enclMethodAttr.jar"); + OutputAnalyzer output = new OutputAnalyzer(pb.start()); + output.shouldContain("java.lang.ClassFormatError: Wrong EnclosingMethod"); + } +} + diff --git a/hotspot/test/runtime/EnclosingMethodAttr/enclMethodAttr.jar b/hotspot/test/runtime/EnclosingMethodAttr/enclMethodAttr.jar new file mode 100644 index 00000000000..590e7ae37b6 Binary files /dev/null and b/hotspot/test/runtime/EnclosingMethodAttr/enclMethodAttr.jar differ diff --git a/hotspot/test/runtime/Thread/TestThreadDumpMonitorContention.java b/hotspot/test/runtime/Thread/TestThreadDumpMonitorContention.java index 06b2274d823..979aefcd446 100644 --- a/hotspot/test/runtime/Thread/TestThreadDumpMonitorContention.java +++ b/hotspot/test/runtime/Thread/TestThreadDumpMonitorContention.java @@ -24,6 +24,7 @@ /* * @test * @bug 8036823 + * @bug 8046287 * @summary Creates two threads contending for the same lock and checks * whether jstack reports "locked" by more than one thread. * @@ -52,10 +53,13 @@ public class TestThreadDumpMonitorContention { // looking for header lines with these patterns: // "ContendingThread-1" #19 prio=5 os_prio=64 tid=0x000000000079c000 nid=0x23 runnable [0xffff80ffb8b87000] // "ContendingThread-2" #21 prio=5 os_prio=64 tid=0x0000000000780000 nid=0x2f waiting for monitor entry [0xfffffd7fc1111000] + // "ContendingThread-2" #24 prio=5 os_prio=64 tid=0x0000000000ec8800 nid=0x31 waiting on condition [0xfffffd7bbfffe000] final static Pattern HEADER_PREFIX_PATTERN = Pattern.compile( "^\"ContendingThread-.*"); - final static Pattern HEADER_WAITING_PATTERN = Pattern.compile( + final static Pattern HEADER_WAITING_PATTERN1 = Pattern.compile( "^\"ContendingThread-.* waiting for monitor entry .*"); + final static Pattern HEADER_WAITING_PATTERN2 = Pattern.compile( + "^\"ContendingThread-.* waiting on condition .*"); final static Pattern HEADER_RUNNABLE_PATTERN = Pattern.compile( "^\"ContendingThread-.* runnable .*"); @@ -80,17 +84,34 @@ public class TestThreadDumpMonitorContention { final static Pattern WAITING_PATTERN = Pattern.compile( ".* waiting to lock \\<.*\\(a TestThreadDumpMonitorContention.*"); + final static Object barrier = new Object(); volatile static boolean done = false; + static int barrier_cnt = 0; + static int blank_line_match_cnt = 0; static int error_cnt = 0; - static String header_line = null; static boolean have_header_line = false; static boolean have_thread_state_line = false; - static int match_cnt = 0; - static String[] match_list = new String[2]; + static String header_line = null; + static int header_prefix_match_cnt = 0; + static int locked_line_match_cnt = 0; + static String[] locked_match_list = new String[2]; static int n_samples = 15; + static int sum_both_running_cnt = 0; + static int sum_both_waiting_cnt = 0; + static int sum_contended_cnt = 0; + static int sum_locked_hdr_runnable_cnt = 0; + static int sum_locked_hdr_waiting1_cnt = 0; + static int sum_locked_hdr_waiting2_cnt = 0; + static int sum_locked_thr_state_blocked_cnt = 0; + static int sum_locked_thr_state_runnable_cnt = 0; + static int sum_one_waiting_cnt = 0; + static int sum_uncontended_cnt = 0; + static int sum_waiting_hdr_waiting1_cnt = 0; + static int sum_waiting_thr_state_blocked_cnt = 0; static String thread_state_line = null; static boolean verbose = false; + static int waiting_line_match_cnt = 0; public static void main(String[] args) throws Exception { if (args.length != 0) { @@ -110,6 +131,11 @@ public class TestThreadDumpMonitorContention { Runnable runnable = new Runnable() { public void run() { + synchronized (barrier) { + // let the main thread know we're running + barrier_cnt++; + barrier.notify(); + } while (!done) { synchronized (this) { } } @@ -118,8 +144,16 @@ public class TestThreadDumpMonitorContention { Thread[] thread_list = new Thread[2]; thread_list[0] = new Thread(runnable, "ContendingThread-1"); thread_list[1] = new Thread(runnable, "ContendingThread-2"); - thread_list[0].start(); - thread_list[1].start(); + synchronized (barrier) { + thread_list[0].start(); + thread_list[1].start(); + + // Wait until the contending threads are running so that + // we don't sample any thread init states. + while (barrier_cnt < 2) { + barrier.wait(); + } + } doSamples(); @@ -143,11 +177,12 @@ public class TestThreadDumpMonitorContention { // Example: // "ContendingThread-1" #21 prio=5 os_prio=64 tid=0x00000000007b9000 nid=0x2f runnable [0xfffffd7fc1111000] // java.lang.Thread.State: RUNNABLE - // at TestThreadDumpMonitorContention$1.run(TestThreadDumpMonitorContention.java:67) + // at TestThreadDumpMonitorContention$1.run(TestThreadDumpMonitorContention.java:140) // at java.lang.Thread.run(Thread.java:745) // static boolean checkBlankLine(String line) { if (line.length() == 0) { + blank_line_match_cnt++; have_header_line = false; have_thread_state_line = false; return true; @@ -161,49 +196,73 @@ public class TestThreadDumpMonitorContention { // Example 1: // "ContendingThread-1" #21 prio=5 os_prio=64 tid=0x00000000007b9000 nid=0x2f runnable [0xfffffd7fc1111000] // java.lang.Thread.State: RUNNABLE - // at TestThreadDumpMonitorContention$1.run(TestThreadDumpMonitorContention.java:67) + // at TestThreadDumpMonitorContention$1.run(TestThreadDumpMonitorContention.java:140) // - locked <0xfffffd7e6a2912f8> (a TestThreadDumpMonitorContention$1) // at java.lang.Thread.run(Thread.java:745) // // Example 2: // "ContendingThread-1" #21 prio=5 os_prio=64 tid=0x00000000007b9000 nid=0x2f waiting for monitor entry [0xfffffd7fc1111000] // java.lang.Thread.State: BLOCKED (on object monitor) - // at TestThreadDumpMonitorContention$1.run(TestThreadDumpMonitorContention.java:67) + // at TestThreadDumpMonitorContention$1.run(TestThreadDumpMonitorContention.java:140) // - locked <0xfffffd7e6a2912f8> (a TestThreadDumpMonitorContention$1) // at java.lang.Thread.run(Thread.java:745) // + // Example 3: + // "ContendingThread-2" #24 prio=5 os_prio=64 tid=0x0000000000ec8800 nid=0x31 waiting on condition [0xfffffd7bbfffe000] + // java.lang.Thread.State: RUNNABLE + // JavaThread state: _thread_blocked + // Thread: 0x0000000000ec8800 [0x31] State: _at_safepoint _has_called_back 0 _at_poll_safepoint 0 + // JavaThread state: _thread_blocked + // at TestThreadDumpMonitorContention$1.run(TestThreadDumpMonitorContention.java:140) + // - locked <0xfffffd7e6d03eb28> (a TestThreadDumpMonitorContention$1) + // at java.lang.Thread.run(Thread.java:745) + // static boolean checkLockedLine(String line) { Matcher matcher = LOCK_PATTERN.matcher(line); if (matcher.matches()) { if (verbose) { System.out.println("locked_line='" + line + "'"); } - match_list[match_cnt] = new String(line); - match_cnt++; + locked_match_list[locked_line_match_cnt] = new String(line); + locked_line_match_cnt++; matcher = HEADER_RUNNABLE_PATTERN.matcher(header_line); - if (!matcher.matches()) { + if (matcher.matches()) { + sum_locked_hdr_runnable_cnt++; + } else { // It's strange, but a locked line can also - // match the HEADER_WAITING_PATTERN. - matcher = HEADER_WAITING_PATTERN.matcher(header_line); - if (!matcher.matches()) { - System.err.println(); - System.err.println("ERROR: header line does " + - "not match runnable or waiting patterns."); - System.err.println("ERROR: header_line='" + - header_line + "'"); - System.err.println("ERROR: locked_line='" + line + "'"); - error_cnt++; + // match the HEADER_WAITING_PATTERN{1,2}. + matcher = HEADER_WAITING_PATTERN1.matcher(header_line); + if (matcher.matches()) { + sum_locked_hdr_waiting1_cnt++; + } else { + matcher = HEADER_WAITING_PATTERN2.matcher(header_line); + if (matcher.matches()) { + sum_locked_hdr_waiting2_cnt++; + } else { + System.err.println(); + System.err.println("ERROR: header line does " + + "not match runnable or waiting patterns."); + System.err.println("ERROR: header_line='" + + header_line + "'"); + System.err.println("ERROR: locked_line='" + line + + "'"); + error_cnt++; + } } } matcher = THREAD_STATE_RUNNABLE_PATTERN.matcher(thread_state_line); - if (!matcher.matches()) { + if (matcher.matches()) { + sum_locked_thr_state_runnable_cnt++; + } else { // It's strange, but a locked line can also // match the THREAD_STATE_BLOCKED_PATTERN. matcher = THREAD_STATE_BLOCKED_PATTERN.matcher( thread_state_line); - if (!matcher.matches()) { + if (matcher.matches()) { + sum_locked_thr_state_blocked_cnt++; + } else { System.err.println(); System.err.println("ERROR: thread state line does not " + "match runnable or waiting patterns."); @@ -229,19 +288,22 @@ public class TestThreadDumpMonitorContention { // Example: // "ContendingThread-2" #22 prio=5 os_prio=64 tid=0x00000000007b9800 nid=0x30 waiting for monitor entry [0xfffffd7fc1010000] // java.lang.Thread.State: BLOCKED (on object monitor) - // at TestThreadDumpMonitorContention$1.run(TestThreadDumpMonitorContention.java:67) + // at TestThreadDumpMonitorContention$1.run(TestThreadDumpMonitorContention.java:140) // - waiting to lock <0xfffffd7e6a2912f8> (a TestThreadDumpMonitorContention$1) // at java.lang.Thread.run(Thread.java:745) // static boolean checkWaitingLine(String line) { Matcher matcher = WAITING_PATTERN.matcher(line); if (matcher.matches()) { + waiting_line_match_cnt++; if (verbose) { System.out.println("waiting_line='" + line + "'"); } - matcher = HEADER_WAITING_PATTERN.matcher(header_line); - if (!matcher.matches()) { + matcher = HEADER_WAITING_PATTERN1.matcher(header_line); + if (matcher.matches()) { + sum_waiting_hdr_waiting1_cnt++; + } else { System.err.println(); System.err.println("ERROR: header line does " + "not match a waiting pattern."); @@ -251,7 +313,9 @@ public class TestThreadDumpMonitorContention { } matcher = THREAD_STATE_BLOCKED_PATTERN.matcher(thread_state_line); - if (!matcher.matches()) { + if (matcher.matches()) { + sum_waiting_thr_state_blocked_cnt++; + } else { System.err.println(); System.err.println("ERROR: thread state line " + "does not match a waiting pattern."); @@ -273,7 +337,10 @@ public class TestThreadDumpMonitorContention { static void doSamples() throws Exception { for (int count = 0; count < n_samples; count++) { - match_cnt = 0; + blank_line_match_cnt = 0; + header_prefix_match_cnt = 0; + locked_line_match_cnt = 0; + waiting_line_match_cnt = 0; // verbose mode or an error has a lot of output so add more space if (verbose || error_cnt > 0) System.out.println(); System.out.println("Sample #" + count); @@ -290,12 +357,12 @@ public class TestThreadDumpMonitorContention { // a failure and we report it // - for a stack trace that matches LOCKED_PATTERN, we verify: // - the header line matches HEADER_RUNNABLE_PATTERN - // or HEADER_WAITING_PATTERN + // or HEADER_WAITING_PATTERN{1,2} // - the thread state line matches THREAD_STATE_BLOCKED_PATTERN // or THREAD_STATE_RUNNABLE_PATTERN // - we report any mismatches as failures // - for a stack trace that matches WAITING_PATTERN, we verify: - // - the header line matches HEADER_WAITING_PATTERN + // - the header line matches HEADER_WAITING_PATTERN1 // - the thread state line matches THREAD_STATE_BLOCKED_PATTERN // - we report any mismatches as failures // - the stack traces that match HEADER_PREFIX_PATTERN may @@ -324,6 +391,7 @@ public class TestThreadDumpMonitorContention { if (!have_header_line) { matcher = HEADER_PREFIX_PATTERN.matcher(line); if (matcher.matches()) { + header_prefix_match_cnt++; if (verbose) { System.out.println(); System.out.println("header='" + line + "'"); @@ -366,19 +434,80 @@ public class TestThreadDumpMonitorContention { } process.waitFor(); - if (match_cnt == 2) { - if (match_list[0].equals(match_list[1])) { - System.err.println(); - System.err.println("ERROR: matching lock lines:"); - System.err.println("ERROR: line[0]'" + match_list[0] + "'"); - System.err.println("ERROR: line[1]'" + match_list[1] + "'"); - error_cnt++; - } - } + if (header_prefix_match_cnt != 2) { + System.err.println(); + System.err.println("ERROR: should match exactly two headers."); + System.err.println("ERROR: header_prefix_match_cnt=" + + header_prefix_match_cnt); + error_cnt++; + } + + if (locked_line_match_cnt == 2) { + if (locked_match_list[0].equals(locked_match_list[1])) { + System.err.println(); + System.err.println("ERROR: matching lock lines:"); + System.err.println("ERROR: line[0]'" + + locked_match_list[0] + "'"); + System.err.println("ERROR: line[1]'" + + locked_match_list[1] + "'"); + error_cnt++; + } + } + + if (locked_line_match_cnt == 1) { + // one thread has the lock + if (waiting_line_match_cnt == 1) { + // and the other contended for it + sum_contended_cnt++; + } else { + // and the other is just running + sum_uncontended_cnt++; + } + } else if (waiting_line_match_cnt == 1) { + // one thread is waiting + sum_one_waiting_cnt++; + } else if (waiting_line_match_cnt == 2) { + // both threads are waiting + sum_both_waiting_cnt++; + } else { + // both threads are running + sum_both_running_cnt++; + } // slight delay between jstack launches Thread.sleep(500); } + + if (error_cnt != 0) { + // skip summary info since there were errors + return; + } + + System.out.println("INFO: Summary for all samples:"); + System.out.println("INFO: both_running_cnt=" + sum_both_running_cnt); + System.out.println("INFO: both_waiting_cnt=" + sum_both_waiting_cnt); + System.out.println("INFO: contended_cnt=" + sum_contended_cnt); + System.out.println("INFO: one_waiting_cnt=" + sum_one_waiting_cnt); + System.out.println("INFO: uncontended_cnt=" + sum_uncontended_cnt); + System.out.println("INFO: locked_hdr_runnable_cnt=" + + sum_locked_hdr_runnable_cnt); + System.out.println("INFO: locked_hdr_waiting1_cnt=" + + sum_locked_hdr_waiting1_cnt); + System.out.println("INFO: locked_hdr_waiting2_cnt=" + + sum_locked_hdr_waiting2_cnt); + System.out.println("INFO: locked_thr_state_blocked_cnt=" + + sum_locked_thr_state_blocked_cnt); + System.out.println("INFO: locked_thr_state_runnable_cnt=" + + sum_locked_thr_state_runnable_cnt); + System.out.println("INFO: waiting_hdr_waiting1_cnt=" + + sum_waiting_hdr_waiting1_cnt); + System.out.println("INFO: waiting_thr_state_blocked_cnt=" + + sum_waiting_thr_state_blocked_cnt); + + if (sum_contended_cnt == 0) { + System.err.println("WARNING: the primary scenario for 8036823" + + " has not been exercised by this test run."); + } } // This helper relies on RuntimeMXBean.getName() returning a string diff --git a/hotspot/test/serviceability/dcmd/ClassLoaderStatsTest.java b/hotspot/test/serviceability/dcmd/ClassLoaderStatsTest.java new file mode 100644 index 00000000000..0b229a8a9a1 --- /dev/null +++ b/hotspot/test/serviceability/dcmd/ClassLoaderStatsTest.java @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * + * @build ClassLoaderStatsTest DcmdUtil + * @run main ClassLoaderStatsTest + */ + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.StringReader; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ClassLoaderStatsTest { + + // ClassLoader Parent CLD* Classes ChunkSz BlockSz Type + // 0x00000007c0215928 0x0000000000000000 0x0000000000000000 0 0 0 org.eclipse.osgi.baseadaptor.BaseAdaptor$1 + // 0x00000007c0009868 0x0000000000000000 0x00007fc52aebcc80 1 6144 3768 sun.reflect.DelegatingClassLoader + // 0x00000007c0009868 0x0000000000000000 0x00007fc52b8916d0 1 6144 3688 sun.reflect.DelegatingClassLoader + // 0x00000007c0009868 0x00000007c0038ba8 0x00007fc52afb8760 1 6144 3688 sun.reflect.DelegatingClassLoader + // 0x00000007c0009868 0x0000000000000000 0x00007fc52afbb1a0 1 6144 3688 sun.reflect.DelegatingClassLoader + // 0x0000000000000000 0x0000000000000000 0x00007fc523416070 5019 30060544 29956216 + // 455 1210368 672848 + unsafe anonymous classes + // 0x00000007c016b5c8 0x00000007c0038ba8 0x00007fc52a995000 5 8192 5864 org.netbeans.StandardModule$OneModuleClassLoader + // 0x00000007c0009868 0x00000007c016b5c8 0x00007fc52ac13640 1 6144 3896 sun.reflect.DelegatingClassLoader + // ... + + static Pattern clLine = Pattern.compile("0x\\p{XDigit}*\\s*0x\\p{XDigit}*\\s*0x\\p{XDigit}*\\s*(\\d*)\\s*(\\d*)\\s*(\\d*)\\s*(.*)"); + static Pattern anonLine = Pattern.compile("\\s*(\\d*)\\s*(\\d*)\\s*(\\d*)\\s*.*"); + + public static DummyClassLoader dummyloader; + + public static void main(String arg[]) throws Exception { + + // create a classloader and load our special class + dummyloader = new DummyClassLoader(); + Class c = Class.forName("TestClass", true, dummyloader); + if (c.getClassLoader() != dummyloader) { + throw new RuntimeException("TestClass defined by wrong classloader: " + c.getClassLoader()); + } + + String result = DcmdUtil.executeDcmd("VM.classloader_stats"); + BufferedReader r = new BufferedReader(new StringReader(result)); + String line; + while((line = r.readLine()) != null) { + Matcher m = clLine.matcher(line); + if (m.matches()) { + // verify that DummyClassLoader has loaded 1 class and 1 anonymous class + if (m.group(4).equals("ClassLoaderStatsTest$DummyClassLoader")) { + System.out.println("line: " + line); + if (!m.group(1).equals("1")) { + throw new Exception("Should have loaded 1 class: " + line); + } + checkPositiveInt(m.group(2)); + checkPositiveInt(m.group(3)); + + String next = r.readLine(); + System.out.println("next: " + next); + Matcher m1 = anonLine.matcher(next); + m1.matches(); + if (!m1.group(1).equals("1")) { + throw new Exception("Should have loaded 1 anonymous class, but found : " + m1.group(1)); + } + checkPositiveInt(m1.group(2)); + checkPositiveInt(m1.group(3)); + } + } + } + } + + private static void checkPositiveInt(String s) throws Exception { + if (Integer.parseInt(s) <= 0) { + throw new Exception("Value should have been > 0: " + s); + } + } + + public static class DummyClassLoader extends ClassLoader { + + public static final String CLASS_NAME = "TestClass"; + + static ByteBuffer readClassFile(String name) + { + File f = new File(System.getProperty("test.classes", "."), + name); + try (FileInputStream fin = new FileInputStream(f); + FileChannel fc = fin.getChannel()) + { + return fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); + } catch (IOException e) { + throw new RuntimeException("Can't open file: " + name, e); + } + } + + protected Class loadClass(String name, boolean resolve) + throws ClassNotFoundException + { + Class c; + if (!"TestClass".equals(name)) { + c = super.loadClass(name, resolve); + } else { + // should not delegate to the system class loader + c = findClass(name); + if (resolve) { + resolveClass(c); + } + } + return c; + } + + protected Class findClass(String name) + throws ClassNotFoundException + { + if (!"TestClass".equals(name)) { + throw new ClassNotFoundException("Unexpected class: " + name); + } + return defineClass(name, readClassFile(name + ".class"), null); + } + } /* DummyClassLoader */ + +} + +class TestClass { + static { + // force creation of anonymous class (for the lambdaform) + Runnable r = () -> System.out.println("Hello"); + r.run(); + } +} diff --git a/hotspot/test/serviceability/sa/jmap-hashcode/Test8028623.java b/hotspot/test/serviceability/sa/jmap-hashcode/Test8028623.java index 6f4b2fd689a..815b3f606ca 100644 --- a/hotspot/test/serviceability/sa/jmap-hashcode/Test8028623.java +++ b/hotspot/test/serviceability/sa/jmap-hashcode/Test8028623.java @@ -26,6 +26,7 @@ * @bug 8028623 * @summary Test hashing of extended characters in Serviceability Agent. * @library /testlibrary + * @ignore 8044416 * @build com.oracle.java.testlibrary.* * @compile -encoding utf8 Test8028623.java * @run main Test8028623 diff --git a/hotspot/test/testlibrary_tests/whitebox/vm_flags/BooleanTest.java b/hotspot/test/testlibrary_tests/whitebox/vm_flags/BooleanTest.java index cf313c37962..a76fd4d9a22 100644 --- a/hotspot/test/testlibrary_tests/whitebox/vm_flags/BooleanTest.java +++ b/hotspot/test/testlibrary_tests/whitebox/vm_flags/BooleanTest.java @@ -25,7 +25,7 @@ * @test BooleanTest * @bug 8028756 * @library /testlibrary /testlibrary/whitebox - * @build BooleanTest + * @build BooleanTest ClassFileInstaller sun.hotspot.WhiteBox com.oracle.java.testlibrary.* * @run main ClassFileInstaller sun.hotspot.WhiteBox * @run main/othervm/timeout=600 -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI BooleanTest * @summary testing of WB::set/getBooleanVMFlag() diff --git a/jdk/.hgtags b/jdk/.hgtags index 827ca017224..38493c04e7f 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -263,3 +263,4 @@ fd8e675f141b9bdb2f46d1ae8251f4ee3a895d64 jdk9-b17 6ad17b31f0d30593392b1e8695b9709dbbd7fb70 jdk9-b18 27561aede285c25a3e9ed8bf8918234ad3bb81e3 jdk9-b19 f87c5be90e01a7ffb47947108eb3e0b0b1920880 jdk9-b20 +2df45ac1bf491278f38c12e0dfbeebadb6c54c8c jdk9-b21 diff --git a/jdk/make/CopyFiles.gmk b/jdk/make/CopyFiles.gmk index c1fa0d4062b..396f2534317 100644 --- a/jdk/make/CopyFiles.gmk +++ b/jdk/make/CopyFiles.gmk @@ -373,7 +373,14 @@ ifeq ($(OPENJDK_TARGET_OS), windows) POLICY_SRC_LIST += $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS)/lib/security/java.policy endif ifndef OPENJDK - ifneq (, $(filter $(OPENJDK_TARGET_OS), windows solaris)) + ifeq ($(OPENJDK_TARGET_OS), windows) + ifeq ($(OPENJDK_TARGET_CPU_BITS), 32) + POLICY_SRC_LIST += $(JDK_TOPDIR)/src/closed/$(OPENJDK_TARGET_OS)/lib/security/java.policy-win32 + else + POLICY_SRC_LIST += $(JDK_TOPDIR)/src/closed/$(OPENJDK_TARGET_OS)/lib/security/java.policy-win64 + endif + endif + ifeq ($(OPENJDK_TARGET_OS), solaris) POLICY_SRC_LIST += $(JDK_TOPDIR)/src/closed/$(OPENJDK_TARGET_OS)/lib/security/java.policy endif endif diff --git a/jdk/make/GenerateData.gmk b/jdk/make/GenerateData.gmk index 28faec4826a..437dd0b1d38 100644 --- a/jdk/make/GenerateData.gmk +++ b/jdk/make/GenerateData.gmk @@ -62,7 +62,7 @@ GENDATA += $(GENDATA_UNINAME) ########################################################################################## -GENDATA_CURDATA := $(JDK_OUTPUTDIR)/lib/currency.data +GENDATA_CURDATA := $(JDK_OUTPUTDIR)/classes/java/util/currency.data $(GENDATA_CURDATA): $(JDK_TOPDIR)/make/data/currency/CurrencyData.properties $(BUILD_TOOLS) $(MKDIR) -p $(@D) diff --git a/jdk/make/Setup.gmk b/jdk/make/Setup.gmk index 123a03e2c17..485c3b72b13 100644 --- a/jdk/make/Setup.gmk +++ b/jdk/make/Setup.gmk @@ -27,7 +27,7 @@ DISABLE_WARNINGS := -Xlint:all,-deprecation,-unchecked,-rawtypes,-cast,-serial,- # To build with all warnings enabled, do the following: # make JAVAC_WARNINGS="-Xlint:all -Xmaxwarns 10000" -JAVAC_WARNINGS := -Xlint:-unchecked,-deprecation,-overrides,auxiliaryclass,cast,classfile,dep-ann,divzero,empty,fallthrough,overloads,serial,static,try,varargs -Werror +JAVAC_WARNINGS := -Xlint:all,-deprecation,-rawtypes,-unchecked -Werror # Any java code executed during a JDK build to build other parts of the JDK must be # executed by the bootstrap JDK (probably with -Xbootclasspath/p: ) and for this diff --git a/jdk/make/lib/Awt2dLibraries.gmk b/jdk/make/lib/Awt2dLibraries.gmk index a689e52f03a..1d44b22ea83 100644 --- a/jdk/make/lib/Awt2dLibraries.gmk +++ b/jdk/make/lib/Awt2dLibraries.gmk @@ -319,7 +319,6 @@ endif ifeq ($(OPENJDK_TARGET_OS), macosx) LIBAWT_FILES += awt_LoadLibrary.c - LIBAWT_CFLAGS += -F/System/Library/Frameworks/JavaVM.framework/Frameworks endif ifeq ($(OPENJDK_TARGET_OS)-$(OPENJDK_TARGET_CPU_ARCH), solaris-sparc) @@ -484,7 +483,6 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBAWT, \ LDFLAGS_SUFFIX_macosx := -lmlib_image -ljvm $(LIBM) \ -framework Cocoa \ -framework OpenGL \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ -framework JavaNativeFoundation \ -framework JavaRuntimeSupport \ -framework ApplicationServices \ @@ -709,21 +707,24 @@ $(BUILD_LIBLCMS): $(BUILD_LIBAWT) ########################################################################################## +BUILD_LIBJAVAJPEG_DIR := $(JDK_TOPDIR)/src/share/native/sun/awt/image/jpeg + ifdef OPENJDK - BUILD_LIBJPEG_MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libjpeg/mapfile-vers + BUILD_LIBJAVAJPEG_MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libjpeg/mapfile-vers else - BUILD_LIBJPEG_MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libjpeg/mapfile-vers-closed - BUILD_LIBJPEG_CLOSED_SRC := $(JDK_TOPDIR)/src/closed/share/native/sun/awt/image/jpeg - BUILD_LIBJPEG_CLOSED_INCLUDES := -I$(BUILD_LIBJPEG_CLOSED_SRC) + BUILD_LIBJAVAJPEG_MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libjpeg/mapfile-vers-closed + BUILD_LIBJAVAJPEG_CLOSED_SRC := $(JDK_TOPDIR)/src/closed/share/native/sun/awt/image/jpeg + BUILD_LIBJAVAJPEG_CLOSED_INCLUDES := -I$(BUILD_LIBJAVAJPEG_CLOSED_SRC) endif -BUILD_LIBJPEG_REORDER := +BUILD_LIBJAVAJPEG_REORDER := ifeq ($(OPENJDK_TARGET_OS), solaris) ifneq ($(OPENJDK_TARGET_CPU), x86_64) - BUILD_LIBJPEG_REORDER := $(JDK_TOPDIR)/make/mapfiles/libjpeg/reorder-$(OPENJDK_TARGET_CPU) + BUILD_LIBJAVAJPEG_REORDER := $(JDK_TOPDIR)/make/mapfiles/libjpeg/reorder-$(OPENJDK_TARGET_CPU) endif endif + # Suppress gcc warnings like "variable might be clobbered by 'longjmp' # or 'vfork'": this warning indicates that some variable is placed to # a register by optimized compiler and it's value might be lost on longjmp(). @@ -735,37 +736,50 @@ endif # $(shell $(EXPR) $(CC_MAJORVER) \> 4 \| \ # \( $(CC_MAJORVER) = 4 \& $(CC_MINORVER) \>= 3 \) ) # ifeq ($(CC_43_OR_NEWER), 1) -# BUILD_LIBJPEG_CFLAGS_linux += -Wno-clobbered +# BUILD_LIBJAVAJPEG_CFLAGS_linux += -Wno-clobbered # endif #endif -$(eval $(call SetupNativeCompilation,BUILD_LIBJPEG, \ - LIBRARY := jpeg, \ +ifeq ($(USE_EXTERNAL_LIBJPEG), true) + LIBJPEG_LIBS := -ljpeg + BUILD_LIBJAVAJPEG_INCLUDE_FILES := \ + imageIOJPEG.c \ + jpegdecoder.c + BUILD_LIBJAVAJPEG_HEADERS := +else + LIBJPEG_LIBS := + BUILD_LIBJAVAJPEG_INCLUDE_FILES := + BUILD_LIBJAVAJPEG_HEADERS := -I$(BUILD_LIBJAVAJPEG_DIR) +endif + +$(eval $(call SetupNativeCompilation,BUILD_LIBJAVAJPEG, \ + LIBRARY := javajpeg, \ OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \ - SRC := $(BUILD_LIBJPEG_CLOSED_SRC) \ - $(JDK_TOPDIR)/src/share/native/sun/awt/image/jpeg, \ + SRC := $(BUILD_LIBJAVAJPEG_CLOSED_SRC) \ + $(BUILD_LIBJAVAJPEG_DIR), \ + INCLUDE_FILES := $(BUILD_LIBJAVAJPEG_INCLUDE_FILES), \ LANG := C, \ OPTIMIZATION := HIGHEST, \ CFLAGS := $(CFLAGS_JDKLIB) \ - $(BUILD_LIBJPEG_CLOSED_INCLUDES) \ - -I$(JDK_TOPDIR)/src/share/native/sun/awt/image/jpeg, \ - MAPFILE := $(BUILD_LIBJPEG_MAPFILE), \ - LDFLAGS := $(LDFLAGS_JDKLIB) \ + $(BUILD_LIBJAVAJPEG_CLOSED_INCLUDES) \ + $(BUILD_LIBJAVAJPEG_HEADERS), \ + MAPFILE := $(BUILD_LIBJAVAJPEG_MAPFILE), \ + LDFLAGS := $(LDFLAGS_JDKLIB) $(LIBJPEG_LIBS) \ $(call SET_SHARED_LIBRARY_ORIGIN), \ LDFLAGS_windows := $(WIN_JAVA_LIB) jvm.lib, \ LDFLAGS_SUFFIX := $(LDFLAGS_JDKLIB_SUFFIX), \ VERSIONINFO_RESOURCE := $(JDK_TOPDIR)/src/windows/resource/version.rc, \ RC_FLAGS := $(RC_FLAGS) \ - -D "JDK_FNAME=jpeg.dll" \ - -D "JDK_INTERNAL_NAME=jpeg" \ + -D "JDK_FNAME=javajpeg.dll" \ + -D "JDK_INTERNAL_NAME=javajpeg" \ -D "JDK_FTYPE=0x2L", \ - REORDER := $(BUILD_LIBJPEG_REORDER), \ + REORDER := $(BUILD_LIBJAVAJPEG_REORDER), \ OBJECT_DIR := $(JDK_OUTPUTDIR)/objs/libjpeg, \ DEBUG_SYMBOLS := $(DEBUG_ALL_BINARIES))) -$(BUILD_LIBJPEG): $(BUILD_LIBJAVA) +$(BUILD_LIBJAVAJPEG): $(BUILD_LIBJAVA) -BUILD_LIBRARIES += $(BUILD_LIBJPEG) +BUILD_LIBRARIES += $(BUILD_LIBJAVAJPEG) ########################################################################################## @@ -1130,12 +1144,6 @@ ifeq ($(BUILD_HEADLESS), true) -I$(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/sun/jdga \ $(foreach dir, $(LIBAWT_HEADLESS_DIRS), -I$(dir)) - ifeq ($(OPENJDK_TARGET_OS), macosx) - LIBAWT_HEADLESS_CFLAGS += \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ - -F/System/Library/Frameworks/ApplicationServices.framework/Frameworks - endif - LIBAWT_HEADLESS_FILES := \ awt_Font.c \ HeadlessToolkit.c \ @@ -1213,6 +1221,13 @@ ifndef BUILD_HEADLESS_ONLY GIFLIB_CFLAGS := -I$(JDK_TOPDIR)/src/share/native/sun/awt/giflib endif + ifeq ($(USE_EXTERNAL_LIBJPEG), true) + LIBJPEG_LDFLAGS := -ljpeg + else + LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/share/native/sun/awt/image/jpeg + LIBJPEG_CFLAGS := -I$(JDK_TOPDIR)/src/share/native/sun/awt/image/jpeg + endif + ifeq ($(USE_EXTERNAL_LIBPNG), false) LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/share/native/sun/awt/libpng LIBPNG_CFLAGS := -I$(JDK_TOPDIR)/src/share/native/sun/awt/libpng @@ -1229,8 +1244,7 @@ ifndef BUILD_HEADLESS_ONLY ifeq ($(OPENJDK_TARGET_OS), macosx) LIBSPLASHSCREEN_CFLAGS := -I$(JDK_TOPDIR)/src/macosx/native/sun/awt/splashscreen \ - $(LIBSPLASHSCREEN_CFLAGS) \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks + $(LIBSPLASHSCREEN_CFLAGS) LIBSPLASHSCREEN_CFLAGS += -DWITH_MACOSX LIBSPLASHSCREEN_CFLAGS += -I$(JDK_TOPDIR)/src/macosx/native/sun/osxapp @@ -1260,7 +1274,6 @@ ifndef BUILD_HEADLESS_ONLY -framework ApplicationServices \ -framework Foundation \ -framework Cocoa \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ -framework JavaNativeFoundation else ifeq ($(OPENJDK_TARGET_OS), windows) LIBSPLASHSCREEN_LDFLAGS_SUFFIX += kernel32.lib user32.lib gdi32.lib delayimp.lib -DELAYLOAD:user32.dll @@ -1276,12 +1289,12 @@ ifndef BUILD_HEADLESS_ONLY LANG := C, \ OPTIMIZATION := LOW, \ CFLAGS := $(LIBSPLASHSCREEN_CFLAGS) $(CFLAGS_JDKLIB) \ - $(GIFLIB_CFLAGS) $(PNG_CFLAGS), \ + $(GIFLIB_CFLAGS) $(LIBJPEG_CFLAGS) $(PNG_CFLAGS), \ MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libsplashscreen/mapfile-vers, \ LDFLAGS := $(LDFLAGS_JDKLIB) \ $(call SET_SHARED_LIBRARY_ORIGIN), \ LDFLAGS_SUFFIX := $(LIBSPLASHSCREEN_LDFLAGS_SUFFIX) $(LIBZ) \ - $(GIFLIB_LDFLAGS) $(PNG_LIBS), \ + $(GIFLIB_LDFLAGS) $(LIBJPEG_LDFLAGS) $(PNG_LIBS), \ LDFLAGS_SUFFIX_solaris := -lc, \ VERSIONINFO_RESOURCE := $(JDK_TOPDIR)/src/windows/resource/version.rc, \ RC_FLAGS := $(RC_FLAGS) \ @@ -1445,9 +1458,7 @@ ifeq ($(OPENJDK_TARGET_OS), macosx) -I$(JDK_TOPDIR)/src/share/native/sun/awt/image/cvutils \ -I$(JDK_TOPDIR)/src/share/native/sun/java2d/loops \ -I$(JDK_TOPDIR)/src/share/native/sun/java2d/pipe \ - -I$(JDK_TOPDIR)/src/share/native/sun/awt/debug \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ - -F/System/Library/Frameworks/ApplicationServices.framework/Frameworks, \ + -I$(JDK_TOPDIR)/src/share/native/sun/awt/debug, \ LDFLAGS := $(LDFLAGS_JDKLIB) \ $(call SET_SHARED_LIBRARY_ORIGIN), \ LDFLAGS_SUFFIX_macosx := -lawt -lmlib_image -losxapp -ljvm $(LIBM) \ @@ -1458,7 +1469,6 @@ ifeq ($(OPENJDK_TARGET_OS), macosx) -framework Cocoa \ -framework Security \ -framework ExceptionHandling \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ -framework JavaNativeFoundation \ -framework JavaRuntimeSupport \ -framework OpenGL \ @@ -1491,8 +1501,7 @@ ifeq ($(OPENJDK_TARGET_OS), macosx) CFLAGS := $(CFLAGS_JDKLIB) \ -I$(JDK_TOPDIR)/src/macosx/native/com/apple/laf \ -I$(JDK_TOPDIR)/src/macosx/native/sun/osxapp \ - -I$(JDK_TOPDIR)/src/macosx/native/sun/awt \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks, \ + -I$(JDK_TOPDIR)/src/macosx/native/sun/awt, \ LDFLAGS := $(LDFLAGS_JDKLIB) \ $(call SET_SHARED_LIBRARY_ORIGIN) \ -Xlinker -rpath -Xlinker @loader_path, \ @@ -1500,7 +1509,6 @@ ifeq ($(OPENJDK_TARGET_OS), macosx) -framework Cocoa \ -framework Carbon \ -framework ApplicationServices \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ -framework JavaNativeFoundation \ -framework JavaRuntimeSupport \ -ljava -ljvm, \ diff --git a/jdk/make/lib/CoreLibraries.gmk b/jdk/make/lib/CoreLibraries.gmk index aa4d90c3e14..871e95a0dff 100644 --- a/jdk/make/lib/CoreLibraries.gmk +++ b/jdk/make/lib/CoreLibraries.gmk @@ -306,7 +306,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBPREFS, \ LDFLAGS_SUFFIX_solaris := -ljvm -ljava -lc, \ LDFLAGS_SUFFIX_aix := -ljvm -ljava, \ LDFLAGS_SUFFIX_windows := advapi32.lib jvm.lib $(WIN_JAVA_LIB), \ - LDFLAGS_SUFFIX_macosx := -ljvm -framework CoreFoundation, \ + LDFLAGS_SUFFIX_macosx := -ljvm -framework CoreFoundation -framework Foundation, \ VERSIONINFO_RESOURCE := $(JDK_TOPDIR)/src/windows/resource/version.rc, \ RC_FLAGS := $(RC_FLAGS) \ -D "JDK_FNAME=prefs.dll" \ diff --git a/jdk/make/lib/PlatformLibraries.gmk b/jdk/make/lib/PlatformLibraries.gmk index e78a9833dd5..e3fc71c4bf9 100644 --- a/jdk/make/lib/PlatformLibraries.gmk +++ b/jdk/make/lib/PlatformLibraries.gmk @@ -32,14 +32,11 @@ ifeq ($(OPENJDK_TARGET_OS), macosx) LANG := C, \ OPTIMIZATION := LOW, \ CFLAGS := $(CFLAGS_JDKLIB) \ - -I$(JDK_TOPDIR)/src/macosx/native/apple/applescript \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ - -F/System/Library/Frameworks/ApplicationServices.framework/Frameworks, \ + -I$(JDK_TOPDIR)/src/macosx/native/apple/applescript, \ LDFLAGS := $(LDFLAGS_JDKLIB) \ $(call SET_SHARED_LIBRARY_ORIGIN), \ LDFLAGS_SUFFIX := -framework Cocoa \ -framework Carbon \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ -framework JavaNativeFoundation \ $(LDFLAGS_JDKLIB_SUFFIX), \ OBJECT_DIR := $(JDK_OUTPUTDIR)/objs/libAppleScriptEngine, \ @@ -63,9 +60,7 @@ ifeq ($(OPENJDK_TARGET_OS), macosx) OPTIMIZATION := LOW, \ CFLAGS := $(CFLAGS_JDKLIB) \ -I$(JDK_TOPDIR)/src/macosx/native/sun/osxapp \ - -I$(JDK_OUTPUTDIR)/gensrc_headers_icons \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ - -F/System/Library/Frameworks/ApplicationServices.framework/Frameworks, \ + -I$(JDK_OUTPUTDIR)/gensrc_headers_icons, \ LDFLAGS := $(LDFLAGS_JDKLIB) \ $(call SET_SHARED_LIBRARY_ORIGIN), \ LDFLAGS_SUFFIX_macosx := \ @@ -76,7 +71,6 @@ ifeq ($(OPENJDK_TARGET_OS), macosx) -framework Cocoa \ -framework Security \ -framework ExceptionHandling \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ -framework JavaNativeFoundation \ -framework JavaRuntimeSupport \ -framework OpenGL \ @@ -107,16 +101,13 @@ ifeq ($(OPENJDK_TARGET_OS), macosx) OPTIMIZATION := LOW, \ CFLAGS := $(CFLAGS_JDKLIB) \ $(foreach dir, $(LIBOSX_DIRS), -I$(dir)) \ - -I$(JDK_TOPDIR)/src/macosx/native/sun/osxapp \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ - -F/System/Library/Frameworks/ApplicationServices.framework/Frameworks, \ + -I$(JDK_TOPDIR)/src/macosx/native/sun/osxapp, \ LDFLAGS := $(LDFLAGS_JDKLIB) \ $(call SET_SHARED_LIBRARY_ORIGIN), \ LDFLAGS_SUFFIX_macosx := \ -losxapp \ -framework Cocoa \ -framework ApplicationServices \ - -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ -framework JavaNativeFoundation \ -framework JavaRuntimeSupport \ -framework Security \ diff --git a/jdk/make/lib/SecurityLibraries.gmk b/jdk/make/lib/SecurityLibraries.gmk index 66c55b8264d..eeb062a30da 100644 --- a/jdk/make/lib/SecurityLibraries.gmk +++ b/jdk/make/lib/SecurityLibraries.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -130,7 +130,7 @@ ifneq ($(BUILD_CRYPTO), no) BUILD_LIBKRB5_NAME := osxkrb5 BUILD_LIBKRB5_SRC := $(JDK_TOPDIR)/src/share/native/sun/security/krb5 \ $(JDK_TOPDIR)/src/macosx/native/sun/security/krb5 - BUILD_LIBKRB5_LIBS := -F/System/Library/Frameworks/JavaVM.framework/Frameworks \ + BUILD_LIBKRB5_LIBS := \ -framework JavaNativeFoundation \ -framework Cocoa \ -framework SystemConfiguration \ @@ -147,7 +147,6 @@ ifneq ($(BUILD_CRYPTO), no) CFLAGS := $(CFLAGS_JDKLIB) \ -I$(JDK_TOPDIR)/src/share/native/sun/security/krb5, \ CFLAGS_windows := -I$(JDK_TOPDIR)/src/windows/native/sun/security/krb5, \ - CFLAGS_macosx := -F/System/Library/Frameworks/JavaVM.framework/Frameworks, \ LDFLAGS := $(LDFLAGS_JDKLIB) \ $(call SET_SHARED_LIBRARY_ORIGIN), \ LDFLAGS_SUFFIX := $(BUILD_LIBKRB5_LIBS), \ diff --git a/jdk/make/mapfiles/libawt/mapfile-vers b/jdk/make/mapfiles/libawt/mapfile-vers index b1c6a39ec1e..636c255c6c6 100644 --- a/jdk/make/mapfiles/libawt/mapfile-vers +++ b/jdk/make/mapfiles/libawt/mapfile-vers @@ -155,6 +155,7 @@ SUNWprivate_1.1 { g_CMpDataID; colorValueID; mul8table; + div8table; jvm; # ProcessPath entry points and data diff --git a/jdk/make/profile-includes.txt b/jdk/make/profile-includes.txt index 2d013fc26fe..17728a7f3d9 100644 --- a/jdk/make/profile-includes.txt +++ b/jdk/make/profile-includes.txt @@ -56,7 +56,6 @@ PROFILE_1_JRE_LIB_FILES := \ $(OPENJDK_TARGET_CPU_LEGACY_LIB)/server/Xusage.txt \ calendars.properties \ classlist \ - currency.data \ ext/localedata.jar \ ext/meta-index \ ext/sunec.jar \ diff --git a/jdk/make/src/classes/build/tools/generatenimbus/PainterGenerator.java b/jdk/make/src/classes/build/tools/generatenimbus/PainterGenerator.java index 07b016d75ff..265ab3c9e65 100644 --- a/jdk/make/src/classes/build/tools/generatenimbus/PainterGenerator.java +++ b/jdk/make/src/classes/build/tools/generatenimbus/PainterGenerator.java @@ -57,6 +57,9 @@ import java.util.Map; * @author Jasper Potts */ public class PainterGenerator { + + private static final boolean debug = false; + //a handful of counters, incremented whenever the associated object type is encounted. //These counters form the basis of the field and method suffixes. //These are all 1 based, because I felt like it :-) @@ -384,16 +387,24 @@ public class PainterGenerator { } if (Float.isNaN(r)) { - System.err.println("[Error] Encountered NaN: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + if (debug) { + System.err.println("[Error] Encountered NaN: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + } return 0; } else if (Float.isInfinite(r)) { - System.err.println("[Error] Encountered Infinity: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + if (debug) { + System.err.println("[Error] Encountered Infinity: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + } return 0; } else if (r < 0) { - System.err.println("[Error] encoded value was less than 0: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + if (debug) { + System.err.println("[Error] encoded value was less than 0: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + } return 0; } else if (r > 3) { - System.err.println("[Error] encoded value was greater than 3: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + if (debug) { + System.err.println("[Error] encoded value was greater than 3: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + } return 3; } else { return r; diff --git a/jdk/make/src/classes/build/tools/tzdb/ChronoField.java b/jdk/make/src/classes/build/tools/tzdb/ChronoField.java deleted file mode 100644 index 7ce34bbfae2..00000000000 --- a/jdk/make/src/classes/build/tools/tzdb/ChronoField.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of JSR-310 nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package build.tools.tzdb; - -/** - * A standard set of date/time fields. - * - * @since 1.8 - */ -enum ChronoField { - - /** - * The second-of-minute. - *

- * This counts the second within the minute, from 0 to 59. - * This field has the same meaning for all calendar systems. - */ - SECOND_OF_MINUTE("SecondOfMinute", 0, 59), - - /** - * The second-of-day. - *

- * This counts the second within the day, from 0 to (24 * 60 * 60) - 1. - * This field has the same meaning for all calendar systems. - */ - SECOND_OF_DAY("SecondOfDay", 0, 86400 - 1), - - /** - * The minute-of-hour. - *

- * This counts the minute within the hour, from 0 to 59. - * This field has the same meaning for all calendar systems. - */ - MINUTE_OF_HOUR("MinuteOfHour", 0, 59), - - /** - * The hour-of-day. - *

- * This counts the hour within the day, from 0 to 23. - * This is the hour that would be observed on a standard 24-hour digital clock. - * This field has the same meaning for all calendar systems. - */ - HOUR_OF_DAY("HourOfDay", 0, 23), - - - /** - * The day-of-month. - *

- * This represents the concept of the day within the month. - * In the default ISO calendar system, this has values from 1 to 31 in most months. - * April, June, September, November have days from 1 to 30, while February has days - * from 1 to 28, or 29 in a leap year. - *

- * Non-ISO calendar systems should implement this field using the most recognized - * day-of-month values for users of the calendar system. - * Normally, this is a count of days from 1 to the length of the month. - */ - DAY_OF_MONTH("DayOfMonth", 1, 31), - - /** - * The month-of-year, such as March. - *

- * This represents the concept of the month within the year. - * In the default ISO calendar system, this has values from January (1) to December (12). - *

- * Non-ISO calendar systems should implement this field using the most recognized - * month-of-year values for users of the calendar system. - * Normally, this is a count of months starting from 1. - */ - MONTH_OF_YEAR("MonthOfYear", 1, 12), - - /** - * The proleptic year, such as 2012. - *

- * This represents the concept of the year, counting sequentially and using negative numbers. - * The proleptic year is not interpreted in terms of the era. - * See {@link #YEAR_OF_ERA} for an example showing the mapping from proleptic year to year-of-era. - *

- * The standard mental model for a date is based on three concepts - year, month and day. - * These map onto the {@code YEAR}, {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH} fields. - * Note that there is no reference to eras. - * The full model for a date requires four concepts - era, year, month and day. These map onto - * the {@code ERA}, {@code YEAR_OF_ERA}, {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH} fields. - * Whether this field or {@code YEAR_OF_ERA} is used depends on which mental model is being used. - * See {@link ChronoLocalDate} for more discussion on this topic. - *

- * Non-ISO calendar systems should implement this field as follows. - * If the calendar system has only two eras, before and after a fixed date, then the - * proleptic-year value must be the same as the year-of-era value for the later era, - * and increasingly negative for the earlier era. - * If the calendar system has more than two eras, then the proleptic-year value may be - * defined with any appropriate value, although defining it to be the same as ISO may be - * the best option. - */ - YEAR("Year", -999_999_999, 999_999_999); - - private final String name; - private final int min; - private final int max; - - private ChronoField(String name, int min, int max) { - this.name = name; - this.min= min; - this.max= max; - } - - /** - * Checks that the specified value is valid for this field. - *

- * - * @param value the value to check - * @return the value that was passed in - */ - public int checkValidValue(int value) { - if (value >= min && value <= max) { - return value; - } - throw new DateTimeException("Invalid value for " + name + " value: " + value); - } - - public String toString() { - return name; - } - -} diff --git a/jdk/make/src/classes/build/tools/tzdb/DateTimeException.java b/jdk/make/src/classes/build/tools/tzdb/DateTimeException.java deleted file mode 100644 index 2b7674df3ff..00000000000 --- a/jdk/make/src/classes/build/tools/tzdb/DateTimeException.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * This file is available under and governed by the GNU General Public - * License version 2 only, as published by the Free Software Foundation. - * However, the following notice accompanied the original version of this - * file: - * - * Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of JSR-310 nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package build.tools.tzdb; - -/** - * Exception used to indicate a problem while calculating a date-time. - *

- * This exception is used to indicate problems with creating, querying - * and manipulating date-time objects. - * - * @since 1.8 - */ -class DateTimeException extends RuntimeException { - - /** - * Serialization version. - */ - private static final long serialVersionUID = -1632418723876261839L; - - /** - * Constructs a new date-time exception with the specified message. - * - * @param message the message to use for this exception, may be null - */ - public DateTimeException(String message) { - super(message); - } - - /** - * Constructs a new date-time exception with the specified message and cause. - * - * @param message the message to use for this exception, may be null - * @param cause the cause of the exception, may be null - */ - public DateTimeException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/jdk/make/src/classes/build/tools/tzdb/LocalDate.java b/jdk/make/src/classes/build/tools/tzdb/LocalDate.java deleted file mode 100644 index fedab6d3156..00000000000 --- a/jdk/make/src/classes/build/tools/tzdb/LocalDate.java +++ /dev/null @@ -1,363 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * This file is available under and governed by the GNU General Public - * License version 2 only, as published by the Free Software Foundation. - * However, the following notice accompanied the original version of this - * file: - * - * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of JSR-310 nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package build.tools.tzdb; - -import static build.tools.tzdb.Utils.*; -import static build.tools.tzdb.LocalTime.SECONDS_PER_DAY; -import static build.tools.tzdb.ChronoField.DAY_OF_MONTH; -import static build.tools.tzdb.ChronoField.MONTH_OF_YEAR; -import static build.tools.tzdb.ChronoField.YEAR; - -import java.util.Objects; - -/** - * A date without a time-zone in the ISO-8601 calendar system, - * such as {@code 2007-12-03}. - * - * @since 1.8 - */ -final class LocalDate { - - /** - * The minimum supported {@code LocalDate}, '-999999999-01-01'. - * This could be used by an application as a "far past" date. - */ - public static final LocalDate MIN = new LocalDate(YEAR_MIN_VALUE, 1, 1); - /** - * The maximum supported {@code LocalDate}, '+999999999-12-31'. - * This could be used by an application as a "far future" date. - */ - public static final LocalDate MAX = new LocalDate(YEAR_MAX_VALUE, 12, 31); - - /** - * The number of days in a 400 year cycle. - */ - private static final int DAYS_PER_CYCLE = 146097; - /** - * The number of days from year zero to year 1970. - * There are five 400 year cycles from year zero to 2000. - * There are 7 leap years from 1970 to 2000. - */ - static final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L); - - /** - * The year. - */ - private final int year; - /** - * The month-of-year. - */ - private final short month; - /** - * The day-of-month. - */ - private final short day; - - /** - * Obtains an instance of {@code LocalDate} from a year, month and day. - *

- * The day must be valid for the year and month, otherwise an exception will be thrown. - * - * @param year the year to represent, from MIN_YEAR to MAX_YEAR - * @param month the month-of-year to represent, from 1 (January) to 12 (December) - * @param dayOfMonth the day-of-month to represent, from 1 to 31 - * @return the local date, not null - * @throws DateTimeException if the value of any field is out of range - * @throws DateTimeException if the day-of-month is invalid for the month-year - */ - public static LocalDate of(int year, int month, int dayOfMonth) { - YEAR.checkValidValue(year); - MONTH_OF_YEAR.checkValidValue(month); - DAY_OF_MONTH.checkValidValue(dayOfMonth); - if (dayOfMonth > 28 && dayOfMonth > lengthOfMonth(month, isLeapYear(year))) { - if (dayOfMonth == 29) { - throw new DateTimeException("Invalid date 'February 29' as '" + year + "' is not a leap year"); - } else { - throw new DateTimeException("Invalid date '" + month + " " + dayOfMonth + "'"); - } - } - return new LocalDate(year, month, dayOfMonth); - } - - /** - * Constructor, previously validated. - * - * @param year the year to represent, from MIN_YEAR to MAX_YEAR - * @param month the month-of-year to represent, not null - * @param dayOfMonth the day-of-month to represent, valid for year-month, from 1 to 31 - */ - private LocalDate(int year, int month, int dayOfMonth) { - this.year = year; - this.month = (short) month; - this.day = (short) dayOfMonth; - } - - /** - * Gets the year field. - *

- * This method returns the primitive {@code int} value for the year. - *

- * The year returned by this method is proleptic as per {@code get(YEAR)}. - * To obtain the year-of-era, use {@code get(YEAR_OF_ERA}. - * - * @return the year, from MIN_YEAR to MAX_YEAR - */ - public int getYear() { - return year; - } - - /** - * Gets the month-of-year field as an int from 1 to 12. - * - * @return the month-of-year - */ - public int getMonth() { - return month; - } - - /** - * Gets the day-of-month field. - *

- * This method returns the primitive {@code int} value for the day-of-month. - * - * @return the day-of-month, from 1 to 31 - */ - public int getDayOfMonth() { - return day; - } - - /** - * Gets the day-of-week field, which is an int from 1 to 7. - * - * @return the day-of-week - */ - public int getDayOfWeek() { - return (int)floorMod(toEpochDay() + 3, 7) + 1; - } - - /** - * Returns a copy of this {@code LocalDate} with the specified number of days added. - *

- * This method adds the specified amount to the days field incrementing the - * month and year fields as necessary to ensure the result remains valid. - * The result is only invalid if the maximum/minimum year is exceeded. - *

- * For example, 2008-12-31 plus one day would result in 2009-01-01. - *

- * This instance is immutable and unaffected by this method call. - * - * @param daysToAdd the days to add, may be negative - * @return a {@code LocalDate} based on this date with the days added, not null - * @throws DateTimeException if the result exceeds the supported date range - */ - public LocalDate plusDays(long daysToAdd) { - if (daysToAdd == 0) { - return this; - } - long mjDay = addExact(toEpochDay(), daysToAdd); - return LocalDate.ofEpochDay(mjDay); - } - - /** - * Returns a copy of this {@code LocalDate} with the specified number of days subtracted. - *

- * This method subtracts the specified amount from the days field decrementing the - * month and year fields as necessary to ensure the result remains valid. - * The result is only invalid if the maximum/minimum year is exceeded. - *

- * For example, 2009-01-01 minus one day would result in 2008-12-31. - *

- * This instance is immutable and unaffected by this method call. - * - * @param daysToSubtract the days to subtract, may be negative - * @return a {@code LocalDate} based on this date with the days subtracted, not null - * @throws DateTimeException if the result exceeds the supported date range - */ - public LocalDate minusDays(long daysToSubtract) { - return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract)); - } - - /** - * Obtains an instance of {@code LocalDate} from the epoch day count. - *

- * The Epoch Day count is a simple incrementing count of days - * where day 0 is 1970-01-01. Negative numbers represent earlier days. - * - * @param epochDay the Epoch Day to convert, based on the epoch 1970-01-01 - * @return the local date, not null - * @throws DateTimeException if the epoch days exceeds the supported date range - */ - public static LocalDate ofEpochDay(long epochDay) { - long zeroDay = epochDay + DAYS_0000_TO_1970; - // find the march-based year - zeroDay -= 60; // adjust to 0000-03-01 so leap day is at end of four year cycle - long adjust = 0; - if (zeroDay < 0) { - // adjust negative years to positive for calculation - long adjustCycles = (zeroDay + 1) / DAYS_PER_CYCLE - 1; - adjust = adjustCycles * 400; - zeroDay += -adjustCycles * DAYS_PER_CYCLE; - } - long yearEst = (400 * zeroDay + 591) / DAYS_PER_CYCLE; - long doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400); - if (doyEst < 0) { - // fix estimate - yearEst--; - doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400); - } - yearEst += adjust; // reset any negative year - int marchDoy0 = (int) doyEst; - - // convert march-based values back to january-based - int marchMonth0 = (marchDoy0 * 5 + 2) / 153; - int month = (marchMonth0 + 2) % 12 + 1; - int dom = marchDoy0 - (marchMonth0 * 306 + 5) / 10 + 1; - yearEst += marchMonth0 / 10; - - // check year now we are certain it is correct - int year = YEAR.checkValidValue((int)yearEst); - return new LocalDate(year, month, dom); - } - - public long toEpochDay() { - long y = year; - long m = month; - long total = 0; - total += 365 * y; - if (y >= 0) { - total += (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400; - } else { - total -= y / -4 - y / -100 + y / -400; - } - total += ((367 * m - 362) / 12); - total += day - 1; - if (m > 2) { - total--; - if (isLeapYear(year) == false) { - total--; - } - } - return total - DAYS_0000_TO_1970; - } - - /** - * Compares this date to another date. - *

- * The comparison is primarily based on the date, from earliest to latest. - * It is "consistent with equals", as defined by {@link Comparable}. - *

- * If all the dates being compared are instances of {@code LocalDate}, - * then the comparison will be entirely based on the date. - * If some dates being compared are in different chronologies, then the - * chronology is also considered, see {@link java.time.temporal.ChronoLocalDate#compareTo}. - * - * @param other the other date to compare to, not null - * @return the comparator value, negative if less, positive if greater - */ - public int compareTo(LocalDate otherDate) { - int cmp = (year - otherDate.year); - if (cmp == 0) { - cmp = (month - otherDate.month); - if (cmp == 0) { - cmp = (day - otherDate.day); - } - } - return cmp; - } - - /** - * Checks if this date is equal to another date. - *

- * Compares this {@code LocalDate} with another ensuring that the date is the same. - *

- * Only objects of type {@code LocalDate} are compared, other types return false. - * To compare the dates of two {@code TemporalAccessor} instances, including dates - * in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator. - * - * @param obj the object to check, null returns false - * @return true if this is equal to the other date - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof LocalDate) { - return compareTo((LocalDate) obj) == 0; - } - return false; - } - - /** - * A hash code for this date. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - int yearValue = year; - int monthValue = month; - int dayValue = day; - return (yearValue & 0xFFFFF800) ^ ((yearValue << 11) + (monthValue << 6) + (dayValue)); - } - -} diff --git a/jdk/make/src/classes/build/tools/tzdb/LocalDateTime.java b/jdk/make/src/classes/build/tools/tzdb/LocalDateTime.java deleted file mode 100644 index ced37b72613..00000000000 --- a/jdk/make/src/classes/build/tools/tzdb/LocalDateTime.java +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * This file is available under and governed by the GNU General Public - * License version 2 only, as published by the Free Software Foundation. - * However, the following notice accompanied the original version of this - * file: - * - * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of JSR-310 nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package build.tools.tzdb; - -import static build.tools.tzdb.Utils.*; -import static build.tools.tzdb.LocalTime.HOURS_PER_DAY; -import static build.tools.tzdb.LocalTime.MICROS_PER_DAY; -import static build.tools.tzdb.LocalTime.MILLIS_PER_DAY; -import static build.tools.tzdb.LocalTime.MINUTES_PER_DAY; -import static build.tools.tzdb.LocalTime.SECONDS_PER_DAY; -import static build.tools.tzdb.LocalTime.SECONDS_PER_MINUTE; -import static build.tools.tzdb.LocalTime.SECONDS_PER_HOUR; - -import java.util.Objects; - -/** - * A date-time without a time-zone in the ISO-8601 calendar system, - * such as {@code 2007-12-03T10:15:30}. - * - * @since 1.8 - */ -final class LocalDateTime { - - /** - * The minimum supported {@code LocalDateTime}, '-999999999-01-01T00:00:00'. - * This is the local date-time of midnight at the start of the minimum date. - * This combines {@link LocalDate#MIN} and {@link LocalTime#MIN}. - * This could be used by an application as a "far past" date-time. - */ - public static final LocalDateTime MIN = LocalDateTime.of(LocalDate.MIN, LocalTime.MIN); - /** - * The maximum supported {@code LocalDateTime}, '+999999999-12-31T23:59:59.999999999'. - * This is the local date-time just before midnight at the end of the maximum date. - * This combines {@link LocalDate#MAX} and {@link LocalTime#MAX}. - * This could be used by an application as a "far future" date-time. - */ - public static final LocalDateTime MAX = LocalDateTime.of(LocalDate.MAX, LocalTime.MAX); - - /** - * The date part. - */ - private final LocalDate date; - /** - * The time part. - */ - private final LocalTime time; - - /** - * Obtains an instance of {@code LocalDateTime} from year, month, - * day, hour and minute, setting the second and nanosecond to zero. - *

- * The day must be valid for the year and month, otherwise an exception will be thrown. - * The second and nanosecond fields will be set to zero. - * - * @param year the year to represent, from MIN_YEAR to MAX_YEAR - * @param month the month-of-year to represent, from 1 (January) to 12 (December) - * @param dayOfMonth the day-of-month to represent, from 1 to 31 - * @param hour the hour-of-day to represent, from 0 to 23 - * @param minute the minute-of-hour to represent, from 0 to 59 - * @return the local date-time, not null - * @throws DateTimeException if the value of any field is out of range - * @throws DateTimeException if the day-of-month is invalid for the month-year - */ - public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute) { - LocalDate date = LocalDate.of(year, month, dayOfMonth); - LocalTime time = LocalTime.of(hour, minute); - return new LocalDateTime(date, time); - } - - /** - * Obtains an instance of {@code LocalDateTime} from a date and time. - * - * @param date the local date, not null - * @param time the local time, not null - * @return the local date-time, not null - */ - public static LocalDateTime of(LocalDate date, LocalTime time) { - Objects.requireNonNull(date, "date"); - Objects.requireNonNull(time, "time"); - return new LocalDateTime(date, time); - } - - /** - * Obtains an instance of {@code LocalDateTime} using seconds from the - * epoch of 1970-01-01T00:00:00Z. - *

- * This allows the {@link ChronoField#INSTANT_SECONDS epoch-second} field - * to be converted to a local date-time. This is primarily intended for - * low-level conversions rather than general application usage. - * - * @param epochSecond the number of seconds from the epoch of 1970-01-01T00:00:00Z - * @param nanoOfSecond the nanosecond within the second, from 0 to 999,999,999 - * @param offset the zone offset, not null - * @return the local date-time, not null - * @throws DateTimeException if the result exceeds the supported range - */ - public static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset) { - Objects.requireNonNull(offset, "offset"); - long localSecond = epochSecond + offset.getTotalSeconds(); // overflow caught later - long localEpochDay = floorDiv(localSecond, SECONDS_PER_DAY); - int secsOfDay = (int)floorMod(localSecond, SECONDS_PER_DAY); - LocalDate date = LocalDate.ofEpochDay(localEpochDay); - LocalTime time = LocalTime.ofSecondOfDay(secsOfDay); // ignore nano - return new LocalDateTime(date, time); - } - - /** - * Constructor. - * - * @param date the date part of the date-time, validated not null - * @param time the time part of the date-time, validated not null - */ - private LocalDateTime(LocalDate date, LocalTime time) { - this.date = date; - this.time = time; - } - - /** - * Returns a copy of this date-time with the new date and time, checking - * to see if a new object is in fact required. - * - * @param newDate the date of the new date-time, not null - * @param newTime the time of the new date-time, not null - * @return the date-time, not null - */ - private LocalDateTime with(LocalDate newDate, LocalTime newTime) { - if (date == newDate && time == newTime) { - return this; - } - return new LocalDateTime(newDate, newTime); - } - - /** - * Gets the {@code LocalDate} part of this date-time. - *

- * This returns a {@code LocalDate} with the same year, month and day - * as this date-time. - * - * @return the date part of this date-time, not null - */ - public LocalDate getDate() { - return date; - } - - /** - * Gets the year field. - *

- * This method returns the primitive {@code int} value for the year. - *

- * The year returned by this method is proleptic as per {@code get(YEAR)}. - * To obtain the year-of-era, use {@code get(YEAR_OF_ERA}. - * - * @return the year, from MIN_YEAR to MAX_YEAR - */ - public int getYear() { - return date.getYear(); - } - - /** - * Gets the month-of-year field as an int from 1 to 12. - * - * @return the month-of-year - */ - public int getMonth() { - return date.getMonth(); - } - - /** - * Gets the day-of-month field. - *

- * This method returns the primitive {@code int} value for the day-of-month. - * - * @return the day-of-month, from 1 to 31 - */ - public int getDayOfMonth() { - return date.getDayOfMonth(); - } - - /** - * Gets the day-of-week field, which is an integer from 1 to 7. - * - * @return the day-of-week, from 1 to 7 - */ - public int getDayOfWeek() { - return date.getDayOfWeek(); - } - - /** - * Gets the {@code LocalTime} part of this date-time. - *

- * This returns a {@code LocalTime} with the same hour, minute, second and - * nanosecond as this date-time. - * - * @return the time part of this date-time, not null - */ - public LocalTime getTime() { - return time; - } - - /** - * Gets the hour-of-day field. - * - * @return the hour-of-day, from 0 to 23 - */ - public int getHour() { - return time.getHour(); - } - - /** - * Gets the minute-of-hour field. - * - * @return the minute-of-hour, from 0 to 59 - */ - public int getMinute() { - return time.getMinute(); - } - - /** - * Gets the second-of-minute field. - * - * @return the second-of-minute, from 0 to 59 - */ - public int getSecond() { - return time.getSecond(); - } - - /** - * Converts this date-time to the number of seconds from the epoch - * of 1970-01-01T00:00:00Z. - *

- * This combines this local date-time and the specified offset to calculate the - * epoch-second value, which is the number of elapsed seconds from 1970-01-01T00:00:00Z. - * Instants on the time-line after the epoch are positive, earlier are negative. - *

- * This default implementation calculates from the epoch-day of the date and the - * second-of-day of the time. - * - * @param offset the offset to use for the conversion, not null - * @return the number of seconds from the epoch of 1970-01-01T00:00:00Z - */ - public long toEpochSecond(ZoneOffset offset) { - Objects.requireNonNull(offset, "offset"); - long epochDay = getDate().toEpochDay(); - long secs = epochDay * 86400 + getTime().toSecondOfDay(); - secs -= offset.getTotalSeconds(); - return secs; - } - - /** - * Returns a copy of this {@code LocalDateTime} with the specified period in days added. - *

- * This method adds the specified amount to the days field incrementing the - * month and year fields as necessary to ensure the result remains valid. - * The result is only invalid if the maximum/minimum year is exceeded. - *

- * For example, 2008-12-31 plus one day would result in 2009-01-01. - *

- * This instance is immutable and unaffected by this method call. - * - * @param days the days to add, may be negative - * @return a {@code LocalDateTime} based on this date-time with the days added, not null - * @throws DateTimeException if the result exceeds the supported date range - */ - public LocalDateTime plusDays(long days) { - LocalDate newDate = date.plusDays(days); - return with(newDate, time); - } - - /** - * Returns a copy of this {@code LocalDateTime} with the specified period in seconds added. - *

- * This instance is immutable and unaffected by this method call. - * - * @param seconds the seconds to add, may be negative - * @return a {@code LocalDateTime} based on this date-time with the seconds added, not null - * @throws DateTimeException if the result exceeds the supported date range - */ - public LocalDateTime plusSeconds(long seconds) { - return plusWithOverflow(date, 0, 0, seconds, 1); - } - - /** - * Returns a copy of this {@code LocalDateTime} with the specified period added. - *

- * This instance is immutable and unaffected by this method call. - * - * @param newDate the new date to base the calculation on, not null - * @param hours the hours to add, may be negative - * @param minutes the minutes to add, may be negative - * @param seconds the seconds to add, may be negative - * @param nanos the nanos to add, may be negative - * @param sign the sign to determine add or subtract - * @return the combined result, not null - */ - private LocalDateTime plusWithOverflow(LocalDate newDate, long hours, long minutes, long seconds, int sign) { - if ((hours | minutes | seconds) == 0) { - return with(newDate, time); - } - long totDays = seconds / SECONDS_PER_DAY + // max/24*60*60 - minutes / MINUTES_PER_DAY + // max/24*60 - hours / HOURS_PER_DAY; // max/24 - totDays *= sign; // total max*0.4237... - long totSecs = (seconds % SECONDS_PER_DAY) + - (minutes % MINUTES_PER_DAY) * SECONDS_PER_MINUTE + - (hours % HOURS_PER_DAY) * SECONDS_PER_HOUR; - long curSoD = time.toSecondOfDay(); - totSecs = totSecs * sign + curSoD; // total 432000000000000 - totDays += floorDiv(totSecs, SECONDS_PER_DAY); - - int newSoD = (int)floorMod(totSecs, SECONDS_PER_DAY); - LocalTime newTime = (newSoD == curSoD ? time : LocalTime.ofSecondOfDay(newSoD)); - return with(newDate.plusDays(totDays), newTime); - } - - /** - * Compares this date-time to another date-time. - *

- * The comparison is primarily based on the date-time, from earliest to latest. - * It is "consistent with equals", as defined by {@link Comparable}. - *

- * If all the date-times being compared are instances of {@code LocalDateTime}, - * then the comparison will be entirely based on the date-time. - * If some dates being compared are in different chronologies, then the - * chronology is also considered, see {@link ChronoLocalDateTime#compareTo}. - * - * @param other the other date-time to compare to, not null - * @return the comparator value, negative if less, positive if greater - */ - public int compareTo(LocalDateTime other) { - int cmp = date.compareTo(other.getDate()); - if (cmp == 0) { - cmp = time.compareTo(other.getTime()); - } - return cmp; - } - - /** - * Checks if this date-time is equal to another date-time. - *

- * Compares this {@code LocalDateTime} with another ensuring that the date-time is the same. - * Only objects of type {@code LocalDateTime} are compared, other types return false. - * - * @param obj the object to check, null returns false - * @return true if this is equal to the other date-time - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof LocalDateTime) { - LocalDateTime other = (LocalDateTime) obj; - return date.equals(other.date) && time.equals(other.time); - } - return false; - } - - /** - * A hash code for this date-time. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - return date.hashCode() ^ time.hashCode(); - } - -} diff --git a/jdk/make/src/classes/build/tools/tzdb/LocalTime.java b/jdk/make/src/classes/build/tools/tzdb/LocalTime.java deleted file mode 100644 index 0fc31868944..00000000000 --- a/jdk/make/src/classes/build/tools/tzdb/LocalTime.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * This file is available under and governed by the GNU General Public - * License version 2 only, as published by the Free Software Foundation. - * However, the following notice accompanied the original version of this - * file: - * - * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of JSR-310 nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package build.tools.tzdb; - -import static build.tools.tzdb.ChronoField.HOUR_OF_DAY; -import static build.tools.tzdb.ChronoField.MINUTE_OF_HOUR; -import static build.tools.tzdb.ChronoField.SECOND_OF_MINUTE; -import static build.tools.tzdb.ChronoField.SECOND_OF_DAY; - -import java.util.Objects; - -/** - * A time without time-zone in the ISO-8601 calendar system, - * such as {@code 10:15:30}. - * - */ -final class LocalTime { - - /** - * The minimum supported {@code LocalTime}, '00:00'. - * This is the time of midnight at the start of the day. - */ - public static final LocalTime MIN; - /** - * The minimum supported {@code LocalTime}, '23:59:59.999999999'. - * This is the time just before midnight at the end of the day. - */ - public static final LocalTime MAX; - /** - * The time of midnight at the start of the day, '00:00'. - */ - public static final LocalTime MIDNIGHT; - /** - * The time of noon in the middle of the day, '12:00'. - */ - public static final LocalTime NOON; - /** - * Constants for the local time of each hour. - */ - private static final LocalTime[] HOURS = new LocalTime[24]; - static { - for (int i = 0; i < HOURS.length; i++) { - HOURS[i] = new LocalTime(i, 0, 0); - } - MIDNIGHT = HOURS[0]; - NOON = HOURS[12]; - MIN = HOURS[0]; - MAX = new LocalTime(23, 59, 59); - } - - /** - * Hours per day. - */ - static final int HOURS_PER_DAY = 24; - /** - * Minutes per hour. - */ - static final int MINUTES_PER_HOUR = 60; - /** - * Minutes per day. - */ - static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * HOURS_PER_DAY; - /** - * Seconds per minute. - */ - static final int SECONDS_PER_MINUTE = 60; - /** - * Seconds per hour. - */ - static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR; - /** - * Seconds per day. - */ - static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY; - /** - * Milliseconds per day. - */ - static final long MILLIS_PER_DAY = SECONDS_PER_DAY * 1000L; - /** - * Microseconds per day. - */ - static final long MICROS_PER_DAY = SECONDS_PER_DAY * 1000_000L; - - /** - * The hour. - */ - private final byte hour; - /** - * The minute. - */ - private final byte minute; - /** - * The second. - */ - private final byte second; - - /** - * Obtains an instance of {@code LocalTime} from an hour and minute. - *

- * The second and nanosecond fields will be set to zero by this factory method. - *

- * This factory may return a cached value, but applications must not rely on this. - * - * @param hour the hour-of-day to represent, from 0 to 23 - * @param minute the minute-of-hour to represent, from 0 to 59 - * @return the local time, not null - * @throws DateTimeException if the value of any field is out of range - */ - public static LocalTime of(int hour, int minute) { - HOUR_OF_DAY.checkValidValue(hour); - if (minute == 0) { - return HOURS[hour]; // for performance - } - MINUTE_OF_HOUR.checkValidValue(minute); - return new LocalTime(hour, minute, 0); - } - - /** - * Obtains an instance of {@code LocalTime} from an hour, minute and second. - *

- * The nanosecond field will be set to zero by this factory method. - *

- * This factory may return a cached value, but applications must not rely on this. - * - * @param hour the hour-of-day to represent, from 0 to 23 - * @param minute the minute-of-hour to represent, from 0 to 59 - * @param second the second-of-minute to represent, from 0 to 59 - * @return the local time, not null - * @throws DateTimeException if the value of any field is out of range - */ - public static LocalTime of(int hour, int minute, int second) { - HOUR_OF_DAY.checkValidValue(hour); - if ((minute | second) == 0) { - return HOURS[hour]; // for performance - } - MINUTE_OF_HOUR.checkValidValue(minute); - SECOND_OF_MINUTE.checkValidValue(second); - return new LocalTime(hour, minute, second); - } - - /** - * Obtains an instance of {@code LocalTime} from a second-of-day value. - *

- * This factory may return a cached value, but applications must not rely on this. - * - * @param secondOfDay the second-of-day, from {@code 0} to {@code 24 * 60 * 60 - 1} - * @return the local time, not null - * @throws DateTimeException if the second-of-day value is invalid - */ - public static LocalTime ofSecondOfDay(int secondOfDay) { - SECOND_OF_DAY.checkValidValue(secondOfDay); - int hours = secondOfDay / SECONDS_PER_HOUR; - secondOfDay -= hours * SECONDS_PER_HOUR; - int minutes = secondOfDay / SECONDS_PER_MINUTE; - secondOfDay -= minutes * SECONDS_PER_MINUTE; - return create(hours, minutes, secondOfDay); - } - - - /** - * Creates a local time from the hour, minute, second and nanosecond fields. - *

- * This factory may return a cached value, but applications must not rely on this. - * - * @param hour the hour-of-day to represent, validated from 0 to 23 - * @param minute the minute-of-hour to represent, validated from 0 to 59 - * @param second the second-of-minute to represent, validated from 0 to 59 - * @return the local time, not null - */ - private static LocalTime create(int hour, int minute, int second) { - if ((minute | second) == 0) { - return HOURS[hour]; - } - return new LocalTime(hour, minute, second); - } - - /** - * Constructor, previously validated. - * - * @param hour the hour-of-day to represent, validated from 0 to 23 - * @param minute the minute-of-hour to represent, validated from 0 to 59 - * @param second the second-of-minute to represent, validated from 0 to 59 - */ - private LocalTime(int hour, int minute, int second) { - this.hour = (byte) hour; - this.minute = (byte) minute; - this.second = (byte) second; - } - - /** - * Gets the hour-of-day field. - * - * @return the hour-of-day, from 0 to 23 - */ - public int getHour() { - return hour; - } - - /** - * Gets the minute-of-hour field. - * - * @return the minute-of-hour, from 0 to 59 - */ - public int getMinute() { - return minute; - } - - /** - * Gets the second-of-minute field. - * - * @return the second-of-minute, from 0 to 59 - */ - public int getSecond() { - return second; - } - - /** - * Returns a copy of this {@code LocalTime} with the specified period in seconds added. - *

- * This adds the specified number of seconds to this time, returning a new time. - * The calculation wraps around midnight. - *

- * This instance is immutable and unaffected by this method call. - * - * @param secondstoAdd the seconds to add, may be negative - * @return a {@code LocalTime} based on this time with the seconds added, not null - */ - public LocalTime plusSeconds(long secondstoAdd) { - if (secondstoAdd == 0) { - return this; - } - int sofd = hour * SECONDS_PER_HOUR + - minute * SECONDS_PER_MINUTE + second; - int newSofd = ((int) (secondstoAdd % SECONDS_PER_DAY) + sofd + SECONDS_PER_DAY) % SECONDS_PER_DAY; - if (sofd == newSofd) { - return this; - } - int newHour = newSofd / SECONDS_PER_HOUR; - int newMinute = (newSofd / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR; - int newSecond = newSofd % SECONDS_PER_MINUTE; - return create(newHour, newMinute, newSecond); - } - - /** - * Returns a copy of this {@code LocalTime} with the specified period in seconds subtracted. - *

- * This subtracts the specified number of seconds from this time, returning a new time. - * The calculation wraps around midnight. - *

- * This instance is immutable and unaffected by this method call. - * - * @param secondsToSubtract the seconds to subtract, may be negative - * @return a {@code LocalTime} based on this time with the seconds subtracted, not null - */ - public LocalTime minusSeconds(long secondsToSubtract) { - return plusSeconds(-(secondsToSubtract % SECONDS_PER_DAY)); - } - - /** - * Extracts the time as seconds of day, - * from {@code 0} to {@code 24 * 60 * 60 - 1}. - * - * @return the second-of-day equivalent to this time - */ - public int toSecondOfDay() { - int total = hour * SECONDS_PER_HOUR; - total += minute * SECONDS_PER_MINUTE; - total += second; - return total; - } - - /** - * Compares this {@code LocalTime} to another time. - *

- * The comparison is based on the time-line position of the local times within a day. - * It is "consistent with equals", as defined by {@link Comparable}. - * - * @param other the other time to compare to, not null - * @return the comparator value, negative if less, positive if greater - * @throws NullPointerException if {@code other} is null - */ - public int compareTo(LocalTime other) { - int cmp = Integer.compare(hour, other.hour); - if (cmp == 0) { - cmp = Integer.compare(minute, other.minute); - if (cmp == 0) { - cmp = Integer.compare(second, other.second); - } - } - return cmp; - } - - /** - * Checks if this time is equal to another time. - *

- * The comparison is based on the time-line position of the time within a day. - *

- * Only objects of type {@code LocalTime} are compared, other types return false. - * To compare the date of two {@code TemporalAccessor} instances, use - * {@link ChronoField#NANO_OF_DAY} as a comparator. - * - * @param obj the object to check, null returns false - * @return true if this is equal to the other time - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof LocalTime) { - LocalTime other = (LocalTime) obj; - return hour == other.hour && minute == other.minute && - second == other.second; - } - return false; - } - - /** - * A hash code for this time. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - long sod = toSecondOfDay(); - return (int) (sod ^ (sod >>> 32)); - } - -} diff --git a/jdk/make/src/classes/build/tools/tzdb/TimeDefinition.java b/jdk/make/src/classes/build/tools/tzdb/TimeDefinition.java deleted file mode 100644 index 8a5853db3d7..00000000000 --- a/jdk/make/src/classes/build/tools/tzdb/TimeDefinition.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * This file is available under and governed by the GNU General Public - * License version 2 only, as published by the Free Software Foundation. - * However, the following notice accompanied the original version of this - * file: - * - * Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of JSR-310 nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package build.tools.tzdb; - -import java.util.Objects; - -/** - * A definition of the way a local time can be converted to the actual - * transition date-time. - *

- * Time zone rules are expressed in one of three ways: - *

    - *
  • Relative to UTC
  • - *
  • Relative to the standard offset in force
  • - *
  • Relative to the wall offset (what you would see on a clock on the wall)
  • - *

- */ -public enum TimeDefinition { - /** The local date-time is expressed in terms of the UTC offset. */ - UTC, - /** The local date-time is expressed in terms of the wall offset. */ - WALL, - /** The local date-time is expressed in terms of the standard offset. */ - STANDARD; - - /** - * Converts the specified local date-time to the local date-time actually - * seen on a wall clock. - *

- * This method converts using the type of this enum. - * The output is defined relative to the 'before' offset of the transition. - *

- * The UTC type uses the UTC offset. - * The STANDARD type uses the standard offset. - * The WALL type returns the input date-time. - * The result is intended for use with the wall-offset. - * - * @param dateTime the local date-time, not null - * @param standardOffset the standard offset, not null - * @param wallOffset the wall offset, not null - * @return the date-time relative to the wall/before offset, not null - */ - public LocalDateTime createDateTime(LocalDateTime dateTime, ZoneOffset standardOffset, ZoneOffset wallOffset) { - switch (this) { - case UTC: { - int difference = wallOffset.getTotalSeconds() - ZoneOffset.UTC.getTotalSeconds(); - return dateTime.plusSeconds(difference); - } - case STANDARD: { - int difference = wallOffset.getTotalSeconds() - standardOffset.getTotalSeconds(); - return dateTime.plusSeconds(difference); - } - default: // WALL - return dateTime; - } - } - -} diff --git a/jdk/make/src/classes/build/tools/tzdb/TzdbZoneRulesCompiler.java b/jdk/make/src/classes/build/tools/tzdb/TzdbZoneRulesCompiler.java index 9f1204ca7fe..8cbdd0d44ff 100644 --- a/jdk/make/src/classes/build/tools/tzdb/TzdbZoneRulesCompiler.java +++ b/jdk/make/src/classes/build/tools/tzdb/TzdbZoneRulesCompiler.java @@ -56,8 +56,6 @@ */ package build.tools.tzdb; -import static build.tools.tzdb.Utils.*; - import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.nio.charset.StandardCharsets; @@ -179,15 +177,41 @@ public final class TzdbZoneRulesCompiler { System.exit(1); System.err.println("Source directory does not contain file: VERSION"); } + + // load source files printVerbose("Compiling TZDB version " + version); - // parse source files - for (Path file : srcFiles) { - printVerbose("Parsing file: " + file); - parseFile(file); - } + TzdbZoneRulesProvider provider = new TzdbZoneRulesProvider(srcFiles); + // build zone rules printVerbose("Building rules"); - buildZoneRules(); + + // Build the rules, zones and links into real zones. + SortedMap builtZones = new TreeMap<>(); + + // build zones + for (String zoneId : provider.getZoneIds()) { + printVerbose("Building zone " + zoneId); + builtZones.put(zoneId, provider.getZoneRules(zoneId)); + } + + // build aliases + Map links = provider.getAliasMap(); + for (String aliasId : links.keySet()) { + String realId = links.get(aliasId); + printVerbose("Linking alias " + aliasId + " to " + realId); + ZoneRules realRules = builtZones.get(realId); + if (realRules == null) { + realId = links.get(realId); // try again (handle alias liked to alias) + printVerbose("Relinking alias " + aliasId + " to " + realId); + realRules = builtZones.get(realId); + if (realRules == null) { + throw new IllegalArgumentException("Alias '" + aliasId + "' links to invalid zone '" + realId); + } + links.put(aliasId, realId); + } + builtZones.put(aliasId, realRules); + } + // output to file printVerbose("Outputting tzdb file: " + dstFile); outputFile(dstFile, version, builtZones, links); @@ -269,361 +293,13 @@ public final class TzdbZoneRulesCompiler { } } - private static final Pattern YEAR = Pattern.compile("(?i)(?min)|(?max)|(?only)|(?[0-9]+)"); - private static final Pattern MONTH = Pattern.compile("(?i)(jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|(aug)|(sep)|(oct)|(nov)|(dec)"); - private static final Matcher DOW = Pattern.compile("(?i)(mon)|(tue)|(wed)|(thu)|(fri)|(sat)|(sun)").matcher(""); - private static final Matcher TIME = Pattern.compile("(?-)?+(?[0-9]{1,2})(:(?[0-5][0-9]))?+(:(?[0-5][0-9]))?+").matcher(""); - - /** The TZDB rules. */ - private final Map> rules = new HashMap<>(); - - /** The TZDB zones. */ - private final Map> zones = new HashMap<>(); - - /** The TZDB links. */ - private final Map links = new HashMap<>(); - - /** The built zones. */ - private final SortedMap builtZones = new TreeMap<>(); - /** Whether to output verbose messages. */ private boolean verbose; /** * private contructor */ - private TzdbZoneRulesCompiler() { - } - - /** - * Parses a source file. - * - * @param file the file being read, not null - * @throws Exception if an error occurs - */ - private void parseFile(Path file) throws Exception { - int lineNumber = 1; - String line = null; - try { - List lines = Files.readAllLines(file, StandardCharsets.ISO_8859_1); - List openZone = null; - for (; lineNumber < lines.size(); lineNumber++) { - line = lines.get(lineNumber); - int index = line.indexOf('#'); // remove comments (doesn't handle # in quotes) - if (index >= 0) { - line = line.substring(0, index); - } - if (line.trim().length() == 0) { // ignore blank lines - continue; - } - Scanner s = new Scanner(line); - if (openZone != null && Character.isWhitespace(line.charAt(0)) && s.hasNext()) { - if (parseZoneLine(s, openZone)) { - openZone = null; - } - } else { - if (s.hasNext()) { - String first = s.next(); - if (first.equals("Zone")) { - openZone = new ArrayList<>(); - try { - zones.put(s.next(), openZone); - if (parseZoneLine(s, openZone)) { - openZone = null; - } - } catch (NoSuchElementException x) { - printVerbose("Invalid Zone line in file: " + file + ", line: " + line); - throw new IllegalArgumentException("Invalid Zone line"); - } - } else { - openZone = null; - if (first.equals("Rule")) { - try { - parseRuleLine(s); - } catch (NoSuchElementException x) { - printVerbose("Invalid Rule line in file: " + file + ", line: " + line); - throw new IllegalArgumentException("Invalid Rule line"); - } - } else if (first.equals("Link")) { - try { - String realId = s.next(); - String aliasId = s.next(); - links.put(aliasId, realId); - } catch (NoSuchElementException x) { - printVerbose("Invalid Link line in file: " + file + ", line: " + line); - throw new IllegalArgumentException("Invalid Link line"); - } - - } else { - throw new IllegalArgumentException("Unknown line"); - } - } - } - } - } - } catch (Exception ex) { - throw new Exception("Failed while parsing file '" + file + "' on line " + lineNumber + " '" + line + "'", ex); - } - } - - /** - * Parses a Rule line. - * - * @param s the line scanner, not null - */ - private void parseRuleLine(Scanner s) { - TZDBRule rule = new TZDBRule(); - String name = s.next(); - if (rules.containsKey(name) == false) { - rules.put(name, new ArrayList()); - } - rules.get(name).add(rule); - rule.startYear = parseYear(s, 0); - rule.endYear = parseYear(s, rule.startYear); - if (rule.startYear > rule.endYear) { - throw new IllegalArgumentException("Year order invalid: " + rule.startYear + " > " + rule.endYear); - } - parseOptional(s.next()); // type is unused - parseMonthDayTime(s, rule); - rule.savingsAmount = parsePeriod(s.next()); - rule.text = parseOptional(s.next()); - } - - /** - * Parses a Zone line. - * - * @param s the line scanner, not null - * @return true if the zone is complete - */ - private boolean parseZoneLine(Scanner s, List zoneList) { - TZDBZone zone = new TZDBZone(); - zoneList.add(zone); - zone.standardOffset = parseOffset(s.next()); - String savingsRule = parseOptional(s.next()); - if (savingsRule == null) { - zone.fixedSavingsSecs = 0; - zone.savingsRule = null; - } else { - try { - zone.fixedSavingsSecs = parsePeriod(savingsRule); - zone.savingsRule = null; - } catch (Exception ex) { - zone.fixedSavingsSecs = null; - zone.savingsRule = savingsRule; - } - } - zone.text = s.next(); - if (s.hasNext()) { - zone.year = Integer.parseInt(s.next()); - if (s.hasNext()) { - parseMonthDayTime(s, zone); - } - return false; - } else { - return true; - } - } - - /** - * Parses a Rule line. - * - * @param s the line scanner, not null - * @param mdt the object to parse into, not null - */ - private void parseMonthDayTime(Scanner s, TZDBMonthDayTime mdt) { - mdt.month = parseMonth(s); - if (s.hasNext()) { - String dayRule = s.next(); - if (dayRule.startsWith("last")) { - mdt.dayOfMonth = -1; - mdt.dayOfWeek = parseDayOfWeek(dayRule.substring(4)); - mdt.adjustForwards = false; - } else { - int index = dayRule.indexOf(">="); - if (index > 0) { - mdt.dayOfWeek = parseDayOfWeek(dayRule.substring(0, index)); - dayRule = dayRule.substring(index + 2); - } else { - index = dayRule.indexOf("<="); - if (index > 0) { - mdt.dayOfWeek = parseDayOfWeek(dayRule.substring(0, index)); - mdt.adjustForwards = false; - dayRule = dayRule.substring(index + 2); - } - } - mdt.dayOfMonth = Integer.parseInt(dayRule); - } - if (s.hasNext()) { - String timeStr = s.next(); - int secsOfDay = parseSecs(timeStr); - if (secsOfDay == 86400) { - mdt.endOfDay = true; - secsOfDay = 0; - } - LocalTime time = LocalTime.ofSecondOfDay(secsOfDay); - mdt.time = time; - mdt.timeDefinition = parseTimeDefinition(timeStr.charAt(timeStr.length() - 1)); - } - } - } - - private int parseYear(Scanner s, int defaultYear) { - if (s.hasNext(YEAR)) { - s.next(YEAR); - MatchResult mr = s.match(); - if (mr.group(1) != null) { - return 1900; // systemv has min - } else if (mr.group(2) != null) { - return YEAR_MAX_VALUE; - } else if (mr.group(3) != null) { - return defaultYear; - } - return Integer.parseInt(mr.group(4)); - /* - if (mr.group("min") != null) { - //return YEAR_MIN_VALUE; - return 1900; // systemv has min - } else if (mr.group("max") != null) { - return YEAR_MAX_VALUE; - } else if (mr.group("only") != null) { - return defaultYear; - } - return Integer.parseInt(mr.group("year")); - */ - } - throw new IllegalArgumentException("Unknown year: " + s.next()); - } - - private int parseMonth(Scanner s) { - if (s.hasNext(MONTH)) { - s.next(MONTH); - for (int moy = 1; moy < 13; moy++) { - if (s.match().group(moy) != null) { - return moy; - } - } - } - throw new IllegalArgumentException("Unknown month: " + s.next()); - } - - private int parseDayOfWeek(String str) { - if (DOW.reset(str).matches()) { - for (int dow = 1; dow < 8; dow++) { - if (DOW.group(dow) != null) { - return dow; - } - } - } - throw new IllegalArgumentException("Unknown day-of-week: " + str); - } - - private String parseOptional(String str) { - return str.equals("-") ? null : str; - } - - private int parseSecs(String str) { - if (str.equals("-")) { - return 0; - } - try { - if (TIME.reset(str).find()) { - int secs = Integer.parseInt(TIME.group("hour")) * 60 * 60; - if (TIME.group("minute") != null) { - secs += Integer.parseInt(TIME.group("minute")) * 60; - } - if (TIME.group("second") != null) { - secs += Integer.parseInt(TIME.group("second")); - } - if (TIME.group("neg") != null) { - secs = -secs; - } - return secs; - } - } catch (NumberFormatException x) {} - throw new IllegalArgumentException(str); - } - - private ZoneOffset parseOffset(String str) { - int secs = parseSecs(str); - return ZoneOffset.ofTotalSeconds(secs); - } - - private int parsePeriod(String str) { - return parseSecs(str); - } - - private TimeDefinition parseTimeDefinition(char c) { - switch (c) { - case 's': - case 'S': - // standard time - return TimeDefinition.STANDARD; - case 'u': - case 'U': - case 'g': - case 'G': - case 'z': - case 'Z': - // UTC - return TimeDefinition.UTC; - case 'w': - case 'W': - default: - // wall time - return TimeDefinition.WALL; - } - } - - /** - * Build the rules, zones and links into real zones. - * - * @throws Exception if an error occurs - */ - private void buildZoneRules() throws Exception { - // build zones - for (String zoneId : zones.keySet()) { - printVerbose("Building zone " + zoneId); - List tzdbZones = zones.get(zoneId); - ZoneRulesBuilder bld = new ZoneRulesBuilder(); - for (TZDBZone tzdbZone : tzdbZones) { - bld = tzdbZone.addToBuilder(bld, rules); - } - builtZones.put(zoneId, bld.toRules(zoneId)); - } - - // build aliases - for (String aliasId : links.keySet()) { - String realId = links.get(aliasId); - printVerbose("Linking alias " + aliasId + " to " + realId); - ZoneRules realRules = builtZones.get(realId); - if (realRules == null) { - realId = links.get(realId); // try again (handle alias liked to alias) - printVerbose("Relinking alias " + aliasId + " to " + realId); - realRules = builtZones.get(realId); - if (realRules == null) { - throw new IllegalArgumentException("Alias '" + aliasId + "' links to invalid zone '" + realId); - } - links.put(aliasId, realId); - } - builtZones.put(aliasId, realRules); - } - // remove UTC and GMT - // builtZones.remove("UTC"); - // builtZones.remove("GMT"); - // builtZones.remove("GMT0"); - builtZones.remove("GMT+0"); - builtZones.remove("GMT-0"); - links.remove("GMT+0"); - links.remove("GMT-0"); - // remove ROC, which is not supported in j.u.tz - builtZones.remove("ROC"); - links.remove("ROC"); - // remove EST, HST and MST. They are supported via - // the short-id mapping - builtZones.remove("EST"); - builtZones.remove("HST"); - builtZones.remove("MST"); - } + private TzdbZoneRulesCompiler() {} /** * Prints a verbose message. @@ -635,109 +311,4 @@ public final class TzdbZoneRulesCompiler { System.out.println(message); } } - - /** - * Class representing a month-day-time in the TZDB file. - */ - abstract class TZDBMonthDayTime { - /** The month of the cutover. */ - int month = 1; - /** The day-of-month of the cutover. */ - int dayOfMonth = 1; - /** Whether to adjust forwards. */ - boolean adjustForwards = true; - /** The day-of-week of the cutover. */ - int dayOfWeek = -1; - /** The time of the cutover. */ - LocalTime time = LocalTime.MIDNIGHT; - /** Whether this is midnight end of day. */ - boolean endOfDay; - /** The time of the cutover. */ - TimeDefinition timeDefinition = TimeDefinition.WALL; - void adjustToFowards(int year) { - if (adjustForwards == false && dayOfMonth > 0) { - LocalDate adjustedDate = LocalDate.of(year, month, dayOfMonth).minusDays(6); - dayOfMonth = adjustedDate.getDayOfMonth(); - month = adjustedDate.getMonth(); - adjustForwards = true; - } - } - } - - /** - * Class representing a rule line in the TZDB file. - */ - final class TZDBRule extends TZDBMonthDayTime { - /** The start year. */ - int startYear; - /** The end year. */ - int endYear; - /** The amount of savings. */ - int savingsAmount; - /** The text name of the zone. */ - String text; - - void addToBuilder(ZoneRulesBuilder bld) { - adjustToFowards(2004); // irrelevant, treat as leap year - bld.addRuleToWindow(startYear, endYear, month, dayOfMonth, dayOfWeek, time, endOfDay, timeDefinition, savingsAmount); - } - } - - /** - * Class representing a linked set of zone lines in the TZDB file. - */ - final class TZDBZone extends TZDBMonthDayTime { - /** The standard offset. */ - ZoneOffset standardOffset; - /** The fixed savings amount. */ - Integer fixedSavingsSecs; - /** The savings rule. */ - String savingsRule; - /** The text name of the zone. */ - String text; - /** The year of the cutover. */ - int year = YEAR_MAX_VALUE; - - ZoneRulesBuilder addToBuilder(ZoneRulesBuilder bld, Map> rules) { - if (year != YEAR_MAX_VALUE) { - bld.addWindow(standardOffset, toDateTime(year), timeDefinition); - } else { - bld.addWindowForever(standardOffset); - } - if (fixedSavingsSecs != null) { - bld.setFixedSavingsToWindow(fixedSavingsSecs); - } else { - List tzdbRules = rules.get(savingsRule); - if (tzdbRules == null) { - throw new IllegalArgumentException("Rule not found: " + savingsRule); - } - for (TZDBRule tzdbRule : tzdbRules) { - tzdbRule.addToBuilder(bld); - } - } - return bld; - } - - private LocalDateTime toDateTime(int year) { - adjustToFowards(year); - LocalDate date; - if (dayOfMonth == -1) { - dayOfMonth = lengthOfMonth(month, isLeapYear(year)); - date = LocalDate.of(year, month, dayOfMonth); - if (dayOfWeek != -1) { - date = previousOrSame(date, dayOfWeek); - } - } else { - date = LocalDate.of(year, month, dayOfMonth); - if (dayOfWeek != -1) { - date = nextOrSame(date, dayOfWeek); - } - } - LocalDateTime ldt = LocalDateTime.of(date, time); - if (endOfDay) { - ldt = ldt.plusDays(1); - } - return ldt; - } - } } diff --git a/jdk/make/src/classes/build/tools/tzdb/TzdbZoneRulesProvider.java b/jdk/make/src/classes/build/tools/tzdb/TzdbZoneRulesProvider.java new file mode 100644 index 00000000000..220de9276c7 --- /dev/null +++ b/jdk/make/src/classes/build/tools/tzdb/TzdbZoneRulesProvider.java @@ -0,0 +1,843 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. 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 build.tools.tzdb; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NavigableMap; +import java.util.Objects; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.time.*; +import java.time.Year; +import java.time.chrono.IsoChronology; +import java.time.temporal.TemporalAdjusters; +import java.time.zone.ZoneOffsetTransition; +import java.time.zone.ZoneOffsetTransitionRule; +import java.time.zone.ZoneOffsetTransitionRule.TimeDefinition; +import java.time.zone.ZoneRulesException; + +/** + * Compile and build time-zone rules from IANA timezone data + * + * @author Xueming Shen + * @author Stephen Colebourne + * @author Michael Nascimento Santos + * + * @since 1.9 + */ + +class TzdbZoneRulesProvider { + + /** + * Creates an instance. + * + * @throws ZoneRulesException if unable to load + */ + public TzdbZoneRulesProvider(List files) { + try { + load(files); + } catch (Exception ex) { + throw new ZoneRulesException("Unable to load TZDB time-zone rules", ex); + } + } + + public Set getZoneIds() { + return new TreeSet(regionIds); + } + + public Map getAliasMap() { + return links; + } + + public ZoneRules getZoneRules(String zoneId) { + Object obj = zones.get(zoneId); + if (obj == null) { + String zoneId0 = zoneId; + if (links.containsKey(zoneId)) { + zoneId = links.get(zoneId); + obj = zones.get(zoneId); + } + if (obj == null) { + throw new ZoneRulesException("Unknown time-zone ID: " + zoneId0); + } + } + if (obj instanceof ZoneRules) { + return (ZoneRules)obj; + } + try { + ZoneRules zrules = buildRules(zoneId, (List)obj); + zones.put(zoneId, zrules); + return zrules; + } catch (Exception ex) { + throw new ZoneRulesException( + "Invalid binary time-zone data: TZDB:" + zoneId, ex); + } + } + + ////////////////////////////////////////////////////////////////////// + + /** + * All the regions that are available. + */ + private List regionIds = new ArrayList<>(600); + + /** + * Zone region to rules mapping + */ + private final Map zones = new ConcurrentHashMap<>(); + + /** + * compatibility list + */ + private static HashSet excludedZones; + static { + // (1) exclude EST, HST and MST. They are supported + // via the short-id mapping + // (2) remove UTC and GMT + // (3) remove ROC, which is not supported in j.u.tz + excludedZones = new HashSet<>(10); + excludedZones.add("EST"); + excludedZones.add("HST"); + excludedZones.add("MST"); + excludedZones.add("GMT+0"); + excludedZones.add("GMT-0"); + excludedZones.add("ROC"); + } + + private Map links = new HashMap<>(150); + private Map> rules = new HashMap<>(500); + + private void load(List files) throws IOException { + + for (Path file : files) { + List openZone = null; + try { + for (String line : Files.readAllLines(file, StandardCharsets.ISO_8859_1)) { + if (line.length() == 0 || line.charAt(0) == '#') { + continue; + } + //StringIterator itr = new StringIterator(line); + String[] tokens = split(line); + if (openZone != null && // continuing zone line + Character.isWhitespace(line.charAt(0)) && + tokens.length > 0) { + ZoneLine zLine = new ZoneLine(); + openZone.add(zLine); + if (zLine.parse(tokens, 0)) { + openZone = null; + } + continue; + } + if (line.startsWith("Zone")) { // parse Zone line + String name = tokens[1]; + if (excludedZones.contains(name)){ + continue; + } + if (zones.containsKey(name)) { + throw new IllegalArgumentException( + "Duplicated zone name in file: " + name + + ", line: [" + line + "]"); + } + openZone = new ArrayList<>(10); + zones.put(name, openZone); + regionIds.add(name); + ZoneLine zLine = new ZoneLine(); + openZone.add(zLine); + if (zLine.parse(tokens, 2)) { + openZone = null; + } + } else if (line.startsWith("Rule")) { // parse Rule line + String name = tokens[1]; + if (!rules.containsKey(name)) { + rules.put(name, new ArrayList(10)); + } + rules.get(name).add(new RuleLine().parse(tokens)); + } else if (line.startsWith("Link")) { // parse link line + if (tokens.length >= 3) { + String realId = tokens[1]; + String aliasId = tokens[2]; + if (excludedZones.contains(aliasId)){ + continue; + } + links.put(aliasId, realId); + regionIds.add(aliasId); + } else { + throw new IllegalArgumentException( + "Invalid Link line in file" + + file + ", line: [" + line + "]"); + } + } else { + // skip unknown line + } + } + + } catch (Exception ex) { + throw new RuntimeException("Failed while processing file [" + file + + "]", ex); + } + } + } + + private String[] split(String str) { + int off = 0; + int end = str.length(); + ArrayList list = new ArrayList<>(10); + while (off < end) { + char c = str.charAt(off); + if (c == '\t' || c == ' ') { + off++; + continue; + } + if (c == '#') { // comment + break; + } + int start = off; + while (off < end) { + c = str.charAt(off); + if (c == ' ' || c == '\t') { + break; + } + off++; + } + if (start != off) { + list.add(str.substring(start, off)); + } + } + return list.toArray(new String[list.size()]); + } + + /** + * Class representing a month-day-time in the TZDB file. + */ + private static abstract class MonthDayTime { + /** The month of the cutover. */ + Month month = Month.JANUARY; + + /** The day-of-month of the cutover. */ + int dayOfMonth = 1; + + /** Whether to adjust forwards. */ + boolean adjustForwards = true; + + /** The day-of-week of the cutover. */ + DayOfWeek dayOfWeek; + + /** The time of the cutover, in second of day */ + int secsOfDay = 0; + + /** Whether this is midnight end of day. */ + boolean endOfDay; + /** The time of the cutover. */ + + TimeDefinition timeDefinition = TimeDefinition.WALL; + + void adjustToForwards(int year) { + if (adjustForwards == false && dayOfMonth > 0) { + // weekDay<=monthDay case, don't have it in tzdb data for now + LocalDate adjustedDate = LocalDate.of(year, month, dayOfMonth).minusDays(6); + dayOfMonth = adjustedDate.getDayOfMonth(); + month = adjustedDate.getMonth(); + adjustForwards = true; + } + } + + LocalDateTime toDateTime(int year) { + LocalDate date; + if (dayOfMonth < 0) { + int monthLen = month.length(IsoChronology.INSTANCE.isLeapYear(year)); + date = LocalDate.of(year, month, monthLen + 1 + dayOfMonth); + if (dayOfWeek != null) { + date = date.with(TemporalAdjusters.previousOrSame(dayOfWeek)); + } + } else { + date = LocalDate.of(year, month, dayOfMonth); + if (dayOfWeek != null) { + date = date.with(TemporalAdjusters.nextOrSame(dayOfWeek)); + } + } + if (endOfDay) { + date = date.plusDays(1); + } + return LocalDateTime.of(date, LocalTime.ofSecondOfDay(secsOfDay)); + } + + /** + * Parses the MonthDaytime segment of a tzdb line. + */ + private void parse(String[] tokens, int off) { + month = parseMonth(tokens[off++]); + if (off < tokens.length) { + String dayRule = tokens[off++]; + if (dayRule.startsWith("last")) { + dayOfMonth = -1; + dayOfWeek = parseDayOfWeek(dayRule.substring(4)); + adjustForwards = false; + } else { + int index = dayRule.indexOf(">="); + if (index > 0) { + dayOfWeek = parseDayOfWeek(dayRule.substring(0, index)); + dayRule = dayRule.substring(index + 2); + } else { + index = dayRule.indexOf("<="); + if (index > 0) { + dayOfWeek = parseDayOfWeek(dayRule.substring(0, index)); + adjustForwards = false; + dayRule = dayRule.substring(index + 2); + } + } + dayOfMonth = Integer.parseInt(dayRule); + if (dayOfMonth < -28 || dayOfMonth > 31 || dayOfMonth == 0) { + throw new IllegalArgumentException( + "Day of month indicator must be between -28 and 31 inclusive excluding zero"); + } + } + if (off < tokens.length) { + String timeStr = tokens[off++]; + secsOfDay = parseSecs(timeStr); + if (secsOfDay == 86400) { + // time must be midnight when end of day flag is true + endOfDay = true; + secsOfDay = 0; + } + timeDefinition = parseTimeDefinition(timeStr.charAt(timeStr.length() - 1)); + } + } + } + + int parseYear(String year, int defaultYear) { + switch (year.toLowerCase()) { + case "min": return 1900; + case "max": return Year.MAX_VALUE; + case "only": return defaultYear; + } + return Integer.parseInt(year); + } + + Month parseMonth(String mon) { + switch (mon) { + case "Jan": return Month.JANUARY; + case "Feb": return Month.FEBRUARY; + case "Mar": return Month.MARCH; + case "Apr": return Month.APRIL; + case "May": return Month.MAY; + case "Jun": return Month.JUNE; + case "Jul": return Month.JULY; + case "Aug": return Month.AUGUST; + case "Sep": return Month.SEPTEMBER; + case "Oct": return Month.OCTOBER; + case "Nov": return Month.NOVEMBER; + case "Dec": return Month.DECEMBER; + } + throw new IllegalArgumentException("Unknown month: " + mon); + } + + DayOfWeek parseDayOfWeek(String dow) { + switch (dow) { + case "Mon": return DayOfWeek.MONDAY; + case "Tue": return DayOfWeek.TUESDAY; + case "Wed": return DayOfWeek.WEDNESDAY; + case "Thu": return DayOfWeek.THURSDAY; + case "Fri": return DayOfWeek.FRIDAY; + case "Sat": return DayOfWeek.SATURDAY; + case "Sun": return DayOfWeek.SUNDAY; + } + throw new IllegalArgumentException("Unknown day-of-week: " + dow); + } + + String parseOptional(String str) { + return str.equals("-") ? null : str; + } + + static final boolean isDigit(char c) { + return c >= '0' && c <= '9'; + } + + private int parseSecs(String time) { + if (time.equals("-")) { + return 0; + } + // faster hack + int secs = 0; + int sign = 1; + int off = 0; + int len = time.length(); + if (off < len && time.charAt(off) == '-') { + sign = -1; + off++; + } + char c0, c1; + if (off < len && isDigit(c0 = time.charAt(off++))) { + int hour = c0 - '0'; + if (off < len && isDigit(c1 = time.charAt(off))) { + hour = hour * 10 + c1 - '0'; + off++; + } + secs = hour * 60 * 60; + if (off < len && time.charAt(off++) == ':') { + if (off + 1 < len && + isDigit(c0 = time.charAt(off++)) && + isDigit(c1 = time.charAt(off++))) { + // minutes + secs += ((c0 - '0') * 10 + c1 - '0') * 60; + if (off < len && time.charAt(off++) == ':') { + if (off + 1 < len && + isDigit(c0 = time.charAt(off++)) && + isDigit(c1 = time.charAt(off++))) { + // seconds + secs += ((c0 - '0') * 10 + c1 - '0'); + } + } + } + + } + return secs * sign; + } + throw new IllegalArgumentException("[" + time + "]"); + } + + int parseOffset(String str) { + int secs = parseSecs(str); + if (Math.abs(secs) > 18 * 60 * 60) { + throw new IllegalArgumentException( + "Zone offset not in valid range: -18:00 to +18:00"); + } + return secs; + } + + int parsePeriod(String str) { + return parseSecs(str); + } + + TimeDefinition parseTimeDefinition(char c) { + switch (c) { + case 's': + case 'S': + // standard time + return TimeDefinition.STANDARD; + case 'u': + case 'U': + case 'g': + case 'G': + case 'z': + case 'Z': + // UTC + return TimeDefinition.UTC; + case 'w': + case 'W': + default: + // wall time + return TimeDefinition.WALL; + } + } + } + + /** + * Class representing a rule line in the TZDB file. + */ + private static class RuleLine extends MonthDayTime { + /** The start year. */ + int startYear; + + /** The end year. */ + int endYear; + + /** The amount of savings, in seconds. */ + int savingsAmount; + + /** The text name of the zone. */ + String text; + + /** + * Converts this to a transition rule. + * + * @param standardOffset the active standard offset, not null + * @param savingsBeforeSecs the active savings before the transition in seconds + * @return the transition, not null + */ + ZoneOffsetTransitionRule toTransitionRule(ZoneOffset stdOffset, int savingsBefore) { + // rule shared by different zones, so don't change it + Month month = this.month; + int dayOfMonth = this.dayOfMonth; + DayOfWeek dayOfWeek = this.dayOfWeek; + boolean endOfDay = this.endOfDay; + + // optimize stored format + if (dayOfMonth < 0) { + if (month != Month.FEBRUARY) { // not Month.FEBRUARY + dayOfMonth = month.maxLength() - 6; + } + } + if (endOfDay && dayOfMonth > 0 && + (dayOfMonth == 28 && month == Month.FEBRUARY) == false) { + LocalDate date = LocalDate.of(2004, month, dayOfMonth).plusDays(1); // leap-year + month = date.getMonth(); + dayOfMonth = date.getDayOfMonth(); + if (dayOfWeek != null) { + dayOfWeek = dayOfWeek.plus(1); + } + endOfDay = false; + } + // build rule + return ZoneOffsetTransitionRule.of( + //month, dayOfMonth, dayOfWeek, time, endOfDay, timeDefinition, + month, dayOfMonth, dayOfWeek, + LocalTime.ofSecondOfDay(secsOfDay), endOfDay, timeDefinition, + stdOffset, + ZoneOffset.ofTotalSeconds(stdOffset.getTotalSeconds() + savingsBefore), + ZoneOffset.ofTotalSeconds(stdOffset.getTotalSeconds() + savingsAmount)); + } + + RuleLine parse(String[] tokens) { + startYear = parseYear(tokens[2], 0); + endYear = parseYear(tokens[3], startYear); + if (startYear > endYear) { + throw new IllegalArgumentException( + "Invalid line/Year order invalid:" + startYear + " > " + endYear); + } + //parseOptional(s.next()); // type is unused + super.parse(tokens, 5); // monthdaytime parsing + savingsAmount = parsePeriod(tokens[8]); + //rule.text = parseOptional(s.next()); + return this; + } + } + + /** + * Class representing a linked set of zone lines in the TZDB file. + */ + private static class ZoneLine extends MonthDayTime { + /** The standard offset. */ + int stdOffsetSecs; + + /** The fixed savings amount. */ + int fixedSavingsSecs = 0; + + /** The savings rule. */ + String savingsRule; + + /** The text name of the zone. */ + String text; + + /** The cutover year */ + int year = Year.MAX_VALUE; + + /** The cutover date time */ + LocalDateTime ldt; + + /** The cutover date/time in epoch seconds/UTC */ + long ldtSecs = Long.MIN_VALUE; + + LocalDateTime toDateTime() { + if (ldt == null) { + ldt = toDateTime(year); + } + return ldt; + } + + /** + * Creates the date-time epoch second in the wall offset for the local + * date-time at the end of the window. + * + * @param savingsSecs the amount of savings in use in seconds + * @return the created date-time epoch second in the wall offset, not null + */ + long toDateTimeEpochSecond(int savingsSecs) { + if (ldtSecs == Long.MIN_VALUE) { + ldtSecs = toDateTime().toEpochSecond(ZoneOffset.UTC); + } + switch(timeDefinition) { + case UTC: return ldtSecs; + case STANDARD: return ldtSecs - stdOffsetSecs; + default: return ldtSecs - (stdOffsetSecs + savingsSecs); // WALL + } + } + + boolean parse(String[] tokens, int off) { + stdOffsetSecs = parseOffset(tokens[off++]); + savingsRule = parseOptional(tokens[off++]); + if (savingsRule != null && savingsRule.length() > 0 && + (savingsRule.charAt(0) == '-' || isDigit(savingsRule.charAt(0)))) { + try { + fixedSavingsSecs = parsePeriod(savingsRule); + savingsRule = null; + } catch (Exception ex) { + fixedSavingsSecs = 0; + } + } + text = tokens[off++]; + if (off < tokens.length) { + year = Integer.parseInt(tokens[off++]); + if (off < tokens.length) { + super.parse(tokens, off); // MonthDayTime + } + return false; + } else { + return true; + } + } + } + + /** + * Class representing a rule line in the TZDB file for a particular year. + */ + private static class TransRule implements Comparable + { + private int year; + private RuleLine rule; + + /** The trans date/time */ + private LocalDateTime ldt; + + /** The trans date/time in epoch seconds (assume UTC) */ + long ldtSecs; + + TransRule(int year, RuleLine rule) { + this.year = year; + this.rule = rule; + this.ldt = rule.toDateTime(year); + this.ldtSecs = ldt.toEpochSecond(ZoneOffset.UTC); + } + + ZoneOffsetTransition toTransition(ZoneOffset standardOffset, int savingsBeforeSecs) { + // copy of code in ZoneOffsetTransitionRule to avoid infinite loop + ZoneOffset wallOffset = ZoneOffset.ofTotalSeconds( + standardOffset.getTotalSeconds() + savingsBeforeSecs); + ZoneOffset offsetAfter = ZoneOffset.ofTotalSeconds( + standardOffset.getTotalSeconds() + rule.savingsAmount); + LocalDateTime dt = rule.timeDefinition + .createDateTime(ldt, standardOffset, wallOffset); + return ZoneOffsetTransition.of(dt, wallOffset, offsetAfter); + } + + long toEpochSecond(ZoneOffset stdOffset, int savingsBeforeSecs) { + switch(rule.timeDefinition) { + case UTC: return ldtSecs; + case STANDARD: return ldtSecs - stdOffset.getTotalSeconds(); + default: return ldtSecs - (stdOffset.getTotalSeconds() + savingsBeforeSecs); // WALL + } + } + + /** + * Tests if this a real transition with the active savings in seconds + * + * @param savingsBefore the active savings in seconds + * @return true, if savings changes + */ + boolean isTransition(int savingsBefore) { + return rule.savingsAmount != savingsBefore; + } + + public int compareTo(TransRule other) { + return (ldtSecs < other.ldtSecs)? -1 : ((ldtSecs == other.ldtSecs) ? 0 : 1); + } + } + + private ZoneRules buildRules(String zoneId, List zones) { + if (zones.isEmpty()) { + throw new IllegalStateException("No available zone window"); + } + final List standardTransitionList = new ArrayList<>(4); + final List transitionList = new ArrayList<>(256); + final List lastTransitionRuleList = new ArrayList<>(2); + + final ZoneLine zone0 = zones.get(0); + // initialize the standard offset, wallOffset and savings for loop + + //ZoneOffset stdOffset = zone0.standardOffset; + ZoneOffset stdOffset = ZoneOffset.ofTotalSeconds(zone0.stdOffsetSecs); + + int savings = zone0.fixedSavingsSecs; + ZoneOffset wallOffset = ZoneOffset.ofTotalSeconds(stdOffset.getTotalSeconds() + savings); + + // start ldt of each zone window + LocalDateTime zoneStart = LocalDateTime.MIN; + + // first stanard offset + ZoneOffset firstStdOffset = stdOffset; + // first wall offset + ZoneOffset firstWallOffset = wallOffset; + + for (ZoneLine zone : zones) { + // check if standard offset changed, update it if yes + ZoneOffset stdOffsetPrev = stdOffset; // for effectiveSavings check + if (zone.stdOffsetSecs != stdOffset.getTotalSeconds()) { + ZoneOffset stdOffsetNew = ZoneOffset.ofTotalSeconds(zone.stdOffsetSecs); + standardTransitionList.add( + ZoneOffsetTransition.of( + LocalDateTime.ofEpochSecond(zoneStart.toEpochSecond(wallOffset), + 0, + stdOffset), + stdOffset, + stdOffsetNew)); + stdOffset = stdOffsetNew; + } + + LocalDateTime zoneEnd; + if (zone.year == Year.MAX_VALUE) { + zoneEnd = LocalDateTime.MAX; + } else { + zoneEnd = zone.toDateTime(); + } + if (zoneEnd.compareTo(zoneStart) < 0) { + throw new IllegalStateException("Windows must be in date-time order: " + + zoneEnd + " < " + zoneStart); + } + // calculate effective savings at the start of the window + List trules = null; + List lastRules = null; + + int effectiveSavings = zone.fixedSavingsSecs; + if (zone.savingsRule != null) { + List tzdbRules = rules.get(zone.savingsRule); + if (tzdbRules == null) { + throw new IllegalArgumentException(" not found: " + + zone.savingsRule); + } + trules = new ArrayList<>(256); + lastRules = new ArrayList<>(2); + int lastRulesStartYear = Year.MIN_VALUE; + + // merge the rules to transitions + for (RuleLine rule : tzdbRules) { + if (rule.startYear > zoneEnd.getYear()) { + // rules will not be used for this zone entry + continue; + } + rule.adjustToForwards(2004); // irrelevant, treat as leap year + + int startYear = rule.startYear; + int endYear = rule.endYear; + if (zoneEnd.equals(LocalDateTime.MAX)) { + if (endYear == Year.MAX_VALUE) { + endYear = startYear; + lastRules.add(new TransRule(endYear, rule)); + lastRulesStartYear = Math.max(startYear, lastRulesStartYear); + } + } else { + if (endYear == Year.MAX_VALUE) { + //endYear = zoneEnd.getYear(); + endYear = zone.year; + } + } + int year = startYear; + while (year <= endYear) { + trules.add(new TransRule(year, rule)); + year++; + } + } + + // last rules, fill the gap years between different last rules + if (zoneEnd.equals(LocalDateTime.MAX)) { + lastRulesStartYear = Math.max(lastRulesStartYear, zoneStart.getYear()) + 1; + for (TransRule rule : lastRules) { + if (rule.year <= lastRulesStartYear) { + int year = rule.year; + while (year <= lastRulesStartYear) { + trules.add(new TransRule(year, rule.rule)); + year++; + } + rule.year = lastRulesStartYear; + rule.ldt = rule.rule.toDateTime(year); + rule.ldtSecs = rule.ldt.toEpochSecond(ZoneOffset.UTC); + } + } + Collections.sort(lastRules); + } + // sort the merged rules + Collections.sort(trules); + + effectiveSavings = 0; + for (TransRule rule : trules) { + if (rule.toEpochSecond(stdOffsetPrev, savings) > + zoneStart.toEpochSecond(wallOffset)) { + // previous savings amount found, which could be the + // savings amount at the instant that the window starts + // (hence isAfter) + break; + } + effectiveSavings = rule.rule.savingsAmount; + } + } + // check if the start of the window represents a transition + ZoneOffset effectiveWallOffset = + ZoneOffset.ofTotalSeconds(stdOffset.getTotalSeconds() + effectiveSavings); + + if (!wallOffset.equals(effectiveWallOffset)) { + transitionList.add(ZoneOffsetTransition.of(zoneStart, + wallOffset, + effectiveWallOffset)); + } + savings = effectiveSavings; + // apply rules within the window + if (trules != null) { + long zoneStartEpochSecs = zoneStart.toEpochSecond(wallOffset); + for (TransRule trule : trules) { + if (trule.isTransition(savings)) { + long epochSecs = trule.toEpochSecond(stdOffset, savings); + if (epochSecs < zoneStartEpochSecs || + epochSecs >= zone.toDateTimeEpochSecond(savings)) { + continue; + } + transitionList.add(trule.toTransition(stdOffset, savings)); + savings = trule.rule.savingsAmount; + } + } + } + if (lastRules != null) { + for (TransRule trule : lastRules) { + lastTransitionRuleList.add(trule.rule.toTransitionRule(stdOffset, savings)); + savings = trule.rule.savingsAmount; + } + } + + // finally we can calculate the true end of the window, passing it to the next window + wallOffset = ZoneOffset.ofTotalSeconds(stdOffset.getTotalSeconds() + savings); + zoneStart = LocalDateTime.ofEpochSecond(zone.toDateTimeEpochSecond(savings), + 0, + wallOffset); + } + return new ZoneRules(firstStdOffset, + firstWallOffset, + standardTransitionList, + transitionList, + lastTransitionRuleList); + } + +} diff --git a/jdk/make/src/classes/build/tools/tzdb/Utils.java b/jdk/make/src/classes/build/tools/tzdb/Utils.java deleted file mode 100644 index d129dd3bc7f..00000000000 --- a/jdk/make/src/classes/build/tools/tzdb/Utils.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * 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. - */ - -/* - * Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of JSR-310 nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package build.tools.tzdb; - -import java.util.Objects; - -class Utils { - - // Returns the largest (closest to positive infinity) - public static long floorDiv(long x, long y) { - long r = x / y; - // if the signs are different and modulo not zero, round down - if ((x ^ y) < 0 && (r * y != x)) { - r--; - } - return r; - } - - // Returns the floor modulus of the {@code long} arguments. - public static long floorMod(long x, long y) { - return x - floorDiv(x, y) * y; - } - - // Returns the sum of its arguments, - public static long addExact(long x, long y) { - long r = x + y; - // HD 2-12 Overflow iff both arguments have the opposite sign of the result - if (((x ^ r) & (y ^ r)) < 0) { - throw new ArithmeticException("long overflow"); - } - return r; - } - - // Year - - // Returns true if the specified year is a leap year. - public static boolean isLeapYear(int year) { - return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0); - } - - // The minimum supported year, '-999,999,999'. - public static final int YEAR_MIN_VALUE = -999_999_999; - - // The maximum supported year, '+999,999,999'. - public static final int YEAR_MAX_VALUE = 999_999_999; - - - // Gets the length of the specified month in days. - public static int lengthOfMonth(int month, boolean leapYear) { - switch (month) { - case 2: //FEBRUARY: - return (leapYear ? 29 : 28); - case 4: //APRIL: - case 6: //JUNE: - case 9: //SEPTEMBER: - case 11: //NOVEMBER: - return 30; - default: - return 31; - } - } - - // Gets the maximum length of the specified month in days. - public static int maxLengthOfMonth(int month) { - switch (month) { - case 2: //FEBRUARY: - return 29; - case 4: //APRIL: - case 6: //JUNE: - case 9: //SEPTEMBER: - case 11: //NOVEMBER: - return 30; - default: - return 31; - } - } - - // DayOfWeek - - // Returns the day-of-week that is the specified number of days after - // this one, from 1 to 7 for Monday to Sunday. - public static int plusDayOfWeek(int dow, long days) { - int amount = (int) (days % 7); - return (dow - 1 + (amount + 7)) % 7 + 1; - } - - // Returns the day-of-week that is the specified number of days before - // this one, from 1 to 7 for Monday to Sunday. - public static int minusDayOfWeek(int dow, long days) { - return plusDayOfWeek(dow, -(days % 7)); - } - - // Adjusts the date to the first occurrence of the specified day-of-week - // before the date being adjusted unless it is already on that day in - // which case the same object is returned. - public static LocalDate previousOrSame(LocalDate date, int dayOfWeek) { - return adjust(date, dayOfWeek, 1); - } - - // Adjusts the date to the first occurrence of the specified day-of-week - // after the date being adjusted unless it is already on that day in - // which case the same object is returned. - public static LocalDate nextOrSame(LocalDate date, int dayOfWeek) { - return adjust(date, dayOfWeek, 0); - } - - // Implementation of next, previous or current day-of-week. - // @param relative whether the current date is a valid answer - private static final LocalDate adjust(LocalDate date, int dow, int relative) { - int calDow = date.getDayOfWeek(); - if (relative < 2 && calDow == dow) { - return date; - } - if ((relative & 1) == 0) { - int daysDiff = calDow - dow; - return date.plusDays(daysDiff >= 0 ? 7 - daysDiff : -daysDiff); - } else { - int daysDiff = dow - calDow; - return date.minusDays(daysDiff >= 0 ? 7 - daysDiff : -daysDiff); - } - } - -} diff --git a/jdk/make/src/classes/build/tools/tzdb/ZoneOffset.java b/jdk/make/src/classes/build/tools/tzdb/ZoneOffset.java deleted file mode 100644 index 4f95fb3dd59..00000000000 --- a/jdk/make/src/classes/build/tools/tzdb/ZoneOffset.java +++ /dev/null @@ -1,474 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * This file is available under and governed by the GNU General Public - * License version 2 only, as published by the Free Software Foundation. - * However, the following notice accompanied the original version of this - * file: - * - * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of JSR-310 nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package build.tools.tzdb; - -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * A time-zone offset from Greenwich/UTC, such as {@code +02:00}. - *

- * A time-zone offset is the period of time that a time-zone differs from Greenwich/UTC. - * This is usually a fixed number of hours and minutes. - * - * @since 1.8 - */ -final class ZoneOffset implements Comparable { - - /** Cache of time-zone offset by offset in seconds. */ - private static final ConcurrentMap SECONDS_CACHE = new ConcurrentHashMap<>(16, 0.75f, 4); - /** Cache of time-zone offset by ID. */ - private static final ConcurrentMap ID_CACHE = new ConcurrentHashMap<>(16, 0.75f, 4); - - /** - * The number of seconds per hour. - */ - private static final int SECONDS_PER_HOUR = 60 * 60; - /** - * The number of seconds per minute. - */ - private static final int SECONDS_PER_MINUTE = 60; - /** - * The number of minutes per hour. - */ - private static final int MINUTES_PER_HOUR = 60; - /** - * The abs maximum seconds. - */ - private static final int MAX_SECONDS = 18 * SECONDS_PER_HOUR; - /** - * Serialization version. - */ - private static final long serialVersionUID = 2357656521762053153L; - - /** - * The time-zone offset for UTC, with an ID of 'Z'. - */ - public static final ZoneOffset UTC = ZoneOffset.ofTotalSeconds(0); - /** - * Constant for the maximum supported offset. - */ - public static final ZoneOffset MIN = ZoneOffset.ofTotalSeconds(-MAX_SECONDS); - /** - * Constant for the maximum supported offset. - */ - public static final ZoneOffset MAX = ZoneOffset.ofTotalSeconds(MAX_SECONDS); - - /** - * The total offset in seconds. - */ - private final int totalSeconds; - /** - * The string form of the time-zone offset. - */ - private final transient String id; - - //----------------------------------------------------------------------- - /** - * Obtains an instance of {@code ZoneOffset} using the ID. - *

- * This method parses the string ID of a {@code ZoneOffset} to - * return an instance. The parsing accepts all the formats generated by - * {@link #getId()}, plus some additional formats: - *

    - *
  • {@code Z} - for UTC - *
  • {@code +h} - *
  • {@code +hh} - *
  • {@code +hh:mm} - *
  • {@code -hh:mm} - *
  • {@code +hhmm} - *
  • {@code -hhmm} - *
  • {@code +hh:mm:ss} - *
  • {@code -hh:mm:ss} - *
  • {@code +hhmmss} - *
  • {@code -hhmmss} - *

- * Note that ± means either the plus or minus symbol. - *

- * The ID of the returned offset will be normalized to one of the formats - * described by {@link #getId()}. - *

- * The maximum supported range is from +18:00 to -18:00 inclusive. - * - * @param offsetId the offset ID, not null - * @return the zone-offset, not null - * @throws DateTimeException if the offset ID is invalid - */ - @SuppressWarnings("fallthrough") - public static ZoneOffset of(String offsetId) { - Objects.requireNonNull(offsetId, "offsetId"); - // "Z" is always in the cache - ZoneOffset offset = ID_CACHE.get(offsetId); - if (offset != null) { - return offset; - } - - // parse - +h, +hh, +hhmm, +hh:mm, +hhmmss, +hh:mm:ss - final int hours, minutes, seconds; - switch (offsetId.length()) { - case 2: - offsetId = offsetId.charAt(0) + "0" + offsetId.charAt(1); // fallthru - case 3: - hours = parseNumber(offsetId, 1, false); - minutes = 0; - seconds = 0; - break; - case 5: - hours = parseNumber(offsetId, 1, false); - minutes = parseNumber(offsetId, 3, false); - seconds = 0; - break; - case 6: - hours = parseNumber(offsetId, 1, false); - minutes = parseNumber(offsetId, 4, true); - seconds = 0; - break; - case 7: - hours = parseNumber(offsetId, 1, false); - minutes = parseNumber(offsetId, 3, false); - seconds = parseNumber(offsetId, 5, false); - break; - case 9: - hours = parseNumber(offsetId, 1, false); - minutes = parseNumber(offsetId, 4, true); - seconds = parseNumber(offsetId, 7, true); - break; - default: - throw new DateTimeException("Zone offset ID '" + offsetId + "' is invalid"); - } - char first = offsetId.charAt(0); - if (first != '+' && first != '-') { - throw new DateTimeException("Zone offset ID '" + offsetId + "' is invalid: Plus/minus not found when expected"); - } - if (first == '-') { - return ofHoursMinutesSeconds(-hours, -minutes, -seconds); - } else { - return ofHoursMinutesSeconds(hours, minutes, seconds); - } - } - - /** - * Parse a two digit zero-prefixed number. - * - * @param offsetId the offset ID, not null - * @param pos the position to parse, valid - * @param precededByColon should this number be prefixed by a precededByColon - * @return the parsed number, from 0 to 99 - */ - private static int parseNumber(CharSequence offsetId, int pos, boolean precededByColon) { - if (precededByColon && offsetId.charAt(pos - 1) != ':') { - throw new DateTimeException("Zone offset ID '" + offsetId + "' is invalid: Colon not found when expected"); - } - char ch1 = offsetId.charAt(pos); - char ch2 = offsetId.charAt(pos + 1); - if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') { - throw new DateTimeException("Zone offset ID '" + offsetId + "' is invalid: Non numeric characters found"); - } - return (ch1 - 48) * 10 + (ch2 - 48); - } - - //----------------------------------------------------------------------- - /** - * Obtains an instance of {@code ZoneOffset} using an offset in hours. - * - * @param hours the time-zone offset in hours, from -18 to +18 - * @return the zone-offset, not null - * @throws DateTimeException if the offset is not in the required range - */ - public static ZoneOffset ofHours(int hours) { - return ofHoursMinutesSeconds(hours, 0, 0); - } - - /** - * Obtains an instance of {@code ZoneOffset} using an offset in - * hours and minutes. - *

- * The sign of the hours and minutes components must match. - * Thus, if the hours is negative, the minutes must be negative or zero. - * If the hours is zero, the minutes may be positive, negative or zero. - * - * @param hours the time-zone offset in hours, from -18 to +18 - * @param minutes the time-zone offset in minutes, from 0 to ±59, sign matches hours - * @return the zone-offset, not null - * @throws DateTimeException if the offset is not in the required range - */ - public static ZoneOffset ofHoursMinutes(int hours, int minutes) { - return ofHoursMinutesSeconds(hours, minutes, 0); - } - - /** - * Obtains an instance of {@code ZoneOffset} using an offset in - * hours, minutes and seconds. - *

- * The sign of the hours, minutes and seconds components must match. - * Thus, if the hours is negative, the minutes and seconds must be negative or zero. - * - * @param hours the time-zone offset in hours, from -18 to +18 - * @param minutes the time-zone offset in minutes, from 0 to ±59, sign matches hours and seconds - * @param seconds the time-zone offset in seconds, from 0 to ±59, sign matches hours and minutes - * @return the zone-offset, not null - * @throws DateTimeException if the offset is not in the required range - */ - public static ZoneOffset ofHoursMinutesSeconds(int hours, int minutes, int seconds) { - validate(hours, minutes, seconds); - int totalSeconds = totalSeconds(hours, minutes, seconds); - return ofTotalSeconds(totalSeconds); - } - - /** - * Validates the offset fields. - * - * @param hours the time-zone offset in hours, from -18 to +18 - * @param minutes the time-zone offset in minutes, from 0 to ±59 - * @param seconds the time-zone offset in seconds, from 0 to ±59 - * @throws DateTimeException if the offset is not in the required range - */ - private static void validate(int hours, int minutes, int seconds) { - if (hours < -18 || hours > 18) { - throw new DateTimeException("Zone offset hours not in valid range: value " + hours + - " is not in the range -18 to 18"); - } - if (hours > 0) { - if (minutes < 0 || seconds < 0) { - throw new DateTimeException("Zone offset minutes and seconds must be positive because hours is positive"); - } - } else if (hours < 0) { - if (minutes > 0 || seconds > 0) { - throw new DateTimeException("Zone offset minutes and seconds must be negative because hours is negative"); - } - } else if ((minutes > 0 && seconds < 0) || (minutes < 0 && seconds > 0)) { - throw new DateTimeException("Zone offset minutes and seconds must have the same sign"); - } - if (Math.abs(minutes) > 59) { - throw new DateTimeException("Zone offset minutes not in valid range: abs(value) " + - Math.abs(minutes) + " is not in the range 0 to 59"); - } - if (Math.abs(seconds) > 59) { - throw new DateTimeException("Zone offset seconds not in valid range: abs(value) " + - Math.abs(seconds) + " is not in the range 0 to 59"); - } - if (Math.abs(hours) == 18 && (Math.abs(minutes) > 0 || Math.abs(seconds) > 0)) { - throw new DateTimeException("Zone offset not in valid range: -18:00 to +18:00"); - } - } - - /** - * Calculates the total offset in seconds. - * - * @param hours the time-zone offset in hours, from -18 to +18 - * @param minutes the time-zone offset in minutes, from 0 to ±59, sign matches hours and seconds - * @param seconds the time-zone offset in seconds, from 0 to ±59, sign matches hours and minutes - * @return the total in seconds - */ - private static int totalSeconds(int hours, int minutes, int seconds) { - return hours * SECONDS_PER_HOUR + minutes * SECONDS_PER_MINUTE + seconds; - } - - //----------------------------------------------------------------------- - /** - * Obtains an instance of {@code ZoneOffset} specifying the total offset in seconds - *

- * The offset must be in the range {@code -18:00} to {@code +18:00}, which corresponds to -64800 to +64800. - * - * @param totalSeconds the total time-zone offset in seconds, from -64800 to +64800 - * @return the ZoneOffset, not null - * @throws DateTimeException if the offset is not in the required range - */ - public static ZoneOffset ofTotalSeconds(int totalSeconds) { - if (Math.abs(totalSeconds) > MAX_SECONDS) { - throw new DateTimeException("Zone offset not in valid range: -18:00 to +18:00"); - } - if (totalSeconds % (15 * SECONDS_PER_MINUTE) == 0) { - Integer totalSecs = totalSeconds; - ZoneOffset result = SECONDS_CACHE.get(totalSecs); - if (result == null) { - result = new ZoneOffset(totalSeconds); - SECONDS_CACHE.putIfAbsent(totalSecs, result); - result = SECONDS_CACHE.get(totalSecs); - ID_CACHE.putIfAbsent(result.getId(), result); - } - return result; - } else { - return new ZoneOffset(totalSeconds); - } - } - - /** - * Constructor. - * - * @param totalSeconds the total time-zone offset in seconds, from -64800 to +64800 - */ - private ZoneOffset(int totalSeconds) { - super(); - this.totalSeconds = totalSeconds; - id = buildId(totalSeconds); - } - - private static String buildId(int totalSeconds) { - if (totalSeconds == 0) { - return "Z"; - } else { - int absTotalSeconds = Math.abs(totalSeconds); - StringBuilder buf = new StringBuilder(); - int absHours = absTotalSeconds / SECONDS_PER_HOUR; - int absMinutes = (absTotalSeconds / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR; - buf.append(totalSeconds < 0 ? "-" : "+") - .append(absHours < 10 ? "0" : "").append(absHours) - .append(absMinutes < 10 ? ":0" : ":").append(absMinutes); - int absSeconds = absTotalSeconds % SECONDS_PER_MINUTE; - if (absSeconds != 0) { - buf.append(absSeconds < 10 ? ":0" : ":").append(absSeconds); - } - return buf.toString(); - } - } - - /** - * Gets the total zone offset in seconds. - *

- * This is the primary way to access the offset amount. - * It returns the total of the hours, minutes and seconds fields as a - * single offset that can be added to a time. - * - * @return the total zone offset amount in seconds - */ - public int getTotalSeconds() { - return totalSeconds; - } - - /** - * Gets the normalized zone offset ID. - *

- * The ID is minor variation to the standard ISO-8601 formatted string - * for the offset. There are three formats: - *

    - *
  • {@code Z} - for UTC (ISO-8601) - *
  • {@code +hh:mm} or {@code -hh:mm} - if the seconds are zero (ISO-8601) - *
  • {@code +hh:mm:ss} or {@code -hh:mm:ss} - if the seconds are non-zero (not ISO-8601) - *

- * - * @return the zone offset ID, not null - */ - public String getId() { - return id; - } - - /** - * Compares this offset to another offset in descending order. - *

- * The offsets are compared in the order that they occur for the same time - * of day around the world. Thus, an offset of {@code +10:00} comes before an - * offset of {@code +09:00} and so on down to {@code -18:00}. - *

- * The comparison is "consistent with equals", as defined by {@link Comparable}. - * - * @param other the other date to compare to, not null - * @return the comparator value, negative if less, postive if greater - * @throws NullPointerException if {@code other} is null - */ - @Override - public int compareTo(ZoneOffset other) { - return other.totalSeconds - totalSeconds; - } - - /** - * Checks if this offset is equal to another offset. - *

- * The comparison is based on the amount of the offset in seconds. - * This is equivalent to a comparison by ID. - * - * @param obj the object to check, null returns false - * @return true if this is equal to the other offset - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof ZoneOffset) { - return totalSeconds == ((ZoneOffset) obj).totalSeconds; - } - return false; - } - - /** - * A hash code for this offset. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - return totalSeconds; - } - - /** - * Outputs this offset as a {@code String}, using the normalized ID. - * - * @return a string representation of this offset, not null - */ - @Override - public String toString() { - return id; - } - -} diff --git a/jdk/make/src/classes/build/tools/tzdb/ZoneOffsetTransition.java b/jdk/make/src/classes/build/tools/tzdb/ZoneOffsetTransition.java deleted file mode 100644 index 167b5f112de..00000000000 --- a/jdk/make/src/classes/build/tools/tzdb/ZoneOffsetTransition.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * This file is available under and governed by the GNU General Public - * License version 2 only, as published by the Free Software Foundation. - * However, the following notice accompanied the original version of this - * file: - * - * Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of JSR-310 nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package build.tools.tzdb; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -/** - * A transition between two offsets caused by a discontinuity in the local time-line. - * - * @since 1.8 - */ -final class ZoneOffsetTransition implements Comparable { - - /** - * The local transition date-time at the transition. - */ - private final LocalDateTime transition; - /** - * The offset before transition. - */ - private final ZoneOffset offsetBefore; - /** - * The offset after transition. - */ - private final ZoneOffset offsetAfter; - - /** - * Creates an instance defining a transition between two offsets. - * - * @param transition the transition date-time with the offset before the transition, not null - * @param offsetBefore the offset before the transition, not null - * @param offsetAfter the offset at and after the transition, not null - */ - ZoneOffsetTransition(LocalDateTime transition, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { - Objects.requireNonNull(transition, "transition"); - Objects.requireNonNull(offsetBefore, "offsetBefore"); - Objects.requireNonNull(offsetAfter, "offsetAfter"); - if (offsetBefore.equals(offsetAfter)) { - throw new IllegalArgumentException("Offsets must not be equal"); - } - this.transition = transition; - this.offsetBefore = offsetBefore; - this.offsetAfter = offsetAfter; - } - - /** - * Creates an instance from epoch-second and offsets. - * - * @param epochSecond the transition epoch-second - * @param offsetBefore the offset before the transition, not null - * @param offsetAfter the offset at and after the transition, not null - */ - ZoneOffsetTransition(long epochSecond, ZoneOffset offsetBefore, ZoneOffset offsetAfter) { - this.transition = LocalDateTime.ofEpochSecond(epochSecond, 0, offsetBefore); - this.offsetBefore = offsetBefore; - this.offsetAfter = offsetAfter; - } - - /** - * Gets the transition instant as an epoch second. - * - * @return the transition epoch second - */ - public long toEpochSecond() { - return transition.toEpochSecond(offsetBefore); - } - - /** - * Gets the local transition date-time, as would be expressed with the 'before' offset. - *

- * This is the date-time where the discontinuity begins expressed with the 'before' offset. - * At this instant, the 'after' offset is actually used, therefore the combination of this - * date-time and the 'before' offset will never occur. - *

- * The combination of the 'before' date-time and offset represents the same instant - * as the 'after' date-time and offset. - * - * @return the transition date-time expressed with the before offset, not null - */ - public LocalDateTime getDateTimeBefore() { - return transition; - } - - /** - * Gets the local transition date-time, as would be expressed with the 'after' offset. - *

- * This is the first date-time after the discontinuity, when the new offset applies. - *

- * The combination of the 'before' date-time and offset represents the same instant - * as the 'after' date-time and offset. - * - * @return the transition date-time expressed with the after offset, not null - */ - public LocalDateTime getDateTimeAfter() { - return transition.plusSeconds(getDurationSeconds()); - } - - /** - * Gets the offset before the transition. - *

- * This is the offset in use before the instant of the transition. - * - * @return the offset before the transition, not null - */ - public ZoneOffset getOffsetBefore() { - return offsetBefore; - } - - /** - * Gets the offset after the transition. - *

- * This is the offset in use on and after the instant of the transition. - * - * @return the offset after the transition, not null - */ - public ZoneOffset getOffsetAfter() { - return offsetAfter; - } - - /** - * Gets the duration of the transition in seconds. - * - * @return the duration in seconds - */ - private int getDurationSeconds() { - return getOffsetAfter().getTotalSeconds() - getOffsetBefore().getTotalSeconds(); - } - - /** - * Does this transition represent a gap in the local time-line. - *

- * Gaps occur where there are local date-times that simply do not not exist. - * An example would be when the offset changes from {@code +01:00} to {@code +02:00}. - * This might be described as 'the clocks will move forward one hour tonight at 1am'. - * - * @return true if this transition is a gap, false if it is an overlap - */ - public boolean isGap() { - return getOffsetAfter().getTotalSeconds() > getOffsetBefore().getTotalSeconds(); - } - - /** - * Does this transition represent a gap in the local time-line. - *

- * Overlaps occur where there are local date-times that exist twice. - * An example would be when the offset changes from {@code +02:00} to {@code +01:00}. - * This might be described as 'the clocks will move back one hour tonight at 2am'. - * - * @return true if this transition is an overlap, false if it is a gap - */ - public boolean isOverlap() { - return getOffsetAfter().getTotalSeconds() < getOffsetBefore().getTotalSeconds(); - } - - /** - * Checks if the specified offset is valid during this transition. - *

- * This checks to see if the given offset will be valid at some point in the transition. - * A gap will always return false. - * An overlap will return true if the offset is either the before or after offset. - * - * @param offset the offset to check, null returns false - * @return true if the offset is valid during the transition - */ - public boolean isValidOffset(ZoneOffset offset) { - return isGap() ? false : (getOffsetBefore().equals(offset) || getOffsetAfter().equals(offset)); - } - - /** - * Gets the valid offsets during this transition. - *

- * A gap will return an empty list, while an overlap will return both offsets. - * - * @return the list of valid offsets - */ - List getValidOffsets() { - if (isGap()) { - return Collections.emptyList(); - } - return Arrays.asList(getOffsetBefore(), getOffsetAfter()); - } - - /** - * Compares this transition to another based on the transition instant. - *

- * This compares the instants of each transition. - * The offsets are ignored, making this order inconsistent with equals. - * - * @param transition the transition to compare to, not null - * @return the comparator value, negative if less, positive if greater - */ - @Override - public int compareTo(ZoneOffsetTransition transition) { - return Long.compare(this.toEpochSecond(), transition.toEpochSecond()); - } - - /** - * Checks if this object equals another. - *

- * The entire state of the object is compared. - * - * @param other the other object to compare to, null returns false - * @return true if equal - */ - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if (other instanceof ZoneOffsetTransition) { - ZoneOffsetTransition d = (ZoneOffsetTransition) other; - return transition.equals(d.transition) && - offsetBefore.equals(d.offsetBefore) && offsetAfter.equals(d.offsetAfter); - } - return false; - } - - /** - * Returns a suitable hash code. - * - * @return the hash code - */ - @Override - public int hashCode() { - return transition.hashCode() ^ offsetBefore.hashCode() ^ Integer.rotateLeft(offsetAfter.hashCode(), 16); - } - -} diff --git a/jdk/make/src/classes/build/tools/tzdb/ZoneOffsetTransitionRule.java b/jdk/make/src/classes/build/tools/tzdb/ZoneOffsetTransitionRule.java deleted file mode 100644 index 783499c2163..00000000000 --- a/jdk/make/src/classes/build/tools/tzdb/ZoneOffsetTransitionRule.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * This file is available under and governed by the GNU General Public - * License version 2 only, as published by the Free Software Foundation. - * However, the following notice accompanied the original version of this - * file: - * - * Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of JSR-310 nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package build.tools.tzdb; - -import static build.tools.tzdb.Utils.*; -import java.util.Objects; - -/** - * A rule expressing how to create a transition. - *

- * This class allows rules for identifying future transitions to be expressed. - * A rule might be written in many forms: - *

    - *
  • the 16th March - *
  • the Sunday on or after the 16th March - *
  • the Sunday on or before the 16th March - *
  • the last Sunday in February - *

- * These different rule types can be expressed and queried. - * - *

Specification for implementors

- * This class is immutable and thread-safe. - * - * @since 1.8 - */ -final class ZoneOffsetTransitionRule { - - /** - * The month of the month-day of the first day of the cutover week. - * The actual date will be adjusted by the dowChange field. - */ - final int month; - /** - * The day-of-month of the month-day of the cutover week. - * If positive, it is the start of the week where the cutover can occur. - * If negative, it represents the end of the week where cutover can occur. - * The value is the number of days from the end of the month, such that - * {@code -1} is the last day of the month, {@code -2} is the second - * to last day, and so on. - */ - final byte dom; - /** - * The cutover day-of-week, -1 to retain the day-of-month. - */ - final int dow; - /** - * The cutover time in the 'before' offset. - */ - final LocalTime time; - /** - * Whether the cutover time is midnight at the end of day. - */ - final boolean timeEndOfDay; - /** - * The definition of how the local time should be interpreted. - */ - final TimeDefinition timeDefinition; - /** - * The standard offset at the cutover. - */ - final ZoneOffset standardOffset; - /** - * The offset before the cutover. - */ - final ZoneOffset offsetBefore; - /** - * The offset after the cutover. - */ - final ZoneOffset offsetAfter; - - /** - * Creates an instance defining the yearly rule to create transitions between two offsets. - * - * @param month the month of the month-day of the first day of the cutover week, from 1 to 12 - * @param dayOfMonthIndicator the day of the month-day of the cutover week, positive if the week is that - * day or later, negative if the week is that day or earlier, counting from the last day of the month, - * from -28 to 31 excluding 0 - * @param dayOfWeek the required day-of-week, -1 if the month-day should not be changed - * @param time the cutover time in the 'before' offset, not null - * @param timeEndOfDay whether the time is midnight at the end of day - * @param timeDefnition how to interpret the cutover - * @param standardOffset the standard offset in force at the cutover, not null - * @param offsetBefore the offset before the cutover, not null - * @param offsetAfter the offset after the cutover, not null - * @throws IllegalArgumentException if the day of month indicator is invalid - * @throws IllegalArgumentException if the end of day flag is true when the time is not midnight - */ - ZoneOffsetTransitionRule( - int month, - int dayOfMonthIndicator, - int dayOfWeek, - LocalTime time, - boolean timeEndOfDay, - TimeDefinition timeDefnition, - ZoneOffset standardOffset, - ZoneOffset offsetBefore, - ZoneOffset offsetAfter) { - Objects.requireNonNull(time, "time"); - Objects.requireNonNull(timeDefnition, "timeDefnition"); - Objects.requireNonNull(standardOffset, "standardOffset"); - Objects.requireNonNull(offsetBefore, "offsetBefore"); - Objects.requireNonNull(offsetAfter, "offsetAfter"); - if (month < 1 || month > 12) { - throw new IllegalArgumentException("month must be between 1 and 12"); - } - if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { - throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); - } - if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { - throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); - } - this.month = month; - this.dom = (byte) dayOfMonthIndicator; - this.dow = dayOfWeek; - this.time = time; - this.timeEndOfDay = timeEndOfDay; - this.timeDefinition = timeDefnition; - this.standardOffset = standardOffset; - this.offsetBefore = offsetBefore; - this.offsetAfter = offsetAfter; - } - - //----------------------------------------------------------------------- - /** - * Checks if this object equals another. - *

- * The entire state of the object is compared. - * - * @param otherRule the other object to compare to, null returns false - * @return true if equal - */ - @Override - public boolean equals(Object otherRule) { - if (otherRule == this) { - return true; - } - if (otherRule instanceof ZoneOffsetTransitionRule) { - ZoneOffsetTransitionRule other = (ZoneOffsetTransitionRule) otherRule; - return month == other.month && dom == other.dom && dow == other.dow && - timeDefinition == other.timeDefinition && - time.equals(other.time) && - timeEndOfDay == other.timeEndOfDay && - standardOffset.equals(other.standardOffset) && - offsetBefore.equals(other.offsetBefore) && - offsetAfter.equals(other.offsetAfter); - } - return false; - } - - /** - * Returns a suitable hash code. - * - * @return the hash code - */ - @Override - public int hashCode() { - int hash = ((time.toSecondOfDay() + (timeEndOfDay ? 1 : 0)) << 15) + - (month << 11) + ((dom + 32) << 5) + - ((dow == -1 ? 8 : dow) << 2) + (timeDefinition.ordinal()); - return hash ^ standardOffset.hashCode() ^ - offsetBefore.hashCode() ^ offsetAfter.hashCode(); - } - -} diff --git a/jdk/make/src/classes/build/tools/tzdb/ZoneRules.java b/jdk/make/src/classes/build/tools/tzdb/ZoneRules.java index 22c3be80c02..4d01d3ac5b6 100644 --- a/jdk/make/src/classes/build/tools/tzdb/ZoneRules.java +++ b/jdk/make/src/classes/build/tools/tzdb/ZoneRules.java @@ -64,6 +64,12 @@ package build.tools.tzdb; import java.io.DataOutput; import java.io.IOException; import java.io.ObjectOutput; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneOffset; +import java.time.zone.ZoneOffsetTransition; +import java.time.zone.ZoneOffsetTransitionRule; +import java.time.zone.ZoneOffsetTransitionRule.TimeDefinition; import java.util.Arrays; import java.util.ArrayList; import java.util.List; @@ -224,15 +230,15 @@ final class ZoneRules { * @throws IOException if an error occurs */ static void writeRule(ZoneOffsetTransitionRule rule, DataOutput out) throws IOException { - int month = rule.month; - byte dom = rule.dom; - int dow = rule.dow; - LocalTime time = rule.time; - boolean timeEndOfDay = rule.timeEndOfDay; - TimeDefinition timeDefinition = rule.timeDefinition; - ZoneOffset standardOffset = rule.standardOffset; - ZoneOffset offsetBefore = rule.offsetBefore; - ZoneOffset offsetAfter = rule.offsetAfter; + int month = rule.getMonth().getValue(); + byte dom = (byte)rule.getDayOfMonthIndicator(); + int dow = rule.getDayOfWeek().getValue(); + LocalTime time = rule.getLocalTime(); + boolean timeEndOfDay = rule.isMidnightEndOfDay(); + TimeDefinition timeDefinition = rule.getTimeDefinition(); + ZoneOffset standardOffset = rule.getStandardOffset(); + ZoneOffset offsetBefore = rule.getOffsetBefore(); + ZoneOffset offsetAfter = rule.getOffsetAfter(); int timeSecs = (timeEndOfDay ? 86400 : time.toSecondOfDay()); int stdOffset = standardOffset.getTotalSeconds(); diff --git a/jdk/make/src/classes/build/tools/tzdb/ZoneRulesBuilder.java b/jdk/make/src/classes/build/tools/tzdb/ZoneRulesBuilder.java deleted file mode 100644 index f4a437dc074..00000000000 --- a/jdk/make/src/classes/build/tools/tzdb/ZoneRulesBuilder.java +++ /dev/null @@ -1,743 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * This file is available under and governed by the GNU General Public - * License version 2 only, as published by the Free Software Foundation. - * However, the following notice accompanied the original version of this - * file: - * - * Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * * Neither the name of JSR-310 nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package build.tools.tzdb; - -import static build.tools.tzdb.Utils.*; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * A mutable builder used to create all the rules for a historic time-zone. - *

- * The rules of a time-zone describe how the offset changes over time. - * The rules are created by building windows on the time-line within which - * the different rules apply. The rules may be one of two kinds: - *

    - *
  • Fixed savings - A single fixed amount of savings from the standard offset will apply.
  • - *
  • Rules - A set of one or more rules describe how daylight savings changes during the window.
  • - *

- * - *

Implementation notes

- * This class is a mutable builder used to create zone instances. - * It must only be used from a single thread. - * The created instances are immutable and thread-safe. - * - * @since 1.8 - */ -public class ZoneRulesBuilder { - - /** - * The list of windows. - */ - private List windowList = new ArrayList<>(); - - //----------------------------------------------------------------------- - /** - * Constructs an instance of the builder that can be used to create zone rules. - *

- * The builder is used by adding one or more windows representing portions - * of the time-line. The standard offset from UTC/Greenwich will be constant - * within a window, although two adjacent windows can have the same standard offset. - *

- * Within each window, there can either be a - * {@link #setFixedSavingsToWindow fixed savings amount} or a - * {@link #addRuleToWindow list of rules}. - */ - public ZoneRulesBuilder() { - } - - //----------------------------------------------------------------------- - /** - * Adds a window to the builder that can be used to filter a set of rules. - *

- * This method defines and adds a window to the zone where the standard offset is specified. - * The window limits the effect of subsequent additions of transition rules - * or fixed savings. If neither rules or fixed savings are added to the window - * then the window will default to no savings. - *

- * Each window must be added sequentially, as the start instant of the window - * is derived from the until instant of the previous window. - * - * @param standardOffset the standard offset, not null - * @param until the date-time that the offset applies until, not null - * @param untilDefinition the time type for the until date-time, not null - * @return this, for chaining - * @throws IllegalStateException if the window order is invalid - */ - public ZoneRulesBuilder addWindow( - ZoneOffset standardOffset, - LocalDateTime until, - TimeDefinition untilDefinition) { - Objects.requireNonNull(standardOffset, "standardOffset"); - Objects.requireNonNull(until, "until"); - Objects.requireNonNull(untilDefinition, "untilDefinition"); - TZWindow window = new TZWindow(standardOffset, until, untilDefinition); - if (windowList.size() > 0) { - TZWindow previous = windowList.get(windowList.size() - 1); - window.validateWindowOrder(previous); - } - windowList.add(window); - return this; - } - - /** - * Adds a window that applies until the end of time to the builder that can be - * used to filter a set of rules. - *

- * This method defines and adds a window to the zone where the standard offset is specified. - * The window limits the effect of subsequent additions of transition rules - * or fixed savings. If neither rules or fixed savings are added to the window - * then the window will default to no savings. - *

- * This must be added after all other windows. - * No more windows can be added after this one. - * - * @param standardOffset the standard offset, not null - * @return this, for chaining - * @throws IllegalStateException if a forever window has already been added - */ - public ZoneRulesBuilder addWindowForever(ZoneOffset standardOffset) { - return addWindow(standardOffset, LocalDateTime.MAX, TimeDefinition.WALL); - } - - //----------------------------------------------------------------------- - /** - * Sets the previously added window to have fixed savings. - *

- * Setting a window to have fixed savings simply means that a single daylight - * savings amount applies throughout the window. The window could be small, - * such as a single summer, or large, such as a multi-year daylight savings. - *

- * A window can either have fixed savings or rules but not both. - * - * @param fixedSavingAmountSecs the amount of saving to use for the whole window, not null - * @return this, for chaining - * @throws IllegalStateException if no window has yet been added - * @throws IllegalStateException if the window already has rules - */ - public ZoneRulesBuilder setFixedSavingsToWindow(int fixedSavingAmountSecs) { - if (windowList.isEmpty()) { - throw new IllegalStateException("Must add a window before setting the fixed savings"); - } - TZWindow window = windowList.get(windowList.size() - 1); - window.setFixedSavings(fixedSavingAmountSecs); - return this; - } - - //----------------------------------------------------------------------- - /** - * Adds a single transition rule to the current window. - *

- * This adds a rule such that the offset, expressed as a daylight savings amount, - * changes at the specified date-time. - * - * @param transitionDateTime the date-time that the transition occurs as defined by timeDefintion, not null - * @param timeDefinition the definition of how to convert local to actual time, not null - * @param savingAmountSecs the amount of saving from the standard offset after the transition in seconds - * @return this, for chaining - * @throws IllegalStateException if no window has yet been added - * @throws IllegalStateException if the window already has fixed savings - * @throws IllegalStateException if the window has reached the maximum capacity of 2000 rules - */ - public ZoneRulesBuilder addRuleToWindow( - LocalDateTime transitionDateTime, - TimeDefinition timeDefinition, - int savingAmountSecs) { - Objects.requireNonNull(transitionDateTime, "transitionDateTime"); - return addRuleToWindow( - transitionDateTime.getYear(), transitionDateTime.getYear(), - transitionDateTime.getMonth(), transitionDateTime.getDayOfMonth(), - -1, transitionDateTime.getTime(), false, timeDefinition, savingAmountSecs); - } - - /** - * Adds a single transition rule to the current window. - *

- * This adds a rule such that the offset, expressed as a daylight savings amount, - * changes at the specified date-time. - * - * @param year the year of the transition, from MIN_YEAR to MAX_YEAR - * @param month the month of the transition, not null - * @param dayOfMonthIndicator the day-of-month of the transition, adjusted by dayOfWeek, - * from 1 to 31 adjusted later, or -1 to -28 adjusted earlier from the last day of the month - * @param time the time that the transition occurs as defined by timeDefintion, not null - * @param timeEndOfDay whether midnight is at the end of day - * @param timeDefinition the definition of how to convert local to actual time, not null - * @param savingAmountSecs the amount of saving from the standard offset after the transition in seconds - * @return this, for chaining - * @throws DateTimeException if a date-time field is out of range - * @throws IllegalStateException if no window has yet been added - * @throws IllegalStateException if the window already has fixed savings - * @throws IllegalStateException if the window has reached the maximum capacity of 2000 rules - */ - public ZoneRulesBuilder addRuleToWindow( - int year, - int month, - int dayOfMonthIndicator, - LocalTime time, - boolean timeEndOfDay, - TimeDefinition timeDefinition, - int savingAmountSecs) { - return addRuleToWindow(year, year, month, dayOfMonthIndicator, -1, time, timeEndOfDay, timeDefinition, savingAmountSecs); - } - - /** - * Adds a multi-year transition rule to the current window. - *

- * This adds a rule such that the offset, expressed as a daylight savings amount, - * changes at the specified date-time for each year in the range. - * - * @param startYear the start year of the rule, from MIN_YEAR to MAX_YEAR - * @param endYear the end year of the rule, from MIN_YEAR to MAX_YEAR - * @param month the month of the transition, from 1 to 12 - * @param dayOfMonthIndicator the day-of-month of the transition, adjusted by dayOfWeek, - * from 1 to 31 adjusted later, or -1 to -28 adjusted earlier from the last day of the month - * @param dayOfWeek the day-of-week to adjust to, -1 if day-of-month should not be adjusted - * @param time the time that the transition occurs as defined by timeDefintion, not null - * @param timeEndOfDay whether midnight is at the end of day - * @param timeDefinition the definition of how to convert local to actual time, not null - * @param savingAmountSecs the amount of saving from the standard offset after the transition in seconds - * @return this, for chaining - * @throws DateTimeException if a date-time field is out of range - * @throws IllegalArgumentException if the day of month indicator is invalid - * @throws IllegalArgumentException if the end of day midnight flag does not match the time - * @throws IllegalStateException if no window has yet been added - * @throws IllegalStateException if the window already has fixed savings - * @throws IllegalStateException if the window has reached the maximum capacity of 2000 rules - */ - public ZoneRulesBuilder addRuleToWindow( - int startYear, - int endYear, - int month, - int dayOfMonthIndicator, - int dayOfWeek, - LocalTime time, - boolean timeEndOfDay, - TimeDefinition timeDefinition, - int savingAmountSecs) { - Objects.requireNonNull(time, "time"); - Objects.requireNonNull(timeDefinition, "timeDefinition"); - if (dayOfMonthIndicator < -28 || dayOfMonthIndicator > 31 || dayOfMonthIndicator == 0) { - throw new IllegalArgumentException("Day of month indicator must be between -28 and 31 inclusive excluding zero"); - } - if (timeEndOfDay && time.equals(LocalTime.MIDNIGHT) == false) { - throw new IllegalArgumentException("Time must be midnight when end of day flag is true"); - } - if (windowList.isEmpty()) { - throw new IllegalStateException("Must add a window before adding a rule"); - } - TZWindow window = windowList.get(windowList.size() - 1); - window.addRule(startYear, endYear, month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefinition, savingAmountSecs); - return this; - } - - //----------------------------------------------------------------------- - /** - * Completes the build converting the builder to a set of time-zone rules. - *

- * Calling this method alters the state of the builder. - * Further rules should not be added to this builder once this method is called. - * - * @param zoneId the time-zone ID, not null - * @return the zone rules, not null - * @throws IllegalStateException if no windows have been added - * @throws IllegalStateException if there is only one rule defined as being forever for any given window - */ - public ZoneRules toRules(String zoneId) { - Objects.requireNonNull(zoneId, "zoneId"); - if (windowList.isEmpty()) { - throw new IllegalStateException("No windows have been added to the builder"); - } - - final List standardTransitionList = new ArrayList<>(4); - final List transitionList = new ArrayList<>(256); - final List lastTransitionRuleList = new ArrayList<>(2); - - // initialize the standard offset calculation - final TZWindow firstWindow = windowList.get(0); - ZoneOffset loopStandardOffset = firstWindow.standardOffset; - int loopSavings = 0; - if (firstWindow.fixedSavingAmountSecs != null) { - loopSavings = firstWindow.fixedSavingAmountSecs; - } - final ZoneOffset firstWallOffset = ZoneOffset.ofTotalSeconds(loopStandardOffset.getTotalSeconds() + loopSavings); - LocalDateTime loopWindowStart = LocalDateTime.of(YEAR_MIN_VALUE, 1, 1, 0, 0); - ZoneOffset loopWindowOffset = firstWallOffset; - - // build the windows and rules to interesting data - for (TZWindow window : windowList) { - // tidy the state - window.tidy(loopWindowStart.getYear()); - - // calculate effective savings at the start of the window - Integer effectiveSavings = window.fixedSavingAmountSecs; - if (effectiveSavings == null) { - // apply rules from this window together with the standard offset and - // savings from the last window to find the savings amount applicable - // at start of this window - effectiveSavings = 0; - for (TZRule rule : window.ruleList) { - if (rule.toEpochSecond(loopStandardOffset, loopSavings) > loopWindowStart.toEpochSecond(loopWindowOffset)) { - // previous savings amount found, which could be the savings amount at - // the instant that the window starts (hence isAfter) - break; - } - effectiveSavings = rule.savingAmountSecs; - } - } - - // check if standard offset changed, and update it - if (loopStandardOffset.equals(window.standardOffset) == false) { - standardTransitionList.add( - new ZoneOffsetTransition( - LocalDateTime.ofEpochSecond(loopWindowStart.toEpochSecond(loopWindowOffset), 0, loopStandardOffset), - loopStandardOffset, window.standardOffset)); - loopStandardOffset = window.standardOffset; - } - - // check if the start of the window represents a transition - ZoneOffset effectiveWallOffset = ZoneOffset.ofTotalSeconds(loopStandardOffset.getTotalSeconds() + effectiveSavings); - if (loopWindowOffset.equals(effectiveWallOffset) == false) { - transitionList.add(new ZoneOffsetTransition(loopWindowStart, loopWindowOffset, effectiveWallOffset)); - } - loopSavings = effectiveSavings; - - // apply rules within the window - for (TZRule rule : window.ruleList) { - if (rule.isTransition(loopSavings)) { - ZoneOffsetTransition trans = rule.toTransition(loopStandardOffset, loopSavings); - if (trans.toEpochSecond() < loopWindowStart.toEpochSecond(loopWindowOffset) == false && - trans.toEpochSecond() < window.createDateTimeEpochSecond(loopSavings)) { - transitionList.add(trans); - loopSavings = rule.savingAmountSecs; - } - } - } - - // calculate last rules - for (TZRule lastRule : window.lastRuleList) { - lastTransitionRuleList.add(lastRule.toTransitionRule(loopStandardOffset, loopSavings)); - loopSavings = lastRule.savingAmountSecs; - } - - // finally we can calculate the true end of the window, passing it to the next window - loopWindowOffset = window.createWallOffset(loopSavings); - loopWindowStart = LocalDateTime.ofEpochSecond( - window.createDateTimeEpochSecond(loopSavings), 0, loopWindowOffset); - } - - return new ZoneRules( - firstWindow.standardOffset, firstWallOffset, standardTransitionList, - transitionList, lastTransitionRuleList); - } - - //----------------------------------------------------------------------- - /** - * A definition of a window in the time-line. - * The window will have one standard offset and will either have a - * fixed DST savings or a set of rules. - */ - class TZWindow { - /** The standard offset during the window, not null. */ - private final ZoneOffset standardOffset; - /** The end local time, not null. */ - private final LocalDateTime windowEnd; - /** The type of the end time, not null. */ - private final TimeDefinition timeDefinition; - - /** The fixed amount of the saving to be applied during this window. */ - private Integer fixedSavingAmountSecs; - /** The rules for the current window. */ - private List ruleList = new ArrayList<>(); - /** The latest year that the last year starts at. */ - private int maxLastRuleStartYear = YEAR_MIN_VALUE; - /** The last rules. */ - private List lastRuleList = new ArrayList<>(); - - /** - * Constructor. - * - * @param standardOffset the standard offset applicable during the window, not null - * @param windowEnd the end of the window, relative to the time definition, null if forever - * @param timeDefinition the time definition for calculating the true end, not null - */ - TZWindow( - ZoneOffset standardOffset, - LocalDateTime windowEnd, - TimeDefinition timeDefinition) { - super(); - this.windowEnd = windowEnd; - this.timeDefinition = timeDefinition; - this.standardOffset = standardOffset; - } - - /** - * Sets the fixed savings amount for the window. - * - * @param fixedSavingAmount the amount of daylight saving to apply throughout the window, may be null - * @throws IllegalStateException if the window already has rules - */ - void setFixedSavings(int fixedSavingAmount) { - if (ruleList.size() > 0 || lastRuleList.size() > 0) { - throw new IllegalStateException("Window has DST rules, so cannot have fixed savings"); - } - this.fixedSavingAmountSecs = fixedSavingAmount; - } - - /** - * Adds a rule to the current window. - * - * @param startYear the start year of the rule, from MIN_YEAR to MAX_YEAR - * @param endYear the end year of the rule, from MIN_YEAR to MAX_YEAR - * @param month the month of the transition, not null - * @param dayOfMonthIndicator the day-of-month of the transition, adjusted by dayOfWeek, - * from 1 to 31 adjusted later, or -1 to -28 adjusted earlier from the last day of the month - * @param dayOfWeek the day-of-week to adjust to, null if day-of-month should not be adjusted - * @param time the time that the transition occurs as defined by timeDefintion, not null - * @param timeEndOfDay whether midnight is at the end of day - * @param timeDefinition the definition of how to convert local to actual time, not null - * @param savingAmountSecs the amount of saving from the standard offset in seconds - * @throws IllegalStateException if the window already has fixed savings - * @throws IllegalStateException if the window has reached the maximum capacity of 2000 rules - */ - void addRule( - int startYear, - int endYear, - int month, - int dayOfMonthIndicator, - int dayOfWeek, - LocalTime time, - boolean timeEndOfDay, - TimeDefinition timeDefinition, - int savingAmountSecs) { - - if (fixedSavingAmountSecs != null) { - throw new IllegalStateException("Window has a fixed DST saving, so cannot have DST rules"); - } - if (ruleList.size() >= 2000) { - throw new IllegalStateException("Window has reached the maximum number of allowed rules"); - } - boolean lastRule = false; - if (endYear == YEAR_MAX_VALUE) { - lastRule = true; - endYear = startYear; - } - int year = startYear; - while (year <= endYear) { - TZRule rule = new TZRule(year, month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefinition, savingAmountSecs); - if (lastRule) { - lastRuleList.add(rule); - maxLastRuleStartYear = Math.max(startYear, maxLastRuleStartYear); - } else { - ruleList.add(rule); - } - year++; - } - } - - /** - * Validates that this window is after the previous one. - * - * @param previous the previous window, not null - * @throws IllegalStateException if the window order is invalid - */ - void validateWindowOrder(TZWindow previous) { - if (windowEnd.compareTo(previous.windowEnd) < 0) { - throw new IllegalStateException("Windows must be added in date-time order: " + - windowEnd + " < " + previous.windowEnd); - } - } - - /** - * Adds rules to make the last rules all start from the same year. - * Also add one more year to avoid weird case where penultimate year has odd offset. - * - * @param windowStartYear the window start year - * @throws IllegalStateException if there is only one rule defined as being forever - */ - void tidy(int windowStartYear) { - if (lastRuleList.size() == 1) { - throw new IllegalStateException("Cannot have only one rule defined as being forever"); - } - - // handle last rules - if (windowEnd.equals(LocalDateTime.MAX)) { - // setup at least one real rule, which closes off other windows nicely - maxLastRuleStartYear = Math.max(maxLastRuleStartYear, windowStartYear) + 1; - for (TZRule lastRule : lastRuleList) { - addRule(lastRule.year, maxLastRuleStartYear, lastRule.month, lastRule.dayOfMonthIndicator, - lastRule.dayOfWeek, lastRule.time, lastRule.timeEndOfDay, lastRule.timeDefinition, lastRule.savingAmountSecs); - lastRule.year = maxLastRuleStartYear + 1; - } - if (maxLastRuleStartYear == YEAR_MAX_VALUE) { - lastRuleList.clear(); - } else { - maxLastRuleStartYear++; - } - } else { - // convert all within the endYear limit - int endYear = windowEnd.getYear(); - for (TZRule lastRule : lastRuleList) { - addRule(lastRule.year, endYear + 1, lastRule.month, lastRule.dayOfMonthIndicator, - lastRule.dayOfWeek, lastRule.time, lastRule.timeEndOfDay, lastRule.timeDefinition, lastRule.savingAmountSecs); - } - lastRuleList.clear(); - maxLastRuleStartYear = YEAR_MAX_VALUE; - } - - // ensure lists are sorted - Collections.sort(ruleList); - Collections.sort(lastRuleList); - - // default fixed savings to zero - if (ruleList.size() == 0 && fixedSavingAmountSecs == null) { - fixedSavingAmountSecs = 0; - } - } - - /** - * Checks if the window is empty. - * - * @return true if the window is only a standard offset - */ - boolean isSingleWindowStandardOffset() { - return windowEnd.equals(LocalDateTime.MAX) && timeDefinition == TimeDefinition.WALL && - fixedSavingAmountSecs == null && lastRuleList.isEmpty() && ruleList.isEmpty(); - } - - /** - * Creates the wall offset for the local date-time at the end of the window. - * - * @param savingsSecs the amount of savings in use in seconds - * @return the created date-time epoch second in the wall offset, not null - */ - ZoneOffset createWallOffset(int savingsSecs) { - return ZoneOffset.ofTotalSeconds(standardOffset.getTotalSeconds() + savingsSecs); - } - - /** - * Creates the offset date-time for the local date-time at the end of the window. - * - * @param savingsSecs the amount of savings in use in seconds - * @return the created date-time epoch second in the wall offset, not null - */ - long createDateTimeEpochSecond(int savingsSecs) { - ZoneOffset wallOffset = createWallOffset(savingsSecs); - LocalDateTime ldt = timeDefinition.createDateTime(windowEnd, standardOffset, wallOffset); - return ldt.toEpochSecond(wallOffset); - } - } - - //----------------------------------------------------------------------- - /** - * A definition of the way a local time can be converted to an offset time. - */ - class TZRule implements Comparable { - private int year; - private int month; - private int dayOfMonthIndicator; - private int dayOfWeek; - private LocalTime time; - private boolean timeEndOfDay; // Whether the local time is end of day. - private TimeDefinition timeDefinition; // The type of the time. - private int savingAmountSecs; // The amount of the saving to be applied after this point. - - /** - * Constructor. - * - * @param year the year - * @param month the month, value from 1 to 12 - * @param dayOfMonthIndicator the day-of-month of the transition, adjusted by dayOfWeek, - * from 1 to 31 adjusted later, or -1 to -28 adjusted earlier from the last day of the month - * @param dayOfWeek the day-of-week, -1 if day-of-month is exact - * @param time the time, not null - * @param timeEndOfDay whether midnight is at the end of day - * @param timeDefinition the time definition, not null - * @param savingAfterSecs the savings amount in seconds - */ - TZRule(int year, int month, int dayOfMonthIndicator, - int dayOfWeek, LocalTime time, boolean timeEndOfDay, - TimeDefinition timeDefinition, int savingAfterSecs) { - this.year = year; - this.month = month; - this.dayOfMonthIndicator = dayOfMonthIndicator; - this.dayOfWeek = dayOfWeek; - this.time = time; - this.timeEndOfDay = timeEndOfDay; - this.timeDefinition = timeDefinition; - this.savingAmountSecs = savingAfterSecs; - } - - /** - * Converts this to a transition. - * - * @param standardOffset the active standard offset, not null - * @param savingsBeforeSecs the active savings in seconds - * @return the transition, not null - */ - ZoneOffsetTransition toTransition(ZoneOffset standardOffset, int savingsBeforeSecs) { - // copy of code in ZoneOffsetTransitionRule to avoid infinite loop - LocalDate date = toLocalDate(); - LocalDateTime ldt = LocalDateTime.of(date, time); - ZoneOffset wallOffset = ZoneOffset.ofTotalSeconds(standardOffset.getTotalSeconds() + savingsBeforeSecs); - LocalDateTime dt = timeDefinition.createDateTime(ldt, standardOffset, wallOffset); - ZoneOffset offsetAfter = ZoneOffset.ofTotalSeconds(standardOffset.getTotalSeconds() + savingAmountSecs); - return new ZoneOffsetTransition(dt, wallOffset, offsetAfter); - } - - /** - * Returns the apoch second of this rules with the specified - * active standard offset and active savings - * - * @param standardOffset the active standard offset, not null - * @param savingsBeforeSecs the active savings in seconds - * @return the transition epoch second - */ - long toEpochSecond(ZoneOffset standardOffset, int savingsBeforeSecs) { - LocalDateTime ldt = LocalDateTime.of(toLocalDate(), time); - ZoneOffset wallOffset = ZoneOffset.ofTotalSeconds(standardOffset.getTotalSeconds() + savingsBeforeSecs); - return timeDefinition.createDateTime(ldt, standardOffset, wallOffset) - .toEpochSecond(wallOffset); - } - - /** - * Tests if this a real transition with the active savings in seconds - * - * @param savingsBeforeSecs the active savings in seconds - * @return true, if savings in seconds changes - */ - boolean isTransition(int savingsBeforeSecs) { - return savingAmountSecs != savingsBeforeSecs; - } - - /** - * Converts this to a transition rule. - * - * @param standardOffset the active standard offset, not null - * @param savingsBeforeSecs the active savings before the transition in seconds - * @return the transition, not null - */ - ZoneOffsetTransitionRule toTransitionRule(ZoneOffset standardOffset, int savingsBeforeSecs) { - // optimize stored format - if (dayOfMonthIndicator < 0) { - if (month != 2) { // not Month.FEBRUARY - dayOfMonthIndicator = maxLengthOfMonth(month) - 6; - } - } - if (timeEndOfDay && dayOfMonthIndicator > 0 && - (dayOfMonthIndicator == 28 && month == 2) == false) { - LocalDate date = LocalDate.of(2004, month, dayOfMonthIndicator).plusDays(1); // leap-year - month = date.getMonth(); - dayOfMonthIndicator = date.getDayOfMonth(); - if (dayOfWeek != -1) { - dayOfWeek = plusDayOfWeek(dayOfWeek, 1); - } - timeEndOfDay = false; - } - // build rule - return new ZoneOffsetTransitionRule( - month, dayOfMonthIndicator, dayOfWeek, time, timeEndOfDay, timeDefinition, - standardOffset, - ZoneOffset.ofTotalSeconds(standardOffset.getTotalSeconds() + savingsBeforeSecs), - ZoneOffset.ofTotalSeconds(standardOffset.getTotalSeconds() + savingAmountSecs)); - } - - public int compareTo(TZRule other) { - int cmp = year - other.year; - cmp = (cmp == 0 ? month - other.month : cmp); - if (cmp == 0) { - // convert to date to handle dow/domIndicator/timeEndOfDay - LocalDate thisDate = toLocalDate(); - LocalDate otherDate = other.toLocalDate(); - cmp = thisDate.compareTo(otherDate); - } - cmp = (cmp == 0 ? time.compareTo(other.time) : cmp); - return cmp; - } - - private LocalDate toLocalDate() { - LocalDate date; - if (dayOfMonthIndicator < 0) { - int monthLen = lengthOfMonth(month, isLeapYear(year)); - date = LocalDate.of(year, month, monthLen + 1 + dayOfMonthIndicator); - if (dayOfWeek != -1) { - date = previousOrSame(date, dayOfWeek); - } - } else { - date = LocalDate.of(year, month, dayOfMonthIndicator); - if (dayOfWeek != -1) { - date = nextOrSame(date, dayOfWeek); - } - } - if (timeEndOfDay) { - date = date.plusDays(1); - } - return date; - } - } - -} diff --git a/jdk/make/src/native/genconstants/ch/genSocketOptionRegistry.c b/jdk/make/src/native/genconstants/ch/genSocketOptionRegistry.c index d5ed5d7a87e..41bd5484ab7 100644 --- a/jdk/make/src/native/genconstants/ch/genSocketOptionRegistry.c +++ b/jdk/make/src/native/genconstants/ch/genSocketOptionRegistry.c @@ -110,6 +110,7 @@ int main(int argc, const char* argv[]) { emit_inet("StandardSocketOptions.IP_MULTICAST_LOOP", IPPROTO_IP, IP_MULTICAST_LOOP); #ifdef AF_INET6 + emit_inet6("StandardSocketOptions.IP_TOS", IPPROTO_IPV6, IPV6_TCLASS); emit_inet6("StandardSocketOptions.IP_MULTICAST_IF", IPPROTO_IPV6, IPV6_MULTICAST_IF); emit_inet6("StandardSocketOptions.IP_MULTICAST_TTL", IPPROTO_IPV6, IPV6_MULTICAST_HOPS); emit_inet6("StandardSocketOptions.IP_MULTICAST_LOOP", IPPROTO_IPV6, IPV6_MULTICAST_LOOP); diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxUI.java b/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxUI.java index c38e108633b..75c7babb58a 100644 --- a/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxUI.java +++ b/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxUI.java @@ -522,15 +522,17 @@ public class AquaComboBoxUI extends BasicComboBoxUI implements Sizeable { }; @SuppressWarnings("serial") // anonymous class - private static Action hideAction = new AbstractAction() { + private final Action hideAction = new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { final JComboBox comboBox = (JComboBox)e.getSource(); + comboBox.firePopupMenuCanceled(); + comboBox.setPopupVisible(false); + } - if (comboBox.isPopupVisible()) { - comboBox.firePopupMenuCanceled(); - comboBox.setPopupVisible(false); - } + @Override + public boolean isEnabled() { + return comboBox.isPopupVisible() && super.isEnabled(); } }; diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaFileSystemModel.java b/jdk/src/macosx/classes/com/apple/laf/AquaFileSystemModel.java index 37e627e8338..b0713215077 100644 --- a/jdk/src/macosx/classes/com/apple/laf/AquaFileSystemModel.java +++ b/jdk/src/macosx/classes/com/apple/laf/AquaFileSystemModel.java @@ -366,6 +366,11 @@ class AquaFileSystemModel extends AbstractTableModel implements PropertyChangeLi final SortableFile otherFile = (SortableFile)other; return otherFile.fFile.equals(fFile); } + + @Override + public int hashCode() { + return Objects.hashCode(fFile); + } } class LoadFilesThread extends Thread { diff --git a/jdk/src/macosx/classes/com/apple/laf/ScreenPopupFactory.java b/jdk/src/macosx/classes/com/apple/laf/ScreenPopupFactory.java index 1ab50a18679..bb2c0f1081b 100644 --- a/jdk/src/macosx/classes/com/apple/laf/ScreenPopupFactory.java +++ b/jdk/src/macosx/classes/com/apple/laf/ScreenPopupFactory.java @@ -29,18 +29,9 @@ import java.awt.*; import javax.swing.*; import sun.lwawt.macosx.CPlatformWindow; +import sun.swing.SwingAccessor; class ScreenPopupFactory extends PopupFactory { - static { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("osxui"); - return null; - } - }); - } - static final Float TRANSLUCENT = new Float(248f/255f); static final Float OPAQUE = new Float(1.0f); @@ -59,19 +50,13 @@ class ScreenPopupFactory extends PopupFactory { return (Window)w; } - /* - * Since we can't change the signature of PopupFactory, we have to call the - * private method getPopup(Component, Component, int, int, int) through JNI - * (see AquaLookAndFeel.m) - */ - native Popup _getHeavyWeightPopup(Component comp, Component invoker, int x, int y); - public Popup getPopup(final Component comp, final Component invoker, final int x, final int y) { if (invoker == null) throw new IllegalArgumentException("Popup.getPopup must be passed non-null contents"); final Popup popup; if (fIsActive) { - popup = _getHeavyWeightPopup(comp, invoker, x, y); + popup = SwingAccessor.getPopupFactoryAccessor() + .getHeavyWeightPopup(this, comp, invoker, x, y); } else { popup = super.getPopup(comp, invoker, x, y); } diff --git a/jdk/src/macosx/classes/sun/font/CStrike.java b/jdk/src/macosx/classes/sun/font/CStrike.java index af4f8754cfb..5296f5c87f0 100644 --- a/jdk/src/macosx/classes/sun/font/CStrike.java +++ b/jdk/src/macosx/classes/sun/font/CStrike.java @@ -415,7 +415,7 @@ public final class CStrike extends FontStrike { generalCache = new HashMap(); } - generalCache.put(new Integer(index), new Long(value)); + generalCache.put(new Integer(index), Long.valueOf(value)); } public synchronized void dispose() { diff --git a/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java b/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java index 354f2538012..408862f7746 100644 --- a/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java +++ b/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java @@ -317,6 +317,8 @@ public abstract class LWComponentPeer * subclasses to initialize specific peers properties. */ void initializeImpl() { + // note that these methods can be overridden by the user and + // can return some strange values like null. setBackground(target.getBackground()); setForeground(target.getForeground()); setFont(target.getFont()); diff --git a/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java b/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java index 226d8c68699..b72ef77d876 100644 --- a/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java +++ b/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java @@ -443,6 +443,12 @@ public class LWWindowPeer getPlatformWindow().updateIconImages(); } + @Override + public void setBackground(final Color c) { + super.setBackground(c); + updateOpaque(); + } + @Override public void setOpacity(float opacity) { getPlatformWindow().setOpacity(opacity); diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java index dd718c0ca0b..c241aae3cc0 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java @@ -97,7 +97,8 @@ public class CEmbeddedFrame extends EmbeddedFrame { public void handleKeyEvent(int eventType, int modifierFlags, String characters, String charsIgnoringMods, boolean isRepeat, short keyCode, boolean needsKeyTyped) { - responder.handleKeyEvent(eventType, modifierFlags, charsIgnoringMods, keyCode, needsKeyTyped, isRepeat); + responder.handleKeyEvent(eventType, modifierFlags, characters, charsIgnoringMods, + keyCode, needsKeyTyped, isRepeat); } public void handleInputEvent(String text) { diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformLWWindow.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformLWWindow.java index d7a91264328..9c2edf22742 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformLWWindow.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformLWWindow.java @@ -29,12 +29,18 @@ import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; import java.awt.Insets; import java.awt.MenuBar; import java.awt.Point; +import java.awt.Rectangle; import java.awt.Window; +import sun.awt.CGraphicsDevice; +import sun.awt.CGraphicsEnvironment; import sun.awt.CausedFocusEvent; +import sun.awt.LightweightFrame; import sun.java2d.SurfaceData; +import sun.lwawt.LWLightweightFramePeer; import sun.lwawt.LWWindowPeer; import sun.lwawt.PlatformWindow; @@ -72,11 +78,6 @@ public class CPlatformLWWindow extends CPlatformWindow { return null; } - @Override - public GraphicsDevice getGraphicsDevice() { - return null; - } - @Override public SurfaceData getScreenSurface() { return null; @@ -199,4 +200,24 @@ public class CPlatformLWWindow extends CPlatformWindow { public long getLayerPtr() { return 0; } + + @Override + public GraphicsDevice getGraphicsDevice() { + CGraphicsEnvironment ge = (CGraphicsEnvironment)GraphicsEnvironment. + getLocalGraphicsEnvironment(); + + LWLightweightFramePeer peer = (LWLightweightFramePeer)getPeer(); + int scale = ((LightweightFrame)peer.getTarget()).getScaleFactor(); + + Rectangle bounds = ((LightweightFrame)peer.getTarget()).getHostBounds(); + for (GraphicsDevice d : ge.getScreenDevices()) { + if (d.getDefaultConfiguration().getBounds().intersects(bounds) && + ((CGraphicsDevice)d).getScaleFactor() == scale) + { + return d; + } + } + // We shouldn't be here... + return ge.getDefaultScreenDevice(); + } } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java index d8d1555450c..591c16d2879 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java @@ -125,7 +125,7 @@ final class CPlatformResponder { /** * Handles key events. */ - void handleKeyEvent(int eventType, int modifierFlags, String chars, + void handleKeyEvent(int eventType, int modifierFlags, String chars, String charsIgnoringModifiers, short keyCode, boolean needsKeyTyped, boolean needsKeyReleased) { boolean isFlagsChangedEvent = isNpapiCallback ? (eventType == CocoaConstants.NPCocoaEventFlagsChanged) : @@ -153,7 +153,10 @@ final class CPlatformResponder { testChar = chars.charAt(0); } - int[] in = new int[] {testChar, isDeadChar ? 1 : 0, modifierFlags, keyCode}; + char testCharIgnoringModifiers = charsIgnoringModifiers != null && charsIgnoringModifiers.length() > 0 ? + charsIgnoringModifiers.charAt(0) : KeyEvent.CHAR_UNDEFINED; + + int[] in = new int[] {testCharIgnoringModifiers, isDeadChar ? 1 : 0, modifierFlags, keyCode}; int[] out = new int[3]; // [jkeyCode, jkeyLocation, deadChar] postsTyped = NSEvent.nsToJavaKeyInfo(in, out); diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java index e81371b4751..3c2cd2325e4 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java @@ -200,7 +200,7 @@ public class CPlatformView extends CFRetainedResource { } private void deliverKeyEvent(NSEvent event) { - responder.handleKeyEvent(event.getType(), event.getModifierFlags(), + responder.handleKeyEvent(event.getType(), event.getModifierFlags(), event.getCharacters(), event.getCharactersIgnoringModifiers(), event.getKeyCode(), true, false); } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java index edf25ddb313..534cf0dd744 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java @@ -119,6 +119,7 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo static final int NONACTIVATING = 1 << 24; static final int IS_DIALOG = 1 << 25; static final int IS_MODAL = 1 << 26; + static final int IS_POPUP = 1 << 27; static final int _STYLE_PROP_BITMASK = DECORATED | TEXTURED | UNIFIED | UTILITY | HUD | SHEET | CLOSEABLE | MINIMIZABLE | RESIZABLE; @@ -318,6 +319,7 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo styleBits = SET(styleBits, TEXTURED, false); // Popups in applets don't activate applet's process styleBits = SET(styleBits, NONACTIVATING, true); + styleBits = SET(styleBits, IS_POPUP, true); } if (Window.Type.UTILITY.equals(target.getType())) { @@ -744,20 +746,22 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo @Override public void setOpaque(boolean isOpaque) { CWrapper.NSWindow.setOpaque(getNSWindowPtr(), isOpaque); - boolean isTextured = (peer == null)? false : peer.isTextured(); - if (!isOpaque && !isTextured) { - long clearColor = CWrapper.NSColor.clearColor(); - CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), clearColor); + boolean isTextured = (peer == null) ? false : peer.isTextured(); + if (!isTextured) { + if (!isOpaque) { + CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), 0); + } else if (peer != null) { + Color color = peer.getBackground(); + if (color != null) { + int rgb = color.getRGB(); + CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), rgb); + } + } } //This is a temporary workaround. Looks like after 7124236 will be fixed //the correct place for invalidateShadow() is CGLayer.drawInCGLContext. - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - invalidateShadow(); - } - }); + SwingUtilities.invokeLater(this::invalidateShadow); } @Override diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java index 8c2e9c01f2d..f0fec624d8d 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java @@ -61,7 +61,14 @@ final class CWrapper { static native void setAlphaValue(long window, float alpha); static native void setOpaque(long window, boolean opaque); - static native void setBackgroundColor(long window, long color); + + /** + * Sets background color of the NSWindow. + * + * @param window the pointer of the NSWindow + * @param color the color in argb format + */ + static native void setBackgroundColor(long window, int color); static native void miniaturize(long window); static native void deminiaturize(long window); @@ -82,8 +89,4 @@ final class CWrapper { static native void setToolTip(long view, String msg); } - - static final class NSColor { - static native long clearColor(); - } } diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java b/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java index ddb74d42b02..d30a39cdfb9 100644 --- a/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java +++ b/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java @@ -47,13 +47,15 @@ final class NSEvent { // Key event information private short keyCode; + private String characters; private String charactersIgnoringModifiers; // Called from native - NSEvent(int type, int modifierFlags, short keyCode, String charactersIgnoringModifiers) { + NSEvent(int type, int modifierFlags, short keyCode, String characters, String charactersIgnoringModifiers) { this.type = type; this.modifierFlags = modifierFlags; this.keyCode = keyCode; + this.characters = characters; this.charactersIgnoringModifiers = charactersIgnoringModifiers; } @@ -121,12 +123,16 @@ final class NSEvent { return charactersIgnoringModifiers; } + String getCharacters() { + return characters; + } + @Override public String toString() { return "NSEvent[" + getType() + " ," + getModifierFlags() + " ," + getClickCount() + " ," + getButtonNumber() + " ," + getX() + " ," + getY() + " ," + getAbsX() + " ," + getAbsY()+ " ," + getKeyCode() + " ," - + getCharactersIgnoringModifiers() + "]"; + + getCharacters() + " ," + getCharactersIgnoringModifiers() + "]"; } /* diff --git a/jdk/src/macosx/native/com/apple/laf/ScreenPopupFactory.m b/jdk/src/macosx/native/com/apple/laf/ScreenPopupFactory.m deleted file mode 100644 index 516ce45d5a0..00000000000 --- a/jdk/src/macosx/native/com/apple/laf/ScreenPopupFactory.m +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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 - * 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. - */ - -#import "com_apple_laf_ScreenPopupFactory.h" -#import - -static JNF_CLASS_CACHE(sjc_PopupFactory, "javax/swing/PopupFactory"); -static JNF_MEMBER_CACHE(jm_getPopup, sjc_PopupFactory, "getPopup", "(Ljava/awt/Component;Ljava/awt/Component;III)Ljavax/swing/Popup;"); - -/* - * Class: com_apple_laf_ScreenPopupFactory - * Method: _getHeavyWeightPopup - * Signature: (Ljava/awt/Component;Ljava/awt/Component;II)Ljavax/swing/Popup; - */ -JNIEXPORT jobject /* javax.swing.Popup */ JNICALL Java_com_apple_laf_ScreenPopupFactory__1getHeavyWeightPopup -(JNIEnv *env, jobject screenPopupFactory, jobject comp, jobject invoker, jint x, jint y) { - jobject popup; -JNF_COCOA_ENTER(env); - popup = JNFCallObjectMethod(env, screenPopupFactory, jm_getPopup, comp, invoker, x, y, 2); -JNF_COCOA_EXIT(env); - return popup; -} diff --git a/jdk/src/macosx/native/jobjc/JObjC.xcodeproj/default.pbxuser b/jdk/src/macosx/native/jobjc/JObjC.xcodeproj/default.pbxuser deleted file mode 100644 index cda3de5e2f2..00000000000 --- a/jdk/src/macosx/native/jobjc/JObjC.xcodeproj/default.pbxuser +++ /dev/null @@ -1,207 +0,0 @@ -// !$*UTF8*$! -/* - * 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 - * 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. - * - */ -{ - 00E6828EFEC88D1A11DB9C8B /* Project object */ = { - activeBuildConfigurationName = Release; - activeExecutable = 6A9FA6570246BA6C0CC91562 /* JObjC */; - activeTarget = EB9FD8610AEECCF5008E157E /* JObjC */; - addToTargets = ( - 4CEBA78E08679EF10015D03E /* JNILib */, - ); - breakpointsGroup = 0AB3651F0B2F67B300788B6C /* XCBreakpointsBucket */; - codeSenseManager = 0AB364DB0B2F66FD00788B6C /* Code sense */; - executables = ( - 6A9FA6570246BA6C0CC91562 /* JObjC */, - ); - perUserDictionary = { - PBXConfiguration.PBXFileTableDataSource3.PBXExecutablesDataSource = { - PBXFileTableDataSourceColumnSortingDirectionKey = "-1"; - PBXFileTableDataSourceColumnSortingKey = PBXExecutablesDataSource_NameID; - PBXFileTableDataSourceColumnWidthsKey = ( - 22, - 300, - 131, - ); - PBXFileTableDataSourceColumnsKey = ( - PBXExecutablesDataSource_ActiveFlagID, - PBXExecutablesDataSource_NameID, - PBXExecutablesDataSource_CommentsID, - ); - }; - PBXConfiguration.PBXFileTableDataSource3.PBXFileTableDataSource = { - PBXFileTableDataSourceColumnSortingDirectionKey = "-1"; - PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID; - PBXFileTableDataSourceColumnWidthsKey = ( - 20, - 245, - 20, - 48, - 43, - 43, - 20, - ); - PBXFileTableDataSourceColumnsKey = ( - PBXFileDataSource_FiletypeID, - PBXFileDataSource_Filename_ColumnID, - PBXFileDataSource_Built_ColumnID, - PBXFileDataSource_ObjectSize_ColumnID, - PBXFileDataSource_Errors_ColumnID, - PBXFileDataSource_Warnings_ColumnID, - PBXFileDataSource_Target_ColumnID, - ); - }; - PBXConfiguration.PBXTargetDataSource.PBXTargetDataSource = { - PBXFileTableDataSourceColumnSortingDirectionKey = "-1"; - PBXFileTableDataSourceColumnSortingKey = PBXFileDataSource_Filename_ColumnID; - PBXFileTableDataSourceColumnWidthsKey = ( - 20, - 200, - 65, - 20, - 48, - 43, - 43, - ); - PBXFileTableDataSourceColumnsKey = ( - PBXFileDataSource_FiletypeID, - PBXFileDataSource_Filename_ColumnID, - PBXTargetDataSource_PrimaryAttribute, - PBXFileDataSource_Built_ColumnID, - PBXFileDataSource_ObjectSize_ColumnID, - PBXFileDataSource_Errors_ColumnID, - PBXFileDataSource_Warnings_ColumnID, - ); - }; - }; - sourceControlManager = 0AB364DA0B2F66FD00788B6C /* Source Control */; - userBuildSettings = { - }; - }; - 0AB364DA0B2F66FD00788B6C /* Source Control */ = { - isa = PBXSourceControlManager; - fallbackIsa = XCSourceControlManager; - isSCMEnabled = 0; - scmConfiguration = { - }; - scmType = ""; - }; - 0AB364DB0B2F66FD00788B6C /* Code sense */ = { - isa = PBXCodeSenseManager; - indexTemplatePath = ""; - }; - 0AB3651F0B2F67B300788B6C /* XCBreakpointsBucket */ = { - isa = XCBreakpointsBucket; - name = "Project Breakpoints"; - objects = ( - ); - }; - 0AB365570B2F6ABB00788B6C /* JObjCdylib.c */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {847, 783}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRect = "{{0, 0}, {847, 783}}"; - sepNavWindowFrame = "{{84, 198}, {886, 912}}"; - }; - }; - 0A3CC35E0B94BB8800F6BA26 /* java */ = { - isa = PBXFileReference; - explicitFileType = "compiled.mach-o.executable"; - name = java; - path = /usr/bin/java; - sourceTree = ""; - }; - 363028F90383184400C91562 /* Manifest */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {847, 783}}"; - sepNavSelRange = "{0, 0}"; - sepNavVisRect = "{{0, 0}, {847, 783}}"; - sepNavWindowFrame = "{{38, 240}, {886, 912}}"; - }; - }; - 4CEBA78E08679EF10015D03E /* Dylib */ = { - activeExec = 0; - }; - 6A9FA6570246BA6C0CC91562 /* JObjC */ = { - isa = PBXExecutable; - activeArgIndex = 0; - activeArgIndices = ( - YES, - ); - argumentStrings = ( - "-cp JObjC.jar JObjC", - ); - autoAttachOnCrash = 1; - configStateDict = { - "PBXLSLaunchAction-0" = { - PBXLSLaunchAction = 0; - PBXLSLaunchStartAction = 1; - PBXLSLaunchStdioStyle = 2; - PBXLSLaunchStyle = 0; - class = PBXLSRunLaunchConfig; - displayName = "Executable Runner"; - identifier = com.apple.Xcode.launch.runConfig; - remoteHostInfo = ""; - startActionInfo = ""; - }; - "PBXLSLaunchAction-1" = { - PBXLSLaunchAction = 1; - PBXLSLaunchStartAction = 1; - PBXLSLaunchStdioStyle = 2; - PBXLSLaunchStyle = 0; - class = PBXJavaDebuggingNativeLaunchConfig; - displayName = "Java Debugger"; - identifier = com.apple.Xcode.launch.JavaDebugNativeConfig; - remoteHostInfo = ""; - startActionInfo = ""; - }; - }; - customDataFormattersEnabled = 1; - debuggerPlugin = GDBDebugging; - disassemblyDisplayState = 0; - dylibVariantSuffix = ""; - enableDebugStr = 1; - environmentEntries = ( - ); - executableSystemSymbolLevel = 0; - executableUserSymbolLevel = 0; - launchableReference = 0A3CC35E0B94BB8800F6BA26 /* java */; - libgmallocEnabled = 0; - name = JObjC; - sourceDirectories = ( - ); - startupPath = "dist"; - }; - EB9FD8610AEECCF5008E157E /* JObjC */ = { - activeExec = 0; - }; - EB9FD8720AEECD83008E157E /* build.xml */ = { - uiCtxt = { - sepNavIntBoundsRect = "{{0, 0}, {847, 1260}}"; - sepNavSelRange = "{1260, 0}"; - sepNavVisRect = "{{0, 8}, {847, 783}}"; - sepNavWindowFrame = "{{752, 266}, {886, 912}}"; - }; - }; -} diff --git a/jdk/src/macosx/native/jobjc/JObjC.xcodeproj/project.pbxproj b/jdk/src/macosx/native/jobjc/JObjC.xcodeproj/project.pbxproj deleted file mode 100644 index 61cf3948d0d..00000000000 --- a/jdk/src/macosx/native/jobjc/JObjC.xcodeproj/project.pbxproj +++ /dev/null @@ -1,1397 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 44; - objects = { - -/* Begin PBXAggregateTarget section */ - 89EBD58C0C95F43D000F04A0 /* B&I */ = { - isa = PBXAggregateTarget; - buildConfigurationList = 89EBD5930C95F44E000F04A0 /* Build configuration list for PBXAggregateTarget "B&I" */; - buildPhases = ( - ); - dependencies = ( - C592D6590E12F27400D076FF /* PBXTargetDependency */, - C592D65B0E12F27600D076FF /* PBXTargetDependency */, - C592D65D0E12F27E00D076FF /* PBXTargetDependency */, - 89D7CB9C0CDC64F800472EA2 /* PBXTargetDependency */, - C592D65F0E12F28500D076FF /* PBXTargetDependency */, - C592D6610E12F28E00D076FF /* PBXTargetDependency */, - C592D6630E12F29200D076FF /* PBXTargetDependency */, - 89D7CC920CDE7A8200472EA2 /* PBXTargetDependency */, - ); - name = "B&I"; - productName = "B&I"; - }; -/* End PBXAggregateTarget section */ - -/* Begin PBXBuildFile section */ - 89D7C9F70CDB900E00472EA2 /* CIF.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9EC0CDB900E00472EA2 /* CIF.m */; }; - 89D7C9F80CDB900E00472EA2 /* Coder.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9ED0CDB900E00472EA2 /* Coder.m */; }; - 89D7C9F90CDB900E00472EA2 /* Function.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9EE0CDB900E00472EA2 /* Function.m */; }; - 89D7C9FA0CDB900E00472EA2 /* ID.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9EF0CDB900E00472EA2 /* ID.m */; }; - 89D7C9FB0CDB900E00472EA2 /* JObjCRuntime.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9F00CDB900E00472EA2 /* JObjCRuntime.m */; }; - 89D7C9FC0CDB900E00472EA2 /* MacOSXFramework.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9F10CDB900E00472EA2 /* MacOSXFramework.m */; }; - 89D7C9FD0CDB900E00472EA2 /* NativeBuffer.h in Headers */ = {isa = PBXBuildFile; fileRef = 89D7C9F20CDB900E00472EA2 /* NativeBuffer.h */; }; - 89D7C9FE0CDB900E00472EA2 /* NativeBuffer.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9F30CDB900E00472EA2 /* NativeBuffer.m */; }; - 89D7C9FF0CDB900E00472EA2 /* NativeObjectLifecycleManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9F40CDB900E00472EA2 /* NativeObjectLifecycleManager.m */; }; - 89D7CA000CDB900E00472EA2 /* NSClass.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9F50CDB900E00472EA2 /* NSClass.m */; }; - 89D7CA010CDB900E00472EA2 /* SEL.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9F60CDB900E00472EA2 /* SEL.m */; }; - 89D7CB770CDC4A6500472EA2 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 890FBACC0C6F782C00902C32 /* Foundation.framework */; }; - 89D7CB780CDC4A6500472EA2 /* JavaVM.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 890FBACA0C6F781000902C32 /* JavaVM.framework */; }; - 89D7CB790CDC4A6500472EA2 /* JavaNativeFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 896D90BB0CC2877C005625F5 /* JavaNativeFoundation.framework */; }; - 89D7CB7A0CDC4A6500472EA2 /* libffi.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 89E437680C97A7F200C756EE /* libffi.dylib */; }; - 89D7CCA40CDF9A2600472EA2 /* NativeBuffer.h in Headers */ = {isa = PBXBuildFile; fileRef = 89D7C9F20CDB900E00472EA2 /* NativeBuffer.h */; }; - 89D7CCA60CDF9A2600472EA2 /* CIF.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9EC0CDB900E00472EA2 /* CIF.m */; }; - 89D7CCA70CDF9A2600472EA2 /* Coder.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9ED0CDB900E00472EA2 /* Coder.m */; }; - 89D7CCA80CDF9A2600472EA2 /* Function.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9EE0CDB900E00472EA2 /* Function.m */; }; - 89D7CCA90CDF9A2600472EA2 /* ID.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9EF0CDB900E00472EA2 /* ID.m */; }; - 89D7CCAA0CDF9A2600472EA2 /* JObjCRuntime.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9F00CDB900E00472EA2 /* JObjCRuntime.m */; }; - 89D7CCAB0CDF9A2600472EA2 /* MacOSXFramework.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9F10CDB900E00472EA2 /* MacOSXFramework.m */; }; - 89D7CCAC0CDF9A2600472EA2 /* NativeBuffer.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9F30CDB900E00472EA2 /* NativeBuffer.m */; }; - 89D7CCAD0CDF9A2600472EA2 /* NativeObjectLifecycleManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9F40CDB900E00472EA2 /* NativeObjectLifecycleManager.m */; }; - 89D7CCAE0CDF9A2600472EA2 /* NSClass.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9F50CDB900E00472EA2 /* NSClass.m */; }; - 89D7CCAF0CDF9A2600472EA2 /* SEL.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7C9F60CDB900E00472EA2 /* SEL.m */; }; - 89D7CCB10CDF9A2600472EA2 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 890FBACC0C6F782C00902C32 /* Foundation.framework */; }; - 89D7CCB20CDF9A2600472EA2 /* JavaVM.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 890FBACA0C6F781000902C32 /* JavaVM.framework */; }; - 89D7CCB30CDF9A2600472EA2 /* JavaNativeFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 896D90BB0CC2877C005625F5 /* JavaNativeFoundation.framework */; }; - 89D7CCB40CDF9A2600472EA2 /* libffi.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 89E437680C97A7F200C756EE /* libffi.dylib */; }; - 89D7CCBB0CDF9AA200472EA2 /* NativeString.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7CCBA0CDF9AA200472EA2 /* NativeString.m */; }; - 89D7CCBD0CDF9AB100472EA2 /* NativeNumber.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7CCBC0CDF9AB100472EA2 /* NativeNumber.m */; }; - 89D7CCBF0CDF9AC600472EA2 /* NativeThread.m in Sources */ = {isa = PBXBuildFile; fileRef = 89D7CCBE0CDF9AC600472EA2 /* NativeThread.m */; }; - C5742F6D0E316EFA00093838 /* Subclassing.m in Sources */ = {isa = PBXBuildFile; fileRef = C5742F6B0E316EFA00093838 /* Subclassing.m */; }; - C5742F700E316F8600093838 /* Subclassing.m in Sources */ = {isa = PBXBuildFile; fileRef = C5742F6B0E316EFA00093838 /* Subclassing.m */; }; - C5D196C90DF9E43C006F9FB9 /* FFIType.m in Sources */ = {isa = PBXBuildFile; fileRef = C5D196C80DF9E43C006F9FB9 /* FFIType.m */; }; - C5D197D90DFB77C6006F9FB9 /* FFIType.m in Sources */ = {isa = PBXBuildFile; fileRef = C5D196C80DF9E43C006F9FB9 /* FFIType.m */; }; - C5E4547B0E36729F0046D3E8 /* Invoke.m in Sources */ = {isa = PBXBuildFile; fileRef = C5E454790E36729F0046D3E8 /* Invoke.m */; }; - C5E4547D0E367DAB0046D3E8 /* Invoke.m in Sources */ = {isa = PBXBuildFile; fileRef = C5E454790E36729F0046D3E8 /* Invoke.m */; }; - C5F3B23D0E39948300B771AE /* FunCallBench.m in Sources */ = {isa = PBXBuildFile; fileRef = C5F3B1370E398F8E00B771AE /* FunCallBench.m */; }; - C5F3B2620E3AB0F300B771AE /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C5F3B2610E3AB0F300B771AE /* AppKit.framework */; }; - C5F3B2640E3AB0F300B771AE /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C5F3B2630E3AB0F300B771AE /* Cocoa.framework */; }; - C5F3B2650E3AB0F300B771AE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 890FBACC0C6F782C00902C32 /* Foundation.framework */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 2CC7556013A1322100B09D1B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = EB9FD8610AEECCF5008E157E; - remoteInfo = "build-core-java"; - }; - 2CC7556213A1322800B09D1B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = C5F3B1530E39927900B771AE; - remoteInfo = "build-test-java"; - }; - 2CC7556413A1323700B09D1B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = 89D7CA160CDBA94D00472EA2; - remoteInfo = "build-generator-java"; - }; - 2CC7556613A1324300B09D1B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = 89D7CC600CDE75EC00472EA2; - remoteInfo = "build-additions-java"; - }; - 2CC7556813A1325700B09D1B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = 89D7CB870CDC4ED000472EA2; - remoteInfo = "run-generator"; - }; - 2CC7556A13A132AF00B09D1B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = 4CEBA78E08679EF10015D03E; - remoteInfo = "build-core-native"; - }; - 2CC7556C13A132B200B09D1B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = EB9FD8610AEECCF5008E157E; - remoteInfo = "build-core-java"; - }; - 89D7CB9B0CDC64F800472EA2 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = 89D7CB870CDC4ED000472EA2; - remoteInfo = "run-generator"; - }; - 89D7CC910CDE7A8200472EA2 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = 89D7CC720CDE767500472EA2; - remoteInfo = "assemble-product-java"; - }; - C592D6580E12F27400D076FF /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = EB9FD8610AEECCF5008E157E; - remoteInfo = "build-core-java"; - }; - C592D65A0E12F27600D076FF /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = 4CEBA78E08679EF10015D03E; - remoteInfo = "build-core-native"; - }; - C592D65C0E12F27E00D076FF /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = 89D7CA160CDBA94D00472EA2; - remoteInfo = "build-generator-java"; - }; - C592D65E0E12F28500D076FF /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = 89D7CC4C0CDE4C0400472EA2; - remoteInfo = "build-generated-java"; - }; - C592D6600E12F28E00D076FF /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = 89D7CC600CDE75EC00472EA2; - remoteInfo = "build-additions-java"; - }; - C592D6620E12F29200D076FF /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = 89D7CCA20CDF9A2600472EA2; - remoteInfo = "build-additions-native"; - }; - C5D197DA0DFB77E4006F9FB9 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 00E6828EFEC88D1A11DB9C8B /* Project object */; - proxyType = 1; - remoteGlobalIDString = 4CEBA78E08679EF10015D03E; - remoteInfo = "build-core-native"; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXFileReference section */ - 0AB364E40B2F671600788B6C /* src */ = {isa = PBXFileReference; lastKnownFileType = folder; path = src; sourceTree = ""; }; - 890FBACA0C6F781000902C32 /* JavaVM.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaVM.framework; path = /System/Library/Frameworks/JavaVM.framework; sourceTree = ""; }; - 890FBACC0C6F782C00902C32 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = /System/Library/Frameworks/Foundation.framework; sourceTree = ""; }; - 896D90BB0CC2877C005625F5 /* JavaNativeFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaNativeFoundation.framework; path = /System/Library/Frameworks/JavaVM.framework/Versions/A/Frameworks/JavaNativeFoundation.framework; sourceTree = ""; }; - 896D91230CC2ED34005625F5 /* README.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README.txt; sourceTree = ""; }; - 89736E5F0CE819E5008C4205 /* JObjC.jar */ = {isa = PBXFileReference; lastKnownFileType = archive.jar; path = JObjC.jar; sourceTree = BUILT_PRODUCTS_DIR; }; - 89D7C9EC0CDB900E00472EA2 /* CIF.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CIF.m; sourceTree = ""; }; - 89D7C9ED0CDB900E00472EA2 /* Coder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Coder.m; sourceTree = ""; }; - 89D7C9EE0CDB900E00472EA2 /* Function.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Function.m; sourceTree = ""; }; - 89D7C9EF0CDB900E00472EA2 /* ID.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ID.m; sourceTree = ""; }; - 89D7C9F00CDB900E00472EA2 /* JObjCRuntime.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JObjCRuntime.m; sourceTree = ""; }; - 89D7C9F10CDB900E00472EA2 /* MacOSXFramework.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MacOSXFramework.m; sourceTree = ""; }; - 89D7C9F20CDB900E00472EA2 /* NativeBuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NativeBuffer.h; sourceTree = ""; }; - 89D7C9F30CDB900E00472EA2 /* NativeBuffer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NativeBuffer.m; sourceTree = ""; }; - 89D7C9F40CDB900E00472EA2 /* NativeObjectLifecycleManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NativeObjectLifecycleManager.m; sourceTree = ""; }; - 89D7C9F50CDB900E00472EA2 /* NSClass.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NSClass.m; sourceTree = ""; }; - 89D7C9F60CDB900E00472EA2 /* SEL.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SEL.m; sourceTree = ""; }; - 89D7CCB80CDF9A2600472EA2 /* libJObjC.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libJObjC.dylib; sourceTree = BUILT_PRODUCTS_DIR; }; - 89D7CCBA0CDF9AA200472EA2 /* NativeString.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NativeString.m; sourceTree = ""; }; - 89D7CCBC0CDF9AB100472EA2 /* NativeNumber.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NativeNumber.m; sourceTree = ""; }; - 89D7CCBE0CDF9AC600472EA2 /* NativeThread.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NativeThread.m; sourceTree = ""; }; - 89E437680C97A7F200C756EE /* libffi.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libffi.dylib; path = /usr/lib/libffi.dylib; sourceTree = ""; }; - C5742F6B0E316EFA00093838 /* Subclassing.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Subclassing.m; sourceTree = ""; }; - C5D196C80DF9E43C006F9FB9 /* FFIType.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FFIType.m; sourceTree = ""; }; - C5E454790E36729F0046D3E8 /* Invoke.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Invoke.m; sourceTree = ""; }; - C5F3B1370E398F8E00B771AE /* FunCallBench.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FunCallBench.m; sourceTree = ""; }; - C5F3B1450E39910500B771AE /* libJObjC-tests.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = "libJObjC-tests.dylib"; sourceTree = BUILT_PRODUCTS_DIR; }; - C5F3B2610E3AB0F300B771AE /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = /System/Library/Frameworks/AppKit.framework; sourceTree = ""; }; - C5F3B2630E3AB0F300B771AE /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = /System/Library/Frameworks/Cocoa.framework; sourceTree = ""; }; - EB9FD8720AEECD83008E157E /* build.xml */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.xml; path = build.xml; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 4CEBA78D08679EF10015D03E /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 89D7CB770CDC4A6500472EA2 /* Foundation.framework in Frameworks */, - 89D7CB780CDC4A6500472EA2 /* JavaVM.framework in Frameworks */, - 89D7CB790CDC4A6500472EA2 /* JavaNativeFoundation.framework in Frameworks */, - 89D7CB7A0CDC4A6500472EA2 /* libffi.dylib in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 89D7CCB00CDF9A2600472EA2 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 89D7CCB10CDF9A2600472EA2 /* Foundation.framework in Frameworks */, - 89D7CCB20CDF9A2600472EA2 /* JavaVM.framework in Frameworks */, - 89D7CCB30CDF9A2600472EA2 /* JavaNativeFoundation.framework in Frameworks */, - 89D7CCB40CDF9A2600472EA2 /* libffi.dylib in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - C5F3B1430E39910500B771AE /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - C5F3B2620E3AB0F300B771AE /* AppKit.framework in Frameworks */, - C5F3B2640E3AB0F300B771AE /* Cocoa.framework in Frameworks */, - C5F3B2650E3AB0F300B771AE /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 00E6828FFEC88D1A11DB9C8B = { - isa = PBXGroup; - children = ( - 896D91230CC2ED34005625F5 /* README.txt */, - EB9FD8720AEECD83008E157E /* build.xml */, - 0AB364E40B2F671600788B6C /* src */, - 89D7C9EB0CDB900E00472EA2 /* native-core */, - 89D7CA020CDB902200472EA2 /* native-additions */, - C5A9597F0E398F050057C96D /* native-tests */, - 89D7CA030CDB903000472EA2 /* products */, - 890FBAC90C6F77B700902C32 /* frameworks */, - C5F3B1450E39910500B771AE /* libJObjC-tests.dylib */, - C5F3B2610E3AB0F300B771AE /* AppKit.framework */, - C5F3B2630E3AB0F300B771AE /* Cocoa.framework */, - ); - sourceTree = ""; - }; - 890FBAC90C6F77B700902C32 /* frameworks */ = { - isa = PBXGroup; - children = ( - 890FBACC0C6F782C00902C32 /* Foundation.framework */, - 890FBACA0C6F781000902C32 /* JavaVM.framework */, - 896D90BB0CC2877C005625F5 /* JavaNativeFoundation.framework */, - 89E437680C97A7F200C756EE /* libffi.dylib */, - ); - name = frameworks; - sourceTree = ""; - }; - 89D7C9EB0CDB900E00472EA2 /* native-core */ = { - isa = PBXGroup; - children = ( - 89D7C9EC0CDB900E00472EA2 /* CIF.m */, - 89D7C9ED0CDB900E00472EA2 /* Coder.m */, - C5D196C80DF9E43C006F9FB9 /* FFIType.m */, - 89D7C9EE0CDB900E00472EA2 /* Function.m */, - 89D7C9EF0CDB900E00472EA2 /* ID.m */, - C5E454790E36729F0046D3E8 /* Invoke.m */, - 89D7C9F00CDB900E00472EA2 /* JObjCRuntime.m */, - 89D7C9F10CDB900E00472EA2 /* MacOSXFramework.m */, - 89D7C9F20CDB900E00472EA2 /* NativeBuffer.h */, - 89D7C9F30CDB900E00472EA2 /* NativeBuffer.m */, - 89D7C9F40CDB900E00472EA2 /* NativeObjectLifecycleManager.m */, - 89D7C9F50CDB900E00472EA2 /* NSClass.m */, - 89D7C9F60CDB900E00472EA2 /* SEL.m */, - C5742F6B0E316EFA00093838 /* Subclassing.m */, - ); - name = "native-core"; - path = src/core/native; - sourceTree = ""; - }; - 89D7CA020CDB902200472EA2 /* native-additions */ = { - isa = PBXGroup; - children = ( - 89D7CCBA0CDF9AA200472EA2 /* NativeString.m */, - 89D7CCBC0CDF9AB100472EA2 /* NativeNumber.m */, - 89D7CCBE0CDF9AC600472EA2 /* NativeThread.m */, - ); - name = "native-additions"; - path = "src/runtime-additions/native"; - sourceTree = ""; - }; - 89D7CA030CDB903000472EA2 /* products */ = { - isa = PBXGroup; - children = ( - 89736E5F0CE819E5008C4205 /* JObjC.jar */, - 89D7CCB80CDF9A2600472EA2 /* libJObjC.dylib */, - ); - name = products; - path = "src/runtime-additions/native"; - sourceTree = ""; - }; - C5A9597F0E398F050057C96D /* native-tests */ = { - isa = PBXGroup; - children = ( - C5F3B1370E398F8E00B771AE /* FunCallBench.m */, - ); - name = "native-tests"; - path = src/tests/native; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXHeadersBuildPhase section */ - 4CEBA78B08679EF10015D03E /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 89D7C9FD0CDB900E00472EA2 /* NativeBuffer.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 89D7CCA30CDF9A2600472EA2 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 89D7CCA40CDF9A2600472EA2 /* NativeBuffer.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - C5F3B1410E39910500B771AE /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXHeadersBuildPhase section */ - -/* Begin PBXLegacyTarget section */ - 89D7CA160CDBA94D00472EA2 /* build-generator-java */ = { - isa = PBXLegacyTarget; - buildArgumentsString = "-verbose -emacs $ACTION"; - buildConfigurationList = 89D7CA1C0CDBA9B000472EA2 /* Build configuration list for PBXLegacyTarget "build-generator-java" */; - buildPhases = ( - ); - buildToolPath = /usr/bin/ant; - dependencies = ( - 2CC7556D13A132B200B09D1B /* PBXTargetDependency */, - 2CC7556B13A132AF00B09D1B /* PBXTargetDependency */, - ); - name = "build-generator-java"; - passBuildSettingsInEnvironment = 1; - productName = "generator-build-java"; - }; - 89D7CB870CDC4ED000472EA2 /* run-generator */ = { - isa = PBXLegacyTarget; - buildArgumentsString = "-verbose -emacs $ACTION"; - buildConfigurationList = 89D7CB8E0CDC4ED900472EA2 /* Build configuration list for PBXLegacyTarget "run-generator" */; - buildPhases = ( - ); - buildToolPath = /usr/bin/ant; - dependencies = ( - 2CC7556513A1323700B09D1B /* PBXTargetDependency */, - ); - name = "run-generator"; - passBuildSettingsInEnvironment = 1; - productName = "run-generator"; - }; - 89D7CC4C0CDE4C0400472EA2 /* build-generated-java */ = { - isa = PBXLegacyTarget; - buildArgumentsString = "-verbose -emacs $ACTION"; - buildConfigurationList = 89D7CC510CDE4C5200472EA2 /* Build configuration list for PBXLegacyTarget "build-generated-java" */; - buildPhases = ( - ); - buildToolPath = /usr/bin/ant; - dependencies = ( - 2CC7556913A1325700B09D1B /* PBXTargetDependency */, - ); - name = "build-generated-java"; - passBuildSettingsInEnvironment = 1; - productName = "build-generated-java"; - }; - 89D7CC600CDE75EC00472EA2 /* build-additions-java */ = { - isa = PBXLegacyTarget; - buildArgumentsString = "-verbose -emacs $ACTION"; - buildConfigurationList = 89D7CC630CDE762000472EA2 /* Build configuration list for PBXLegacyTarget "build-additions-java" */; - buildPhases = ( - ); - buildToolPath = /usr/bin/ant; - dependencies = ( - ); - name = "build-additions-java"; - passBuildSettingsInEnvironment = 1; - productName = "build-additions-java"; - }; - 89D7CC720CDE767500472EA2 /* assemble-product-java */ = { - isa = PBXLegacyTarget; - buildArgumentsString = "-verbose -emacs $ACTION"; - buildConfigurationList = 89D7CC7A0CDE76F500472EA2 /* Build configuration list for PBXLegacyTarget "assemble-product-java" */; - buildPhases = ( - ); - buildToolPath = /usr/bin/ant; - dependencies = ( - ); - name = "assemble-product-java"; - passBuildSettingsInEnvironment = 1; - productName = "package-product"; - }; - C5F3B1530E39927900B771AE /* build-test-java */ = { - isa = PBXLegacyTarget; - buildArgumentsString = "-verbose -emacs $ACTION"; - buildConfigurationList = C5F3B15B0E3992AC00B771AE /* Build configuration list for PBXLegacyTarget "build-test-java" */; - buildPhases = ( - ); - buildToolPath = /usr/bin/ant; - dependencies = ( - ); - name = "build-test-java"; - passBuildSettingsInEnvironment = 1; - productName = "build-test"; - }; - EB9FD8610AEECCF5008E157E /* build-core-java */ = { - isa = PBXLegacyTarget; - buildArgumentsString = "-verbose -emacs $ACTION"; - buildConfigurationList = EB9FD8690AEECD13008E157E /* Build configuration list for PBXLegacyTarget "build-core-java" */; - buildPhases = ( - ); - buildToolPath = /usr/bin/ant; - buildWorkingDirectory = ""; - dependencies = ( - ); - name = "build-core-java"; - passBuildSettingsInEnvironment = 1; - productName = AntJNIWrapper; - }; -/* End PBXLegacyTarget section */ - -/* Begin PBXNativeTarget section */ - 4CEBA78E08679EF10015D03E /* build-core-native */ = { - isa = PBXNativeTarget; - buildConfigurationList = 4CEBA79108679F100015D03E /* Build configuration list for PBXNativeTarget "build-core-native" */; - buildPhases = ( - 4CEBA78B08679EF10015D03E /* Headers */, - 4CEBA78C08679EF10015D03E /* Sources */, - 4CEBA78D08679EF10015D03E /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - 2CC7556113A1322100B09D1B /* PBXTargetDependency */, - ); - name = "build-core-native"; - productName = DylibN; - productType = "com.apple.product-type.library.dynamic"; - }; - 89D7CCA20CDF9A2600472EA2 /* build-additions-native */ = { - isa = PBXNativeTarget; - buildConfigurationList = 89D7CCB50CDF9A2600472EA2 /* Build configuration list for PBXNativeTarget "build-additions-native" */; - buildPhases = ( - 89D7CCA30CDF9A2600472EA2 /* Headers */, - 89D7CCA50CDF9A2600472EA2 /* Sources */, - 89D7CCB00CDF9A2600472EA2 /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - 2CC7556713A1324300B09D1B /* PBXTargetDependency */, - C5D197DB0DFB77E4006F9FB9 /* PBXTargetDependency */, - ); - name = "build-additions-native"; - productName = DylibN; - productReference = 89D7CCB80CDF9A2600472EA2 /* libJObjC.dylib */; - productType = "com.apple.product-type.library.dynamic"; - }; - C5F3B1440E39910500B771AE /* build-test-native */ = { - isa = PBXNativeTarget; - buildConfigurationList = C5F3B1480E39917500B771AE /* Build configuration list for PBXNativeTarget "build-test-native" */; - buildPhases = ( - C5F3B1410E39910500B771AE /* Headers */, - C5F3B1420E39910500B771AE /* Sources */, - C5F3B1430E39910500B771AE /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - 2CC7556313A1322800B09D1B /* PBXTargetDependency */, - ); - name = "build-test-native"; - productName = "build-tests-native"; - productReference = C5F3B1450E39910500B771AE /* libJObjC-tests.dylib */; - productType = "com.apple.product-type.library.dynamic"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 00E6828EFEC88D1A11DB9C8B /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 0410; - }; - buildConfigurationList = 4CEBA75C08679E4D0015D03E /* Build configuration list for PBXProject "JObjC" */; - compatibilityVersion = "Xcode 3.0"; - developmentRegion = English; - hasScannedForEncodings = 1; - knownRegions = ( - English, - Japanese, - French, - German, - ); - mainGroup = 00E6828FFEC88D1A11DB9C8B; - productRefGroup = 00E6828FFEC88D1A11DB9C8B; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 89EBD58C0C95F43D000F04A0 /* B&I */, - EB9FD8610AEECCF5008E157E /* build-core-java */, - 4CEBA78E08679EF10015D03E /* build-core-native */, - 89D7CA160CDBA94D00472EA2 /* build-generator-java */, - 89D7CB870CDC4ED000472EA2 /* run-generator */, - 89D7CC4C0CDE4C0400472EA2 /* build-generated-java */, - 89D7CC600CDE75EC00472EA2 /* build-additions-java */, - 89D7CCA20CDF9A2600472EA2 /* build-additions-native */, - 89D7CC720CDE767500472EA2 /* assemble-product-java */, - C5F3B1530E39927900B771AE /* build-test-java */, - C5F3B1440E39910500B771AE /* build-test-native */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXSourcesBuildPhase section */ - 4CEBA78C08679EF10015D03E /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - C5E4547B0E36729F0046D3E8 /* Invoke.m in Sources */, - C5742F6D0E316EFA00093838 /* Subclassing.m in Sources */, - 89D7C9F70CDB900E00472EA2 /* CIF.m in Sources */, - 89D7C9F80CDB900E00472EA2 /* Coder.m in Sources */, - 89D7C9F90CDB900E00472EA2 /* Function.m in Sources */, - 89D7C9FA0CDB900E00472EA2 /* ID.m in Sources */, - 89D7C9FB0CDB900E00472EA2 /* JObjCRuntime.m in Sources */, - 89D7C9FC0CDB900E00472EA2 /* MacOSXFramework.m in Sources */, - 89D7C9FE0CDB900E00472EA2 /* NativeBuffer.m in Sources */, - 89D7C9FF0CDB900E00472EA2 /* NativeObjectLifecycleManager.m in Sources */, - 89D7CA000CDB900E00472EA2 /* NSClass.m in Sources */, - 89D7CA010CDB900E00472EA2 /* SEL.m in Sources */, - C5D196C90DF9E43C006F9FB9 /* FFIType.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 89D7CCA50CDF9A2600472EA2 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - C5E4547D0E367DAB0046D3E8 /* Invoke.m in Sources */, - C5742F700E316F8600093838 /* Subclassing.m in Sources */, - 89D7CCA60CDF9A2600472EA2 /* CIF.m in Sources */, - 89D7CCA70CDF9A2600472EA2 /* Coder.m in Sources */, - 89D7CCA80CDF9A2600472EA2 /* Function.m in Sources */, - 89D7CCA90CDF9A2600472EA2 /* ID.m in Sources */, - 89D7CCAA0CDF9A2600472EA2 /* JObjCRuntime.m in Sources */, - 89D7CCAB0CDF9A2600472EA2 /* MacOSXFramework.m in Sources */, - 89D7CCAC0CDF9A2600472EA2 /* NativeBuffer.m in Sources */, - 89D7CCAD0CDF9A2600472EA2 /* NativeObjectLifecycleManager.m in Sources */, - 89D7CCAE0CDF9A2600472EA2 /* NSClass.m in Sources */, - 89D7CCAF0CDF9A2600472EA2 /* SEL.m in Sources */, - 89D7CCBB0CDF9AA200472EA2 /* NativeString.m in Sources */, - 89D7CCBD0CDF9AB100472EA2 /* NativeNumber.m in Sources */, - 89D7CCBF0CDF9AC600472EA2 /* NativeThread.m in Sources */, - C5D197D90DFB77C6006F9FB9 /* FFIType.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - C5F3B1420E39910500B771AE /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - C5F3B23D0E39948300B771AE /* FunCallBench.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 2CC7556113A1322100B09D1B /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = EB9FD8610AEECCF5008E157E /* build-core-java */; - targetProxy = 2CC7556013A1322100B09D1B /* PBXContainerItemProxy */; - }; - 2CC7556313A1322800B09D1B /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = C5F3B1530E39927900B771AE /* build-test-java */; - targetProxy = 2CC7556213A1322800B09D1B /* PBXContainerItemProxy */; - }; - 2CC7556513A1323700B09D1B /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 89D7CA160CDBA94D00472EA2 /* build-generator-java */; - targetProxy = 2CC7556413A1323700B09D1B /* PBXContainerItemProxy */; - }; - 2CC7556713A1324300B09D1B /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 89D7CC600CDE75EC00472EA2 /* build-additions-java */; - targetProxy = 2CC7556613A1324300B09D1B /* PBXContainerItemProxy */; - }; - 2CC7556913A1325700B09D1B /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 89D7CB870CDC4ED000472EA2 /* run-generator */; - targetProxy = 2CC7556813A1325700B09D1B /* PBXContainerItemProxy */; - }; - 2CC7556B13A132AF00B09D1B /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 4CEBA78E08679EF10015D03E /* build-core-native */; - targetProxy = 2CC7556A13A132AF00B09D1B /* PBXContainerItemProxy */; - }; - 2CC7556D13A132B200B09D1B /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = EB9FD8610AEECCF5008E157E /* build-core-java */; - targetProxy = 2CC7556C13A132B200B09D1B /* PBXContainerItemProxy */; - }; - 89D7CB9C0CDC64F800472EA2 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 89D7CB870CDC4ED000472EA2 /* run-generator */; - targetProxy = 89D7CB9B0CDC64F800472EA2 /* PBXContainerItemProxy */; - }; - 89D7CC920CDE7A8200472EA2 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 89D7CC720CDE767500472EA2 /* assemble-product-java */; - targetProxy = 89D7CC910CDE7A8200472EA2 /* PBXContainerItemProxy */; - }; - C592D6590E12F27400D076FF /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = EB9FD8610AEECCF5008E157E /* build-core-java */; - targetProxy = C592D6580E12F27400D076FF /* PBXContainerItemProxy */; - }; - C592D65B0E12F27600D076FF /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 4CEBA78E08679EF10015D03E /* build-core-native */; - targetProxy = C592D65A0E12F27600D076FF /* PBXContainerItemProxy */; - }; - C592D65D0E12F27E00D076FF /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 89D7CA160CDBA94D00472EA2 /* build-generator-java */; - targetProxy = C592D65C0E12F27E00D076FF /* PBXContainerItemProxy */; - }; - C592D65F0E12F28500D076FF /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 89D7CC4C0CDE4C0400472EA2 /* build-generated-java */; - targetProxy = C592D65E0E12F28500D076FF /* PBXContainerItemProxy */; - }; - C592D6610E12F28E00D076FF /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 89D7CC600CDE75EC00472EA2 /* build-additions-java */; - targetProxy = C592D6600E12F28E00D076FF /* PBXContainerItemProxy */; - }; - C592D6630E12F29200D076FF /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 89D7CCA20CDF9A2600472EA2 /* build-additions-native */; - targetProxy = C592D6620E12F29200D076FF /* PBXContainerItemProxy */; - }; - C5D197DB0DFB77E4006F9FB9 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 4CEBA78E08679EF10015D03E /* build-core-native */; - targetProxy = C5D197DA0DFB77E4006F9FB9 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin XCBuildConfiguration section */ - 4CEBA75D08679E4D0015D03E /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = ( - "$(NATIVE_ARCH_32_BIT)", - "$(NATIVE_ARCH_64_BIT)", - ); - GCC_ENABLE_OBJC_GC = supported; - SYMROOT = build; - }; - name = Debug; - }; - 4CEBA75E08679E4D0015D03E /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - GCC_ENABLE_OBJC_GC = supported; - INSTALL_PATH = /System/Library/Java/Extensions; - }; - name = Release; - }; - 4CEBA79208679F100015D03E /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = ( - "$(NATIVE_ARCH_32_BIT)", - "$(NATIVE_ARCH_64_BIT)", - ); - COPY_PHASE_STRIP = NO; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - EXECUTABLE_EXTENSION = dylib; - EXECUTABLE_PREFIX = lib; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_2)", - ); - FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/A/Frameworks\""; - FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_2 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/A/Frameworks\""; - GCC_GENERATE_DEBUGGING_SYMBOLS = YES; - GCC_MODEL_TUNING = G5; - GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES; - GCC_TREAT_NONCONFORMANT_CODE_ERRORS_AS_WARNINGS = YES; - GCC_TREAT_WARNINGS_AS_ERRORS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_MISSING_NEWLINE = YES; - GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_CHECK_SWITCH_STATEMENTS = YES; - GCC_WARN_EFFECTIVE_CPLUSPLUS_VIOLATIONS = YES; - GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES; - GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; - GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES; - GCC_WARN_MISSING_PARENTHESES = YES; - GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES; - GCC_WARN_PEDANTIC = NO; - GCC_WARN_PROTOTYPE_CONVERSION = NO; - GCC_WARN_SHADOW = YES; - GCC_WARN_SIGN_COMPARE = YES; - GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNKNOWN_PRAGMAS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - HEADER_SEARCH_PATHS = ( - "$(HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_1)", - /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers, - ); - HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/src/jni_headers/core\" \"$(OBJROOT)/src/jni_headers/core\""; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(LIBRARY_SEARCH_PATHS_QUOTED_1)", - ); - LIBRARY_SEARCH_PATHS_QUOTED_1 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/1.5.0/Libraries\""; - LIBRARY_STYLE = DYNAMIC; - MACH_O_TYPE = mh_dylib; - OTHER_LDFLAGS = ""; - OTHER_REZFLAGS = ""; - PRODUCT_NAME = JObjC; - SECTORDER_FLAGS = ""; - VALID_ARCHS = "ppc7400 ppc970 i386 x86_64 ppc"; - WARNING_CFLAGS = ( - "-Wmost", - "-Wno-four-char-constants", - "-Wno-unknown-pragmas", - "-Wformat", - "-Wformat-security", - "-Wcast-align", - "-Wwrite-strings", - "-Wuninitialized", - "-Wshadow", - "-Wshorten-64-to-32", - "-Wsign-compare", - "-Wpointer-arith", - "-Wall", - ); - ZERO_LINK = NO; - }; - name = Debug; - }; - 4CEBA79308679F100015D03E /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = ( - i386, - ppc, - x86_64, - ); - COPY_PHASE_STRIP = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - EXECUTABLE_EXTENSION = dylib; - EXECUTABLE_PREFIX = lib; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_2)", - ); - FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/A/Frameworks\""; - FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_2 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/A/Frameworks\""; - GCC_GENERATE_DEBUGGING_SYMBOLS = NO; - GCC_MODEL_TUNING = G5; - GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES; - GCC_TREAT_NONCONFORMANT_CODE_ERRORS_AS_WARNINGS = YES; - GCC_TREAT_WARNINGS_AS_ERRORS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_MISSING_NEWLINE = YES; - GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_CHECK_SWITCH_STATEMENTS = YES; - GCC_WARN_EFFECTIVE_CPLUSPLUS_VIOLATIONS = YES; - GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES; - GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; - GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES; - GCC_WARN_MISSING_PARENTHESES = YES; - GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES; - GCC_WARN_PEDANTIC = NO; - GCC_WARN_PROTOTYPE_CONVERSION = NO; - GCC_WARN_SHADOW = YES; - GCC_WARN_SIGN_COMPARE = YES; - GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNKNOWN_PRAGMAS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - HEADER_SEARCH_PATHS = ( - "$(HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_1)", - /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers, - ); - HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/src/jni_headers/core\" \"$(OBJROOT)/src/jni_headers/core\""; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(LIBRARY_SEARCH_PATHS_QUOTED_FOR_TARGET_1)", - ); - LIBRARY_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/1.5.0/Libraries\""; - LIBRARY_STYLE = DYNAMIC; - MACH_O_TYPE = mh_dylib; - OTHER_LDFLAGS = ""; - OTHER_REZFLAGS = ""; - PRODUCT_NAME = JObjC; - SECTORDER_FLAGS = ""; - VALID_ARCHS = "ppc7400 ppc970 i386 x86_64 ppc"; - WARNING_CFLAGS = ( - "-Wmost", - "-Wno-four-char-constants", - "-Wno-unknown-pragmas", - "-Wformat", - "-Wformat-security", - "-Wcast-align", - "-Wwrite-strings", - "-Wuninitialized", - "-Wshadow", - "-Wshorten-64-to-32", - "-Wsign-compare", - "-Wpointer-arith", - "-Wall", - ); - ZERO_LINK = NO; - }; - name = Release; - }; - 89D7CA170CDBA94D00472EA2 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - PRODUCT_NAME = "build-generator"; - }; - name = Debug; - }; - 89D7CA180CDBA94D00472EA2 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - PRODUCT_NAME = "build-generator"; - ZERO_LINK = NO; - }; - name = Release; - }; - 89D7CB880CDC4ED000472EA2 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = "\U00010"; - PRODUCT_NAME = "run-generator"; - }; - name = Debug; - }; - 89D7CB890CDC4ED000472EA2 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - PRODUCT_NAME = "run-generator"; - ZERO_LINK = NO; - }; - name = Release; - }; - 89D7CC4D0CDE4C0400472EA2 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - PRODUCT_NAME = "build-generated"; - }; - name = Debug; - }; - 89D7CC4E0CDE4C0400472EA2 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - PRODUCT_NAME = "build-generated"; - ZERO_LINK = NO; - }; - name = Release; - }; - 89D7CC610CDE75EC00472EA2 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - PRODUCT_NAME = "build-additions"; - }; - name = Debug; - }; - 89D7CC620CDE75EC00472EA2 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - PRODUCT_NAME = "build-additions"; - ZERO_LINK = NO; - }; - name = Release; - }; - 89D7CC730CDE767500472EA2 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - PRODUCT_NAME = "assemble-product"; - }; - name = Debug; - }; - 89D7CC740CDE767500472EA2 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - PRODUCT_NAME = "assemble-product"; - ZERO_LINK = NO; - }; - name = Release; - }; - 89D7CCB60CDF9A2600472EA2 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = ( - "$(NATIVE_ARCH_32_BIT)", - "$(NATIVE_ARCH_64_BIT)", - ); - COPY_PHASE_STRIP = NO; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - EXECUTABLE_EXTENSION = dylib; - EXECUTABLE_PREFIX = lib; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_2)", - ); - FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/A/Frameworks\""; - FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_2 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/A/Frameworks\""; - GCC_GENERATE_DEBUGGING_SYMBOLS = YES; - GCC_MODEL_TUNING = G5; - GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES; - GCC_TREAT_NONCONFORMANT_CODE_ERRORS_AS_WARNINGS = YES; - GCC_TREAT_WARNINGS_AS_ERRORS = NO; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_MISSING_NEWLINE = YES; - GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_CHECK_SWITCH_STATEMENTS = YES; - GCC_WARN_EFFECTIVE_CPLUSPLUS_VIOLATIONS = YES; - GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES; - GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; - GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES; - GCC_WARN_MISSING_PARENTHESES = YES; - GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES; - GCC_WARN_PEDANTIC = NO; - GCC_WARN_PROTOTYPE_CONVERSION = NO; - GCC_WARN_SHADOW = YES; - GCC_WARN_SIGN_COMPARE = YES; - GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNKNOWN_PRAGMAS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - HEADER_SEARCH_PATHS = ( - "$(HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_1)", - "$(HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_2)", - /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers, - ); - HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/src/jni_headers/core\" \"$(OBJROOT)/src/jni_headers/core\""; - HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_2 = "\"$(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/src/jni_headers/additions\" \"$(OBJROOT)/src/jni_headers/additions\""; - INSTALL_PATH = /usr/local/lib; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(LIBRARY_SEARCH_PATHS_QUOTED_1)", - ); - LIBRARY_SEARCH_PATHS_QUOTED_1 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/1.5.0/Libraries\""; - LIBRARY_STYLE = DYNAMIC; - MACH_O_TYPE = mh_dylib; - OTHER_LDFLAGS = ""; - OTHER_REZFLAGS = ""; - PRODUCT_NAME = JObjC; - SECTORDER_FLAGS = ""; - VALID_ARCHS = "ppc7400 ppc970 i386 x86_64 ppc"; - WARNING_CFLAGS = ( - "-Wmost", - "-Wno-four-char-constants", - "-Wno-unknown-pragmas", - "-Wformat", - "-Wformat-security", - "-Wcast-align", - "-Wwrite-strings", - "-Wuninitialized", - "-Wshadow", - "-Wshorten-64-to-32", - "-Wsign-compare", - "-Wpointer-arith", - "-Wall", - ); - ZERO_LINK = NO; - }; - name = Debug; - }; - 89D7CCB70CDF9A2600472EA2 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = ( - x86_64, - ppc, - i386, - ); - COPY_PHASE_STRIP = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - EXECUTABLE_EXTENSION = dylib; - EXECUTABLE_PREFIX = lib; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_2)", - ); - FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/A/Frameworks\""; - FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_2 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/A/Frameworks\""; - GCC_GENERATE_DEBUGGING_SYMBOLS = NO; - GCC_MODEL_TUNING = G5; - GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES; - GCC_TREAT_NONCONFORMANT_CODE_ERRORS_AS_WARNINGS = YES; - GCC_TREAT_WARNINGS_AS_ERRORS = NO; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_MISSING_NEWLINE = YES; - GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_CHECK_SWITCH_STATEMENTS = YES; - GCC_WARN_EFFECTIVE_CPLUSPLUS_VIOLATIONS = YES; - GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES; - GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; - GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES; - GCC_WARN_MISSING_PARENTHESES = YES; - GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES; - GCC_WARN_PEDANTIC = NO; - GCC_WARN_PROTOTYPE_CONVERSION = NO; - GCC_WARN_SHADOW = YES; - GCC_WARN_SIGN_COMPARE = YES; - GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNKNOWN_PRAGMAS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - HEADER_SEARCH_PATHS = ( - "$(HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_1)", - "$(HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_2)", - /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers, - ); - HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/src/jni_headers/core\" \"$(OBJROOT)/src/jni_headers/core\""; - HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_2 = "\"$(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/src/jni_headers/additions\" \"$(OBJROOT)/src/jni_headers/additions\""; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(LIBRARY_SEARCH_PATHS_QUOTED_FOR_TARGET_1)", - ); - LIBRARY_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/1.5.0/Libraries\""; - LIBRARY_STYLE = DYNAMIC; - MACH_O_TYPE = mh_dylib; - OTHER_LDFLAGS = ""; - OTHER_REZFLAGS = ""; - PRODUCT_NAME = JObjC; - SECTORDER_FLAGS = ""; - VALID_ARCHS = "ppc7400 ppc970 i386 x86_64 ppc"; - WARNING_CFLAGS = ( - "-Wmost", - "-Wno-four-char-constants", - "-Wno-unknown-pragmas", - "-Wformat", - "-Wformat-security", - "-Wcast-align", - "-Wwrite-strings", - "-Wuninitialized", - "-Wshadow", - "-Wshorten-64-to-32", - "-Wsign-compare", - "-Wpointer-arith", - "-Wall", - ); - ZERO_LINK = NO; - }; - name = Release; - }; - 89EBD58D0C95F43D000F04A0 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - PRODUCT_NAME = "B&I"; - }; - name = Debug; - }; - 89EBD58E0C95F43D000F04A0 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - PRODUCT_NAME = "B&I"; - ZERO_LINK = NO; - }; - name = Release; - }; - C5F3B1460E39910500B771AE /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = YES; - ARCHS = ( - x86_64, - i386, - ppc, - ); - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - EXECUTABLE_EXTENSION = dylib; - EXECUTABLE_PREFIX = lib; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_2)", - ); - FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/A/Frameworks\""; - FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_2 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/A/Frameworks\""; - GCC_DYNAMIC_NO_PIC = NO; - GCC_MODEL_TUNING = G5; - GCC_OPTIMIZATION_LEVEL = 0; - HEADER_SEARCH_PATHS = ( - "$(HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_1)", - "$(HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_2)", - /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers, - "\"$(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/src/jni_headers/core\"", - "\"$(OBJROOT)/src/jni_headers/core\"", - "\"$(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/src/jni_headers/additions\"", - "\"$(OBJROOT)/src/jni_headers/additions\"", - "\"$(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/src/jni_headers/test\"", - "\"$(OBJROOT)/src/jni_headers/test\"", - ); - INSTALL_PATH = /usr/local/lib; - LIBRARY_STYLE = DYNAMIC; - MACH_O_TYPE = mh_dylib; - PRODUCT_NAME = "JObjC-tests"; - SKIP_INSTALL = YES; - }; - name = Debug; - }; - C5F3B1470E39910500B771AE /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = YES; - ARCHS = ( - x86_64, - i386, - ppc, - ); - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = dwarf; - EXECUTABLE_EXTENSION = dylib; - EXECUTABLE_PREFIX = lib; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_2)", - ); - FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/A/Frameworks\""; - FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_2 = "\"$(SYSTEM_LIBRARY_DIR)/Frameworks/JavaVM.framework/Versions/A/Frameworks\""; - GCC_MODEL_TUNING = G5; - HEADER_SEARCH_PATHS = ( - "$(HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_1)", - "$(HEADER_SEARCH_PATHS_QUOTED_FOR_TARGET_2)", - /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers, - "\"$(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/src/jni_headers/core\"", - "\"$(OBJROOT)/src/jni_headers/core\"", - "\"$(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/src/jni_headers/additions\"", - "\"$(OBJROOT)/src/jni_headers/additions\"", - "\"$(PROJECT_TEMP_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/src/jni_headers/test\"", - "\"$(OBJROOT)/src/jni_headers/test\"", - ); - INSTALL_PATH = /usr/local/lib; - LIBRARY_STYLE = DYNAMIC; - MACH_O_TYPE = mh_dylib; - PRODUCT_NAME = "JObjC-tests"; - SKIP_INSTALL = YES; - ZERO_LINK = NO; - }; - name = Release; - }; - C5F3B1540E39927A00B771AE /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - PRODUCT_NAME = "build-test"; - }; - name = Debug; - }; - C5F3B1550E39927A00B771AE /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - PRODUCT_NAME = "build-test"; - ZERO_LINK = NO; - }; - name = Release; - }; - EB9FD86A0AEECD13008E157E /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_GENERATE_DEBUGGING_SYMBOLS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - PRODUCT_NAME = "build-core"; - }; - name = Debug; - }; - EB9FD86B0AEECD13008E157E /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - COPY_PHASE_STRIP = YES; - GCC_GENERATE_DEBUGGING_SYMBOLS = NO; - PRODUCT_NAME = "build-core"; - ZERO_LINK = NO; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 4CEBA75C08679E4D0015D03E /* Build configuration list for PBXProject "JObjC" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 4CEBA75D08679E4D0015D03E /* Debug */, - 4CEBA75E08679E4D0015D03E /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4CEBA79108679F100015D03E /* Build configuration list for PBXNativeTarget "build-core-native" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 4CEBA79208679F100015D03E /* Debug */, - 4CEBA79308679F100015D03E /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 89D7CA1C0CDBA9B000472EA2 /* Build configuration list for PBXLegacyTarget "build-generator-java" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 89D7CA170CDBA94D00472EA2 /* Debug */, - 89D7CA180CDBA94D00472EA2 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 89D7CB8E0CDC4ED900472EA2 /* Build configuration list for PBXLegacyTarget "run-generator" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 89D7CB880CDC4ED000472EA2 /* Debug */, - 89D7CB890CDC4ED000472EA2 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 89D7CC510CDE4C5200472EA2 /* Build configuration list for PBXLegacyTarget "build-generated-java" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 89D7CC4D0CDE4C0400472EA2 /* Debug */, - 89D7CC4E0CDE4C0400472EA2 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 89D7CC630CDE762000472EA2 /* Build configuration list for PBXLegacyTarget "build-additions-java" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 89D7CC610CDE75EC00472EA2 /* Debug */, - 89D7CC620CDE75EC00472EA2 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 89D7CC7A0CDE76F500472EA2 /* Build configuration list for PBXLegacyTarget "assemble-product-java" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 89D7CC730CDE767500472EA2 /* Debug */, - 89D7CC740CDE767500472EA2 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 89D7CCB50CDF9A2600472EA2 /* Build configuration list for PBXNativeTarget "build-additions-native" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 89D7CCB60CDF9A2600472EA2 /* Debug */, - 89D7CCB70CDF9A2600472EA2 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 89EBD5930C95F44E000F04A0 /* Build configuration list for PBXAggregateTarget "B&I" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 89EBD58D0C95F43D000F04A0 /* Debug */, - 89EBD58E0C95F43D000F04A0 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - C5F3B1480E39917500B771AE /* Build configuration list for PBXNativeTarget "build-test-native" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - C5F3B1460E39910500B771AE /* Debug */, - C5F3B1470E39910500B771AE /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - C5F3B15B0E3992AC00B771AE /* Build configuration list for PBXLegacyTarget "build-test-java" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - C5F3B1540E39927A00B771AE /* Debug */, - C5F3B1550E39927A00B771AE /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - EB9FD8690AEECD13008E157E /* Build configuration list for PBXLegacyTarget "build-core-java" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - EB9FD86A0AEECD13008E157E /* Debug */, - EB9FD86B0AEECD13008E157E /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 00E6828EFEC88D1A11DB9C8B /* Project object */; -} diff --git a/jdk/src/macosx/native/jobjc/README.txt b/jdk/src/macosx/native/jobjc/README.txt deleted file mode 100644 index 3bde08a77c4..00000000000 --- a/jdk/src/macosx/native/jobjc/README.txt +++ /dev/null @@ -1,132 +0,0 @@ -#title JObjC -# -# 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 -# 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. -# - -JObjC core provides a pure Java interface for calling C functions and -sending ObjC messages. Given some information, it can marshal types -automatically. - -It also parses BridgeSupport to generate Java wrappers around -Framework bundles. These wrappers rely on the core to provide access -to the C constants, enums, structs, functions, ObjC classes, etc of a -framework. - -* How to build it - -Your best option is `ant all`. There's an Xcode "B&I" target that -works for buildit. - -You'll need a recent JavaNativeFoundation, and perhaps some other -things. Everything is usually there on SnowLeopard (or Leopard after -the common ~javabuild/bin/update runs). - -The build process is quite involved. Xcode takes care of the native -parts, ant takes care of the Java parts, and there's an unholy mix of -external targets and hidden dependencies that keep Xcode and ant (and -buildit on top of that) from stepping on each other. So a warning: the -ant and Xcode targets don't have proper dependencies set up because of -this. They have some dependencies configured, but not the entire -chain. This is because of the jumping back and forth between -externals. If you run the aggregate targets (Xcode B&I, ant all, ant -test, ant bench), everything's is good. But if you manually invoke -individual targets, chances are you'll miss something. Let's go over -it all step by step: - -** ant gen-pcoder - -The PrimitiveCoder subclasses have a lot of boiler plate which -simplifies the generated MixedPrimitiveCoder classes. So instead of -maintaining it, I maintain a tiny Haskell script that spits out the -Java code. This ant target runs that script if Haskell is available on -the system. If it isn't available, this will silently fail. That's -okay, because chances are the PrimitiveCoder.java that you got from -svn is current and does not need to be updated. - -** ant build-core / Xcode build-core-java - -Build core simply builds the JObjC core java classes, and also -generates headers for the JNI for Xcode. - -** ant build-core-native / Xcode build-core-native - -Xcode builds the native core, using the headers from the Java core. It -generates libJObjC.dylib. - -** ant build-generator / Xcode build-generator-java - -ant builds the generator. - -** ant run-generator / Xcode run-generator - -ant runs the generator, using the core Java and native classes. - -What is rungen? And what's run-generator-old? run-generator-old is the -preferred way to run the generator from ant, but there's a strange bug -when running from buildit that causes run-generator-old to -freeze. Pratik was helping me debug it, inspecting the stack and -snooping dtrace probes, but we never found the reason for the -block. So I figured that maybe if I just add a layer of indirection -maybe it'll work around that. And it did. Sad but true. - -** ant build-generated / Xcode build-generated-java - -Build the generator output. - -** ant build-additions / Xcode build-additions-java - -Builds java additions. - -** ant build-additions-native / Xcode build-additions-native - -This builds a new version of libJObjC.dylib. It will rebuild -everything from the core, and include everything from additions. - -** ant assemble-product / Xcode assemble-product-java - -Create a jar, copy products to destination, etc. - -* How to test it - -The test cases also contain a Java component and a native component, -and are built similarly to the above. The benchmarks are built -together with the tests. So "ant build-test" and "ant -build-test-native" will build both the benchmarks and the test. "ant -test" will run the test. "ant bench" will run benchmarks. If you only -want to run a specific benchmark, you can pass a regexp in the -environment variable BENCH_MATCH. - - -ant test -ant bench -BENCH_MATCH=Foo ant bench - - -Test and bench reports will end up in -build/JObjC.build/Debug/test-reports/ - -* How to use it - -Include the jar in your classpath and set your java.library.path to -the directory that contains the dylib. Same thing for app bundles. diff --git a/jdk/src/macosx/native/jobjc/bridgesupport.gmk b/jdk/src/macosx/native/jobjc/bridgesupport.gmk deleted file mode 100644 index 1de9bd1d5c5..00000000000 --- a/jdk/src/macosx/native/jobjc/bridgesupport.gmk +++ /dev/null @@ -1,54 +0,0 @@ -# -# 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 -# 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. -# - -# makefile for generating a stable set of bridgesupport files that change timestamp -# only when the bridgesupport data actually changes - -FRAMEWORKS_DIR = /System/Library/Frameworks -GBM = /usr/bin/gen_bridge_metadata -GEN_HEADERS = $(addsuffix .headers,$(FRAMEWORKS)) -GEN_BRIDGESUPPORT = $(addsuffix .bridgesupport,$(FRAMEWORKS)) - -%.bridgesupport : %.headers $(FRAMEWORKS_DIR)/%.framework/Headers/*.h - @echo "generating bridge support for" $< - if [ -f $(FRAMEWORKS_DIR)/$(<:.headers=.framework)/Resources/BridgeSupport/$(<:.headers=Full.bridgesupport) ] ; \ - then cp $(FRAMEWORKS_DIR)/$(<:.headers=.framework)/Resources/BridgeSupport/$(<:.headers=Full.bridgesupport) $@ ; \ - else $(GBM) -F complete --framework $(<:.headers=.framework) -o $@ ; \ - fi - if cmp -s $@ $(STABLE_GEN_DIR)/$(@:.bridgesupport=Full.bridgesupport) ; \ - then : ; \ - else cp $@ $(STABLE_GEN_DIR)/$(@:.bridgesupport=Full.bridgesupport) ; \ - fi - -%.headers : $(FRAMEWORKS_DIR)/%.framework/Headers - @echo linking $< - ln -s $< $@ - -$(STABLE_GEN_DIR): - mkdir -p $(STABLE_GEN_DIR) - -$(GEN_BRIDGESUPPORT): $(GEN_HEADERS) $(STABLE_GEN_DIR) - -all: $(GEN_BRIDGESUPPORT) diff --git a/jdk/src/macosx/native/jobjc/build.xml b/jdk/src/macosx/native/jobjc/build.xml deleted file mode 100644 index 9f638840fcf..00000000000 --- a/jdk/src/macosx/native/jobjc/build.xml +++ /dev/null @@ -1,520 +0,0 @@ - - - - - - - - Nothing to do for install-headers build phase - - - - Nothing to do for install-source build phase - - - - - - - This Ant build file depends on the native Xcode project to invoke - targets by defining $PRODUCT_NAME to specify the target. - - - --- Redirecting to target "${env.PRODUCT_NAME}" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/jdk/src/macosx/native/jobjc/extract_classes.pl b/jdk/src/macosx/native/jobjc/extract_classes.pl deleted file mode 100644 index b0950db4699..00000000000 --- a/jdk/src/macosx/native/jobjc/extract_classes.pl +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/perl -# -# 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 -# 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. -## - -$file_dir = $ARGV[0]; -@file_list = qx("/usr/bin/find" "$file_dir"); - -foreach $file (@file_list) { - if ($file =~ s/\.class//) { - if ($file !~ s/\$[0-9]//) { - $file =~ s/$file_dir\///g; - $file =~ s/\//\./g; - chomp($file); - print "$file,"; - } - } -} diff --git a/jdk/src/macosx/native/jobjc/run-and-write-if-okay b/jdk/src/macosx/native/jobjc/run-and-write-if-okay deleted file mode 100644 index 8d0bb690276..00000000000 --- a/jdk/src/macosx/native/jobjc/run-and-write-if-okay +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env ruby -# -# 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 -# 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. -# -# - -if ARGV.length < 2 - puts <&1`. If it returns successfully, it writes the output to OUTPATH. -This script will return successfully unless writing the output fails. -EOF - exit -end - -EXECPATH = ARGV[0] -OUTPATH = ARGV[1] - -output = `#{EXECPATH}` -puts output - -if $?.to_i == 0 - puts "Writing output of #{EXECPATH} to #{OUTPATH}" - File.open(OUTPATH, 'w') {|f| f.write(output) } -else - puts "#{EXECPATH} failed to run trial. Ignoring." -end diff --git a/jdk/src/macosx/native/jobjc/rungen b/jdk/src/macosx/native/jobjc/rungen deleted file mode 100644 index 17aeabea15d..00000000000 --- a/jdk/src/macosx/native/jobjc/rungen +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env ruby -# -# 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 -# 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. -# -# - -xcodeAction = ARGV[0] - -exit unless xcodeAction == "install" - -JOBJC_JAR = ARGV[1] -LIBPATH = ARGV[2] -OBJROOT = ARGV[3] -ARCHS = ARGV[4] -STABLE_GEN_DIR = ARGV[5] - -ourJavaHome = ENV['JAVA_HOME'] -ourJavaVersion = `java -fullversion 2>&1` -$stderr.puts "ENV['JAVA_HOME'] = #{ourJavaHome}" -$stderr.puts "java -fullversion = #{ourJavaVersion}" - -$stderr.puts "jobjc_jar = #{JOBJC_JAR}" -$stderr.puts "libpath = #{LIBPATH}" -$stderr.puts "objroot = #{OBJROOT}" -$stderr.puts "ARCHS = #{ARCHS}" -$stderr.puts "STABLE_GEN_DIR = #{STABLE_GEN_DIR}" - -jarch = if ARCHS =~ /x86_64/ then "-d64" else "-d32" end - -# compute the boot class path, but remove the JObjC jar file that may have been installed in the boot jdk - -bootclasspathcmd = "java -classpath #{OBJROOT}/bin/core:#{OBJROOT}/bin/generator com.apple.internal.jobjc.generator.BootClassPathMinus #{JOBJC_JAR}" -$stderr.puts bootclasspathcmd -bootclasspath = `#{bootclasspathcmd}` - -$stderr.puts "bootclasspath is: " -$stderr.puts bootclasspath - -# we run the generator with our newly created JObjC. The installed version (if available) has been removed from -# the boot class path, so we are building with everything newly created. -cmd = "java #{jarch} -Xms128m -Xmx512m -Djava.library.path=#{LIBPATH} -Xbootclasspath:#{bootclasspath.chomp} -classpath #{OBJROOT}/bin/core:#{OBJROOT}/bin/generator -ea com.apple.internal.jobjc.generator.Generator dst=#{OBJROOT}/src/jobjc frameworks=#{STABLE_GEN_DIR}" - -$stderr.puts cmd -puts `#{cmd} 2>&1` - -raise $?.to_i if $?.to_i != 0 diff --git a/jdk/src/macosx/native/jobjc/runjava b/jdk/src/macosx/native/jobjc/runjava deleted file mode 100644 index a6e91547e7d..00000000000 --- a/jdk/src/macosx/native/jobjc/runjava +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash -# -# 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 -# 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. -# -# -java -ea -classpath "lib/junit-4.4.jar:build/JObjC.build/Debug/bin/core:build/JObjC.build/Debug/bin/generator:build/JObjC.build/Debug/bin/additions:build/JObjC.build/Debug/bin/test:build/JObjC.build/Debug/bin/generated" -Djava.library.path=build/Debug $@ diff --git a/jdk/src/macosx/native/jobjc/src/core/PrimitiveCoder.hs b/jdk/src/macosx/native/jobjc/src/core/PrimitiveCoder.hs deleted file mode 100644 index b9b0070fcb4..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/PrimitiveCoder.hs +++ /dev/null @@ -1,275 +0,0 @@ -#!/usr/bin/env runhaskell - -{- -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ --} -{- -The simplest way to get Haskell is through MacPorts: sudo port install ghc - -Otherwise, see http://www.haskell.org/ghc/ --} - -import Data.List -import Data.Maybe -import Data.Char - -data Width = W32 | W64 - deriving (Show, Eq, Bounded, Enum) - -data NType = NBOOL | Nschar | Nuchar | Nsshort | Nushort | Nsint | Nuint - | Nslong | Nulong | Nslonglong | Nulonglong | Nfloat | Ndouble - deriving (Show, Eq, Bounded, Enum) - -data JPrim = Jboolean | Jbyte | Jchar | Jshort | Jint | Jlong | Jfloat | Jdouble - deriving (Show, Eq, Bounded, Enum) - -data JClass = JBoolean | JByte | JCharacter | JShort | JInteger | JLong - | JFloat | JDouble - deriving (Show, Eq, Bounded, Enum) - -data FFIType = SINT8 | UINT8 | SINT16 | UINT16 | SINT32 | UINT32 - | SINT64 | UINT64 | FLOAT | DOUBLE - deriving (Show, Eq, Bounded, Enum) - -widths = [minBound..maxBound] :: [Width] -ntypes = [minBound..maxBound] :: [NType] -jprims = [minBound..maxBound] :: [JPrim] -jclasses = [minBound..maxBound] :: [JClass] -ffitypes = [minBound..maxBound] :: [FFIType] - --- What's the FFIType for a given Width and NType? For example: W32 NBOOL -> SINT8 -ffitype :: Width -> NType -> FFIType -ffitype _ NBOOL = SINT8 -ffitype _ Nschar = SINT8 -ffitype _ Nuchar = UINT8 -ffitype _ Nsshort = SINT16 -ffitype _ Nushort = UINT16 -ffitype _ Nsint = SINT32 -ffitype _ Nuint = UINT32 -ffitype W32 Nslong = SINT32 -ffitype W64 Nslong = SINT64 -ffitype W32 Nulong = UINT32 -ffitype W64 Nulong = UINT64 -ffitype _ Nslonglong = SINT64 -ffitype _ Nulonglong = UINT64 -ffitype _ Nfloat = FLOAT -ffitype _ Ndouble = DOUBLE - -sizeof :: FFIType -> Int -sizeof SINT8 = 1 -sizeof UINT8 = 1 -sizeof SINT16 = 2 -sizeof UINT16 = 2 -sizeof SINT32 = 4 -sizeof UINT32 = 4 -sizeof SINT64 = 8 -sizeof UINT64 = 8 -sizeof FLOAT = 4 -sizeof DOUBLE = 8 - --- What's the Obj-C encoding for a given NType? For example: unsigned char -> 'C' -encoding nt = fromJust $ lookup nt $ - [(NBOOL, 'B'), (Nschar, 'c'), (Nuchar, 'C'), (Nsshort, 's'), - (Nushort, 'S'), (Nsint, 'i'), (Nuint, 'I'), (Nslong, 'l'), - (Nulong, 'L'), (Nslonglong, 'q'), (Nulonglong, 'Q'), - (Nfloat, 'f'), (Ndouble, 'd')] - --- What's the JPrim for a given NType? For example: native signed long long -> java long -ntype2jprim nt = fromJust $ lookup nt $ - [(NBOOL, Jboolean), (Nschar, Jbyte), (Nuchar, Jbyte), - (Nsshort, Jshort), (Nushort, Jshort), (Nsint, Jint), (Nuint, Jint), - (Nslong, Jlong), (Nulong, Jlong), - (Nslonglong, Jlong), (Nulonglong, Jlong), - (Nfloat, Jfloat), (Ndouble, Jdouble)] - --- What's the JClass for a given JPrim? For example: int -> Integer -jprim2jclass jp = fromJust $ lookup jp $ - [(Jboolean, JBoolean), (Jbyte, JByte), (Jchar, JCharacter), - (Jshort, JShort), (Jint, JInteger), (Jlong, JLong), - (Jfloat, JFloat), (Jdouble, JDouble)] - --- Convert a type to something suitable for Java code. For example: Jboolean -> boolean -ntype2js nt = tail $ show nt -jclass2js t = tail $ show t -jprim2js p = tail $ show p -ffitype2js f = "FFI_" ++ (show f) - --- Capitalize the first letter of a String -capitalize [] = [] -capitalize s = [toUpper $ head s] ++ tail s - --- Given an Width and NType, return the Java code for reading said NType from memory. -popAddr :: Width -> NType -> String -popAddr _ NBOOL = "rt.unsafe.getByte(addr) != 0" -popAddr _ Nschar = "rt.unsafe.getByte(addr)" -popAddr _ Nuchar = "rt.unsafe.getByte(addr)" -popAddr W32 Nslong = "rt.unsafe.getInt(addr)" -popAddr W32 Nulong = "rt.unsafe.getInt(addr)" -popAddr _ ntype = "rt.unsafe.get" ++ (capitalize.jprim2js.ntype2jprim $ ntype) ++ "(addr)" - --- Given an Width and NType, return the Java code for writing said NType to memory. -pushAddr :: Width -> NType -> String -pushAddr _ NBOOL = "rt.unsafe.putByte(addr, (byte) (x ? 1 : 0));" -pushAddr _ Nschar = "rt.unsafe.putByte(addr, x);" -pushAddr _ Nuchar = "rt.unsafe.putByte(addr, x);" -pushAddr W32 Nslong = "rt.unsafe.putInt(addr, (int) x);" -pushAddr W32 Nulong = "rt.unsafe.putInt(addr, (int) x);" -pushAddr _ ntype = "rt.unsafe.put" ++ (capitalize jprimS) ++ "(addr, (" ++ jprimS ++ ") x);" - where jprimS = jprim2js.ntype2jprim $ ntype - --- Helpers for generating Java ternarnies and conditionals. -archExpr x32 x64 = if x32 /= x64 then retdiff else x32 - where retdiff = "(JObjCRuntime.IS64 ? (" ++ x64 ++ ") : (" ++ x32 ++ "))" - -archStmt x32 x64 = if x32 /= x64 then retdiff else x32 - where retdiff = "if(JObjCRuntime.IS64){ " ++ x64 ++ " }else{ " ++ x32 ++ " }" - --- Get a Java expression for the correct FFIType at runtime. For example: (JObjCRuntime.IS64 ? FFI_SINT64 : FFI_SINT32) -ffitypeVal nt = archExpr (ffitype2js $ ffitype W32 nt) - (ffitype2js $ ffitype W64 nt) - --- Similar to ffiTypeVal. Get the correct pop expression and push statement. -popAddrVal nt = archExpr (popAddr W32 nt) (popAddr W64 nt) -pushAddrVal nt = archStmt (pushAddr W32 nt) (pushAddr W64 nt) - --- What's the Coder class name we're using for a given NType? -coderName nt = aux nt ++ "Coder" - where - aux NBOOL = "Bool" - aux Nschar = "SChar" - aux Nuchar = "UChar" - aux Nsshort = "SShort" - aux Nushort = "UShort" - aux Nsint = "SInt" - aux Nuint = "UInt" - aux Nslong = "SLong" - aux Nulong = "ULong" - aux Nslonglong = "SLongLong" - aux Nulonglong = "ULongLong" - aux Nfloat = "Float" - aux Ndouble = "Double" - --- Operation for converting between primitives. Usually it just casts, but booleans are special. -jconvertPrims sym Jboolean Jboolean = sym -jconvertPrims sym Jboolean b = "((" ++ jprim2js b ++ ")(" ++ sym ++ " ? 1 : 0))" -jconvertPrims sym a Jboolean = "(" ++ sym ++ " != 0)" -jconvertPrims sym a b = if a == b then sym else "((" ++ jprim2js b ++ ")" ++ sym ++ ")" - -sizeofRet nt = - let ffitypes = map (\w -> ffitype w nt) widths - sizes = map sizeof ffitypes in - if (length $ nub sizes) == 1 - then "\t\treturn " ++ (show.head $ sizes) ++ ";" - else unlines [ - "\t\tswitch(w){", - (unlines $ map casestmt widths), - "\t\tdefault: return -1;", - "\t\t}"] - where - casestmt w = "\t\t\tcase " ++ (show w) ++ ": return " ++ - (show.sizeof $ ffitype w nt) ++ ";" - --- Generate a coder class for a given NType. -c2java ntype = - unlines [ - "// native " ++ ntypeS ++ " -> java " ++ jprimS, - "public static final class " ++ className ++ " extends PrimitiveCoder<" ++ jclassS ++ ">{", - "\tpublic static final " ++ className ++ " INST = new " ++ className ++ "();", - "\tpublic " ++ className ++ "(){ super("++ffitypeVal ntype++", \"" ++ [encoding ntype] ++ "\", "++jclassS++".class, "++jprimS++".class); }", - "\t// compile time", - "\t@Override public void push(JObjCRuntime rt, long addr, " ++ jprimS ++ " x){", - "\t\t" ++ pushAddrVal ntype, - "\t}", - "\t@Override public " ++ jprimS ++ " pop" ++ capitalize jprimS ++ "(JObjCRuntime rt, long addr){", - "\t\treturn " ++ popAddrVal ntype ++ ";", - "\t}", - "\t// for runtime coding", - "\t@Override public int sizeof(Width w){", - sizeofRet ntype, - "\t}", - "\t@Override public void push(JObjCRuntime rt, long addr, " ++ jclassS ++ " x){ " ++ - "push(rt, addr, (" ++ jprimS ++ ") x); }", - "\t@Override public " ++ jclassS ++ " pop(JObjCRuntime rt, long addr){ " ++ - "return pop" ++ capitalize jprimS ++ "(rt, addr); }", - "\t// proxies for mixed encoding", - makeProxyMethods ntype, - "}" - ] - where - jprim = ntype2jprim ntype - jclass = jprim2jclass jprim - jprimS = jprim2js jprim - jclassS = jclass2js jclass - ntypeS = ntype2js ntype - className = coderName ntype - --- Generate push and pop methods that convert and proxy to actual implementation. -makeProxyMethods nt = unlines $ map aux jprims - where - targetJPrim = ntype2jprim nt - targetJPrimS = jprim2js targetJPrim - aux jprim = if targetJPrim == jprim then "" else unlines [ - "\t@Override public void push(JObjCRuntime rt, long addr, " ++ jprimS ++ " x){ " ++ - "push(rt, addr, " ++ pushConversion "x" ++ "); }", - "\t@Override public " ++ jprimS ++ " pop" ++ capitalize jprimS ++ "(JObjCRuntime rt, long addr){ " ++ - "return " ++ (popConversion ("pop" ++ capitalize targetJPrimS ++ "(rt, addr)")) ++ "; }" - ] - where - jprimS = jprim2js jprim - pushConversion sym = jconvertPrims sym jprim targetJPrim - popConversion sym = jconvertPrims sym targetJPrim jprim - -main = do - putStrLn "package com.apple.jobjc;" - - putStrLn "import com.apple.jobjc.JObjCRuntime.Width;" - - putStrLn "// Auto generated by PrimitiveCoder.hs" - putStrLn "// Do not edit by hand." - - putStrLn "public abstract class PrimitiveCoder extends Coder{" - - putStrLn "\tpublic PrimitiveCoder(int ffiTypeCode, String objCEncoding, Class jclass, Class jprim){" - putStrLn "\t\tsuper(ffiTypeCode, objCEncoding, jclass, jprim);" - putStrLn "\t}" - - mapM_ (\p -> putStrLn $ unlines [makePopI p, makePushI p]) jprims - - mapM_ (putStrLn . c2java) ntypes - - putStrLn "}" - where - makePopI jprim = unlines ["\tpublic final " ++ jprim2js jprim ++ " pop" ++ (capitalize.jprim2js $ jprim) - ++ "(NativeArgumentBuffer args){\n" - ++ "\t\treturn pop" ++ (capitalize.jprim2js $ jprim) ++ "(args.runtime, args.retValPtr);\n" - ++ "\t}", - "\tpublic abstract " ++ jprim2js jprim ++ " pop" ++ (capitalize.jprim2js $ jprim) ++ "(JObjCRuntime runtime, long addr);"] - makePushI jprim = unlines ["\tpublic final void push" - ++ "(NativeArgumentBuffer args, " ++ jprim2js jprim ++ " x){\n" - ++ "\t\tpush(args.runtime, args.argValuesPtr, x);\n" - ++ "\t\targs.didPutArgValue(sizeof());\n" - ++ "\t}", - "\tpublic abstract void push(JObjCRuntime runtime, long addr, " ++ jprim2js jprim ++ " x);"] diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/CIF.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/CIF.java deleted file mode 100644 index c32d822662f..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/CIF.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.jobjc.Coder.PrimitivePointerCoder; - -class CIF { - private static native int getSizeofCIF(); - private static final int SIZEOF = getSizeofCIF(); - private static native boolean prepCIF(long cifPtr, int nargs, long retFFITypePtr, long argsPtr); - - public static CIF createCIFFor(final NativeArgumentBuffer args, final Coder returnCoder, final Coder ... argCoders) { - NativeBuffer cifBuf = new NativeBuffer(SIZEOF + (argCoders.length * JObjCRuntime.PTR_LEN)); - final long argsPtr = cifBuf.bufferPtr + SIZEOF; - - { - long argsIterPtr = argsPtr; - for(final Coder coder : argCoders){ - PrimitivePointerCoder.INST.push(args.runtime, argsIterPtr, coder.getFFITypePtr()); - argsIterPtr += JObjCRuntime.PTR_LEN; - } - } - - boolean ok = prepCIF(cifBuf.bufferPtr, argCoders.length, returnCoder.getFFITypePtr(), argsPtr); - if(!ok) - throw new RuntimeException("ffi_prep_cif failed."); - - return new CIF(cifBuf, returnCoder, argCoders); - } - - final NativeBuffer cif; - // CIF needs to keep refs to the Coders, so they don't get finalized and their FFITypes freed. - final Coder returnCoder; - final Coder[] argCoders; - - private CIF(final NativeBuffer cif, Coder returnCoder, Coder... argCoders) { - this.cif = cif; - this.returnCoder = returnCoder; - this.argCoders = argCoders; - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Coder.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Coder.java deleted file mode 100644 index 9efc76e9c05..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Coder.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - -import java.io.StringWriter; -import java.lang.reflect.Method; - -import com.apple.jobjc.JObjCRuntime.Width; -import com.apple.jobjc.PrimitiveCoder.BoolCoder; -import com.apple.jobjc.PrimitiveCoder.DoubleCoder; -import com.apple.jobjc.PrimitiveCoder.FloatCoder; -import com.apple.jobjc.PrimitiveCoder.SCharCoder; -import com.apple.jobjc.PrimitiveCoder.SIntCoder; -import com.apple.jobjc.PrimitiveCoder.SLongLongCoder; -import com.apple.jobjc.PrimitiveCoder.SShortCoder; - -public abstract class Coder { - private static native long getNativeFFITypePtrForCode(final int code); - - static final int FFI_VOID = 0; - static final int FFI_PTR = FFI_VOID+1; - - static final int FFI_SINT8 = FFI_PTR+1; - static final int FFI_UINT8 = FFI_SINT8+1; - static final int FFI_SINT16 = FFI_UINT8+1; - static final int FFI_UINT16 = FFI_SINT16+1; - static final int FFI_SINT32 = FFI_UINT16+1; - static final int FFI_UINT32 = FFI_SINT32+1; - static final int FFI_SINT64 = FFI_UINT32+1; - static final int FFI_UINT64 = FFI_SINT64+1; - - static final int FFI_FLOAT = FFI_UINT64+1; - static final int FFI_DOUBLE = FFI_FLOAT+1; - static final int FFI_LONGDOUBLE = FFI_DOUBLE+1; - - private static long[] ffiCodesToFFITypePtrs; - static{ - System.loadLibrary("JObjC"); - ffiCodesToFFITypePtrs = new long[FFI_LONGDOUBLE + 1]; - for (int i = 0; i < FFI_LONGDOUBLE + 1; i++) ffiCodesToFFITypePtrs[i] = getNativeFFITypePtrForCode(i); - } - - long getFFITypePtr() { - return ffiCodesToFFITypePtrs[getTypeCode()]; - } - - // runtime coding - public abstract void push(final JObjCRuntime runtime, final long addr, final T x); - public abstract T pop(final JObjCRuntime runtime, final long addr); - - public void push(final NativeArgumentBuffer args, final T x){ - push(args.runtime, args.argValuesPtr, x); - args.didPutArgValue(sizeof()); - } - - public T pop(final NativeArgumentBuffer args){ - return pop(args.runtime, args.retValPtr); - } - - public abstract int sizeof(Width w); - final public int sizeof(){ return sizeof(JObjCRuntime.WIDTH); } - - // - - public Coder(int ffiTypeCode, String objCEncoding, Class jclass, Class jprim) { - this.ffiTypeCode = ffiTypeCode; - this.objCEncoding = objCEncoding; - this.jclass = jclass; - this.jprim = jprim; - } - - public Coder(int ffiTypeCode, String objCEncoding, Class jclass) { - this(ffiTypeCode, objCEncoding, jclass, null); - } - - private final int ffiTypeCode; - private final String objCEncoding; - private final Class jclass; - private final Class jprim; - - final int getTypeCode() { return ffiTypeCode; } - final String getObjCEncoding(){ return objCEncoding; } - public final Class getJavaClass() { return jclass; } - public final Class getJavaPrimitive() { return jprim; } - - // runtime coding - - private static Coder[] runtimeCoders; - static public Coder getCoderAtRuntimeForType(Class cls){ - if(runtimeCoders == null) runtimeCoders = new Coder[]{ - NSClassCoder.INST, IDCoder.INST, PointerCoder.INST, - DoubleCoder.INST, FloatCoder.INST, SLongLongCoder.INST, - SIntCoder.INST, SShortCoder.INST, SCharCoder.INST, BoolCoder.INST, - VoidCoder.INST - }; - - for(Coder c : runtimeCoders) - if((c.getJavaClass() != null && c.getJavaClass().isAssignableFrom(cls)) || - (c.getJavaPrimitive() != null && c.getJavaPrimitive().isAssignableFrom(cls))) - return c; - - if(Struct.class.isAssignableFrom(cls)){ - try { - Method m = cls.getDeclaredMethod("getStructCoder"); - m.setAccessible(true); - return (Coder) m.invoke(null); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - throw new RuntimeException("Could not find suitable coder for " + cls); - } - - static public Coder getCoderAtRuntime(Object inst){ - if(inst == null) return PointerCoder.INST; - if(inst instanceof Struct) return ((Struct) inst).getCoder(); - return getCoderAtRuntimeForType(inst.getClass()); - } - - // - - public static final class VoidCoder extends Coder{ - public static final VoidCoder INST = new VoidCoder(); - public VoidCoder(){ super(FFI_VOID, "v", Void.class, void.class); } - @Override public int sizeof(Width w) { return -1; } - @Override public Object pop(JObjCRuntime runtime, long addr) { throw new RuntimeException("Trying to pop a Void."); } - @Override public void push(JObjCRuntime runtime, long addr, Object x) { throw new RuntimeException("Trying to push a Void."); } - } - - public static final class UnknownCoder extends Coder { - public static final UnknownCoder INST = new UnknownCoder(); - public UnknownCoder(){ super(-1, "?", null, null); } - @Override public int sizeof(Width w) { return -1; } - @Override public void push(JObjCRuntime runtime, long addr, Object x) { throw new RuntimeException("Coder not implemented");} - @Override public Object pop(JObjCRuntime runtime, long addr) { throw new RuntimeException("Coder not implemented"); } - } - - public static final class PrimitivePointerCoder extends Coder { - public static final PrimitivePointerCoder INST = new PrimitivePointerCoder(); - public PrimitivePointerCoder(){ super(Coder.FFI_PTR, "^?", Long.class, long.class); } - @Override public int sizeof(Width w) { return JObjCRuntime.PTR_LEN; } - - public void push(JObjCRuntime runtime, long addr, long x) { - if(JObjCRuntime.IS64) - runtime.unsafe.putLong(addr, x); - else - runtime.unsafe.putInt(addr, (int) x); - } - - public void push(final JObjCRuntime runtime, final NativeArgumentBuffer argBuf, final long ptr) { - push(runtime, argBuf.argValuesPtr, ptr); - argBuf.didPutArgValue(sizeof()); - } - - public long popPtr(final JObjCRuntime runtime, final long addr) { - return JObjCRuntime.IS64 ? runtime.unsafe.getLong(addr) : runtime.unsafe.getInt(addr); - } - - public long popPtr(final JObjCRuntime runtime, final NativeArgumentBuffer argBuf) { - return popPtr(runtime, argBuf.retValPtr); - } - - @Override public Long pop(JObjCRuntime runtime, long addr) { return popPtr(runtime, addr); } - @Override public void push(JObjCRuntime runtime, long addr, Long x) { push(runtime, addr, (long) x); } - } - - public static final class PointerCoder extends Coder { - public static final PointerCoder INST = new PointerCoder(); - public PointerCoder(){ super(FFI_PTR, "^?", Pointer.class); } - @Override public int sizeof(Width w) { return PrimitivePointerCoder.INST.sizeof(w); } - - @Override public Pointer pop(JObjCRuntime runtime, long addr) { - return new Pointer(PrimitivePointerCoder.INST.popPtr(runtime, addr)); - } - @Override public void push(JObjCRuntime runtime, long addr, Pointer x) { - PrimitivePointerCoder.INST.push(runtime, addr, x == null ? 0 : x.ptr); - } - } - - public static final class SELCoder extends Coder { - public static final SELCoder INST = new SELCoder(); - public SELCoder(){ super(FFI_PTR, ":", SEL.class); } - @Override public int sizeof(Width w) { return PrimitivePointerCoder.INST.sizeof(w); } - - @Override public void push(JObjCRuntime runtime, long addr, SEL x) { - PrimitivePointerCoder.INST.push(runtime, addr, x == null ? 0 : x.selPtr); - } - @Override public SEL pop(JObjCRuntime runtime, long addr) { - return new SEL(PrimitivePointerCoder.INST.popPtr(runtime, addr)); - } - } - - public static abstract class StructCoder extends Coder { - private final FFIType ffiType; - final int sizeof; - - public StructCoder(final int sizeof, final Coder... elementCoders){ - super(-1, objCEncoding(elementCoders), null); - this.ffiType = new FFIType(elementCoders); - this.sizeof = sizeof; - } - - @Override public int sizeof(Width w) { return sizeof; } - - private static String objCEncoding(final Coder[] elementCoders) { - StringWriter str = new StringWriter(); - str.append("{?="); - for(Coder c : elementCoders) - str.append(c.getObjCEncoding()); - str.append("}"); - return str.toString(); - } - - @Override long getFFITypePtr() { return ffiType.getPtr(); } - - @Override public void push(NativeArgumentBuffer argBuf, Struct x) { - // Just point to the instance on the heap instead of copying it onto the arg buf. - argBuf.doPutArgPtr(x.raw.bufferPtr); - } - - @Override public void push(JObjCRuntime rt, long addr, Struct x) { - rt.unsafe.copyMemory(x.raw.bufferPtr, addr, sizeof); - } - - protected abstract Struct newInstance(JObjCRuntime runtime); - - @Override public Struct pop(final JObjCRuntime runtime, final long addr) { - Struct s = newInstance(runtime); - runtime.unsafe.copyMemory(addr, s.raw.bufferPtr, sizeof); - return s; - } - } - - public static final class IDCoder extends Coder{ - public static final IDCoder INST = new IDCoder(); - public IDCoder(){ super(FFI_PTR, "@", ID.class); } - @Override public int sizeof(Width w) { return PrimitivePointerCoder.INST.sizeof(w); } - - public T newID(final JObjCRuntime runtime, final long objPtr) { - return (T) ID.getObjCObjectFor(runtime, objPtr); - } - - @Override public ID pop(final JObjCRuntime runtime, final long addr) { - return newID(runtime, PrimitivePointerCoder.INST.popPtr(runtime, addr)); - } - - @Override public void push(final JObjCRuntime runtime, final long addr, final ID x) { - PointerCoder.INST.push(runtime, addr, x); - } - } - - public static final class NSClassCoder extends Coder{ - public static final NSClassCoder INST = new NSClassCoder(); - public NSClassCoder(){ super(FFI_PTR, "#", NSClass.class); } - @Override public int sizeof(Width w) { return PrimitivePointerCoder.INST.sizeof(w); } - - @Override public NSClass pop(JObjCRuntime runtime, long addr) { - final long clsPtr = PrimitivePointerCoder.INST.popPtr(runtime, addr); - if (clsPtr == 0) return null; - return NSClass.getObjCClassFor(runtime, clsPtr); - } - @Override public void push(JObjCRuntime runtime, long addr, NSClass x) { - PointerCoder.INST.push(runtime, addr, x); - } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/FFIType.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/FFIType.java deleted file mode 100644 index dcff0035587..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/FFIType.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - -import com.apple.jobjc.Coder.PrimitivePointerCoder; - - -class FFIType{ - private static native void makeFFIType(long ffi_type_buf, long elements_buf); - private static native int getFFITypeSizeof(); - private static int FFI_TYPE_SIZEOF = getFFITypeSizeof(); - final NativeBuffer ffi_type; - final NativeBuffer elements; - final Coder[] elementCoders; - - public FFIType(final Coder... elementCoders){ - final JObjCRuntime runtime = JObjCRuntime.inst(); - this.elementCoders = elementCoders; - this.ffi_type = new NativeBuffer(FFI_TYPE_SIZEOF); - this.elements = new NativeBuffer(JObjCRuntime.PTR_LEN * (elementCoders.length + 1)); - - long elIterPtr = elements.bufferPtr; - for(Coder c : elementCoders){ - PrimitivePointerCoder.INST.push(runtime, elIterPtr, c.getFFITypePtr()); - elIterPtr += PrimitivePointerCoder.INST.sizeof(); - } - PrimitivePointerCoder.INST.push(runtime, elIterPtr, 0); - - makeFFIType(ffi_type.bufferPtr, elements.bufferPtr); - } - - public long getPtr(){ - return ffi_type.bufferPtr; - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Function.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Function.java deleted file mode 100644 index 413d8fafe76..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Function.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - - -public class Function { - private static native long getFxnPtrForFunctionName(final String functionName); - private static native long getFxnPtrForFunctionNameAndLib(final long libPtr, final String functionName); - - final long fxnPtr; - - Function(final long fxnPtr) { - this.fxnPtr = fxnPtr; - } - - public Function(final String name) { - this(getFxnPtr(name)); - } - - public Function(final MacOSXFramework framework, final String name) { - this(getFxnPtr(name, framework)); - } - - static long getFxnPtr(final String name){ - long fxnPtr = getFxnPtrForFunctionName(name); - if(fxnPtr == 0) throw new RuntimeException("Function pointer for " + name + " not found in runtime."); - return fxnPtr; - } - - static long getFxnPtr(final String name, final MacOSXFramework framework){ - long fxnPtr = 0; - for(int i = 0; fxnPtr == 0 && i < framework.nativeLibPtrs.length; i++){ - fxnPtr = getFxnPtrForFunctionNameAndLib(framework.nativeLibPtrs[i], name); - if(fxnPtr != 0) return fxnPtr; - } - throw new RuntimeException("Function pointer for " + name + " not found in framework " + framework + "."); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/ID.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/ID.java deleted file mode 100644 index aa202cf0943..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/ID.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - -import java.lang.ref.WeakReference; -import java.lang.reflect.Constructor; -import java.util.LinkedHashMap; -import java.util.Map; - - -public class ID extends Pointer{ - static native String getNativeDescription(final long objPtr); - - final JObjCRuntime runtime; - - static final Class[] CTOR_ARGS = { long.class, JObjCRuntime.class }; - protected ID(final long objPtr, final JObjCRuntime runtime) { - super(objPtr); - runtime.assertOK(); - this.runtime = runtime; - } - - protected ID(final ID obj, final JObjCRuntime runtime) { - this(obj.ptr, runtime); - } - - @Override protected NativeObjectLifecycleManager getNativeObjectLifecycleManager() { - return NativeObjectLifecycleManager.CFRetainRelease.INST; - } - - protected final JObjCRuntime getRuntime() { return runtime; } - - @Override public String toString(){ - String s = super.toString(); - return s + " (ObjC: " + ptr + " / " + Long.toHexString(ptr) + ")"; - } - - // - - public static T getInstance(final long ptr, final JObjCRuntime runtime){ - return (T) getObjCObjectFor(runtime, ptr); - } - - static T getObjCObjectFor(final JObjCRuntime runtime, final long objPtr){ - if (objPtr == 0) return null; - - final WeakReference cachedObj = objectCache.get().get(objPtr); - if(cachedObj != null && cachedObj.get() != null) return (T) cachedObj.get(); - - final long clsPtr = NSClass.getClass(objPtr); - - final T newObj = (T) (runtime.subclassing.isUserClass(clsPtr) ? - Subclassing.getJObjectFromIVar(objPtr) - : createNewObjCObjectFor(runtime, objPtr, clsPtr)); - - objectCache.get().put(objPtr, new WeakReference(newObj)); - return newObj; - } - - static T createNewObjCObjectFor(final JObjCRuntime runtime, final long objPtr, final long clsPtr) { - final Constructor ctor = getConstructorForClassPtr(runtime, clsPtr); - return (T) createNewObjCObjectForConstructor(ctor, objPtr, runtime); - } - - @SuppressWarnings("unchecked") - static Constructor getConstructorForClassPtr(final JObjCRuntime runtime, final long clazzPtr){ - final Constructor cachedCtor = (Constructor) constructorCache.get().get(clazzPtr); - if(cachedCtor != null) return cachedCtor; - - final Class clazz = getClassForClassPtr(runtime, clazzPtr); - Constructor ctor; - try { - ctor = clazz.getDeclaredConstructor(CTOR_ARGS); - } catch (SecurityException e) { - throw new RuntimeException(e); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - ctor.setAccessible(true); - constructorCache.get().put(clazzPtr, (Constructor) ctor); - return ctor; - } - - @SuppressWarnings("unchecked") - static Class getClassForClassPtr(final JObjCRuntime runtime, final long clazzPtr){ - final String className = NSClass.getClassNameOfClass(clazzPtr); - final Class clazz = (Class) runtime.getClassForNativeClassName(className); - if(clazz == null){ - final long superClazzPtr = NSClass.getSuperClassOfClass(clazzPtr); - if(superClazzPtr != 0) - return getClassForClassPtr(runtime, superClazzPtr); - } - return clazz; - } - - static T createNewObjCObjectForConstructor(final Constructor ctor, final long objPtr, final JObjCRuntime runtime) { - try { - final T newInstance = (T) ctor.newInstance(new Object[] { Long.valueOf(objPtr), runtime }); - objectCache.get().put(objPtr, new WeakReference(newInstance)); - return newInstance; - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - static T createNewObjCObjectForClass(final Class clazz, final long objPtr, final JObjCRuntime runtime) { - try { - final Constructor constructor = clazz.getDeclaredConstructor(CTOR_ARGS); - constructor.setAccessible(true); - return (T) createNewObjCObjectForConstructor(constructor, objPtr, runtime); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - // - - static final ThreadLocal> constructorCache = new ThreadLocal>(){ - @Override protected LinkedHashMap initialValue(){ - final int MAX_ENTRIES = 1000; - final float LOAD_FACTOR = 0.75f; - return new LinkedHashMap((int) (MAX_ENTRIES/LOAD_FACTOR), LOAD_FACTOR, true) { - @Override protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > MAX_ENTRIES; - } - }; - } - }; - - static final ThreadLocal> objectCache = new ThreadLocal>(){ - @Override protected LinkedHashMap initialValue(){ - final int MAX_ENTRIES = 1000; - final float LOAD_FACTOR = 0.75f; - return new LinkedHashMap((int) (MAX_ENTRIES/LOAD_FACTOR), LOAD_FACTOR, true) { - @Override protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > MAX_ENTRIES || eldest.getValue().get() == null; - } - }; - } - }; -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Invoke.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Invoke.java deleted file mode 100644 index 48ffc98663f..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Invoke.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - -import com.apple.jobjc.Coder.IDCoder; -import com.apple.jobjc.Coder.NSClassCoder; -import com.apple.jobjc.Coder.PrimitivePointerCoder; -import com.apple.jobjc.Coder.SELCoder; -import com.apple.jobjc.Coder.StructCoder; - - -public abstract class Invoke { - public abstract void invoke(NativeArgumentBuffer argBuf); - public abstract void invoke(NativeArgumentBuffer buffer, Struct retvalStruct); - - // - - public static final class FunCall extends Invoke{ - static native void invoke(long cifPtr, long fxnPtr, long retValPtr, long argsPtr); - - final long fxnPtr; - final CIF cif; - - FunCall(long fxnPtr, CIF cif) { - this.fxnPtr = fxnPtr; - this.cif = cif; - } - - public FunCall(final JObjCRuntime runtime, final String name, final Coder returnCoder, final Coder ... argCoders) { - this(Function.getFxnPtr(name), CIF.createCIFFor(runtime.getThreadLocalState(), returnCoder, argCoders)); - } - - public FunCall(final MacOSXFramework framework, final String name, final Coder returnCoder, final Coder ... argCoders) { - this(Function.getFxnPtr(name, framework), CIF.createCIFFor(framework.getRuntime().getThreadLocalState(), returnCoder, argCoders)); - } - - public void init(final NativeArgumentBuffer argBuf) { - argBuf.reset(); - } - - @Override public void invoke(final NativeArgumentBuffer argBuf) { - invoke(argBuf, argBuf.retValPtr); - } - - @Override public void invoke(final NativeArgumentBuffer buffer, final Struct retvalStruct) { - invoke(buffer, retvalStruct.raw.bufferPtr); - } - - void invoke(final NativeArgumentBuffer argBuf, final long retValPtr) { - invoke(cif.cif.bufferPtr, fxnPtr, retValPtr, argBuf.buffer.bufferPtr); - } - } - - public static final class MsgSend extends Invoke{ - static{ System.load("/usr/lib/libobjc.dylib"); } - - private static final long OBJC_MSG_SEND_FXN_PTR = new Function("objc_msgSend").fxnPtr; - private static final long OBJC_MSG_SEND_FPRET_FXN_PTR = new Function("objc_msgSend_fpret").fxnPtr; - private static final long OBJC_MSG_SEND_STRET_FXN_PTR = new Function("objc_msgSend_stret").fxnPtr; - - final FunCall funCall; - final long selPtr; - - public MsgSend(final JObjCRuntime runtime, final String name, final Coder returnCoder, final Coder ... argCoders) { - this.funCall = new FunCall(getMsgSendFxnPtr(returnCoder), - CIF.createCIFFor(runtime.getThreadLocalState(), returnCoder, getSelCoders(argCoders))); - this.selPtr = SEL.getSelectorPtr(name); - } - - public void init(final NativeArgumentBuffer nativeBuffer, final ID obj) { - funCall.init(nativeBuffer); - IDCoder.INST.push(nativeBuffer, obj); - PrimitivePointerCoder.INST.push(nativeBuffer.runtime, nativeBuffer, selPtr); - } - - @Override public void invoke(final NativeArgumentBuffer argBuf) { - funCall.invoke(argBuf); - } - - @Override public void invoke(final NativeArgumentBuffer buffer, final Struct retvalStruct) { - funCall.invoke(buffer, retvalStruct); - } - - // support - - static Coder[] getSelCoders(final Coder[] argCoders) { - final Coder[] selArgCoders = new Coder[argCoders.length + 2]; - selArgCoders[0] = IDCoder.INST; - selArgCoders[1] = SELCoder.INST; - for (int i = 0; i < argCoders.length; i++) - selArgCoders[i + 2] = argCoders[i]; - return selArgCoders; - } - - static long getMsgSendFxnPtr(final Coder returnCoder) { - if(returnCoder instanceof StructCoder){ - StructCoder scoder = (StructCoder) returnCoder; - - switch(JObjCRuntime.ARCH){ - case ppc: - return OBJC_MSG_SEND_STRET_FXN_PTR; - case i386: - switch(scoder.sizeof){ - case 1: case 2: case 4: case 8: - return OBJC_MSG_SEND_FXN_PTR; - } - return OBJC_MSG_SEND_STRET_FXN_PTR; - case x86_64: - if(scoder.sizeof > 16) - return OBJC_MSG_SEND_STRET_FXN_PTR; - else - return OBJC_MSG_SEND_FXN_PTR; - default: - throw new RuntimeException(); - } - } - - final int typeCode = returnCoder.getTypeCode(); - - switch(JObjCRuntime.ARCH){ - case ppc: - return OBJC_MSG_SEND_FXN_PTR; - case i386: - switch(typeCode) { - case Coder.FFI_FLOAT: case Coder.FFI_DOUBLE: case Coder.FFI_LONGDOUBLE: - return OBJC_MSG_SEND_FPRET_FXN_PTR; - } - return OBJC_MSG_SEND_FXN_PTR; - case x86_64: - if(typeCode == Coder.FFI_LONGDOUBLE) - return OBJC_MSG_SEND_FPRET_FXN_PTR; - return OBJC_MSG_SEND_FXN_PTR; - default: - throw new RuntimeException(); - } - } - } - - public static final class MsgSendSuper extends Invoke{ - static{ System.load("/usr/lib/libobjc.dylib"); } - - private static final long OBJC_MSG_SEND_SUPER_FXN_PTR = new Function("objc_msgSendSuper").fxnPtr; - private static final long OBJC_MSG_SEND_SUPER_STRET_FXN_PTR = new Function("objc_msgSendSuper_stret").fxnPtr; - - final FunCall funCall; - final long selPtr; - - public MsgSendSuper(final JObjCRuntime runtime, final String name, final Coder returnCoder, final Coder ... argCoders) { - this.funCall = new FunCall(getMsgSendSuperFxnPtr(returnCoder), - CIF.createCIFFor(runtime.getThreadLocalState(), returnCoder, getSuperSelCoders(argCoders))); - this.selPtr = SEL.getSelectorPtr(name); - } - - public void init(final NativeArgumentBuffer argBuf, final ID obj, final NSClass cls) { - funCall.init(argBuf); - - // Instead of mallocing a struct, or keeping another thread local, - // let's write objc_super out to the argbuf, and then point an argument - // to the data. - - final long valPtr = argBuf.argValuesPtr; - final int ptrLen = JObjCRuntime.PTR_LEN; - - IDCoder .INST.push(argBuf.runtime, valPtr, obj); - NSClassCoder.INST.push(argBuf.runtime, valPtr + ptrLen, cls); - argBuf.argValuesPtr += ptrLen + ptrLen; - - PrimitivePointerCoder.INST.push(argBuf.runtime, argBuf, valPtr); - PrimitivePointerCoder.INST.push(argBuf.runtime, argBuf, selPtr); - } - - @Override public void invoke(final NativeArgumentBuffer argBuf) { - funCall.invoke(argBuf); - } - - @Override public void invoke(final NativeArgumentBuffer buffer, final Struct retvalStruct) { - funCall.invoke(buffer, retvalStruct); - } - - // - - private final static StructCoder objc_super_coder = new StructCoder(JObjCRuntime.PTR_LEN*2, IDCoder.INST, NSClassCoder.INST){ - @Override protected Struct newInstance(JObjCRuntime runtime) { return null; }}; - - static Coder[] getSuperSelCoders(final Coder[] argCoders) { - final Coder[] selArgCoders = new Coder[argCoders.length + 2]; - selArgCoders[0] = objc_super_coder; - selArgCoders[1] = SELCoder.INST; - for (int i = 0; i < argCoders.length; i++) - selArgCoders[i + 2] = argCoders[i]; - return selArgCoders; - } - - static long getMsgSendSuperFxnPtr(final Coder returnCoder){ - long normal = MsgSend.getMsgSendFxnPtr(returnCoder); - if(normal == MsgSend.OBJC_MSG_SEND_STRET_FXN_PTR) - return OBJC_MSG_SEND_SUPER_STRET_FXN_PTR; - else - return OBJC_MSG_SEND_SUPER_FXN_PTR; - } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/JObjCRuntime.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/JObjCRuntime.java deleted file mode 100644 index 5bc01bc4e97..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/JObjCRuntime.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - -import java.lang.reflect.Field; -import java.nio.ByteOrder; -import java.util.ArrayList; -import java.util.List; - -import sun.misc.Unsafe; - - -public final class JObjCRuntime { - static { System.loadLibrary("JObjC"); } - - public static enum Arch{ ppc, i386, x86_64 }; - public static enum Width{ W32, W64 }; - - public static final Arch ARCH = getArch(); - public static final Width WIDTH = getWidth(); - - private static Arch getArch(){ - String arch = System.getProperty("os.arch"); - if("ppc".equals(arch)) return Arch.ppc; - if("i386".equals(arch)) return Arch.i386; - if("x86_64".equals(arch)) return Arch.x86_64; - if("amd64".equals(arch)) return Arch.x86_64; - if("universal".equals(arch)) return Arch.x86_64; - throw new RuntimeException("Did not recognize os.arch system property: '" + arch + "'"); - } - - private static Width getWidth(){ - String width = System.getProperty("sun.arch.data.model"); - if("32".equals(width)) return Width.W32; - if("64".equals(width)) return Width.W64; - throw new RuntimeException("Did not recognize sun.arch.data.model system property: '" + width + "'"); - } - - public static final boolean IS32 = System.getProperty("sun.arch.data.model").equals("32"); - public static final boolean IS64 = System.getProperty("sun.arch.data.model").equals("64"); - public static final int PTR_LEN = IS64 ? 8 : 4; - public static final boolean IS_BIG_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN; - static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("JObjC.debug")); - - static void checkPermission(){ - final SecurityManager security = System.getSecurityManager(); - if (security != null) security.checkPermission(new RuntimePermission("canProcessApplicationEvents")); - } - - public final void assertOK(){ - if(this != instance) - throw new SecurityException("runtime"); - } - - private JObjCRuntime(){} - - private static JObjCRuntime instance; - static JObjCRuntime inst() { - if (instance == null) instance = new JObjCRuntime(); - return instance; - } - - public static JObjCRuntime getInstance() { - checkPermission(); - return inst(); - } - - public final NativeArgumentBuffer getThreadLocalState() { - return NativeArgumentBuffer.getThreadLocalBuffer(this); - } - - final Unsafe unsafe = getUnsafe(); - final Subclassing subclassing = new Subclassing(this); - final List registeredPackages = new ArrayList(); - - @SuppressWarnings("unchecked") - Class getClassForNativeClassName(final String className) { - for (final String pkg : registeredPackages) { - try { - final Class clazz = Class.forName(pkg + "." + className); - if (clazz != null) return (Class)clazz; - } catch (final ClassNotFoundException e) { } - } - - return null; - } - - private final static Unsafe getUnsafe() { - Unsafe inst = null; - try { - Field f = Unsafe.class.getDeclaredField("theUnsafe"); - f.setAccessible(true); - inst = (Unsafe) f.get(null); - if(inst == null) throw new NullPointerException("Unsafe.theUnsafe == null"); - } catch (Exception e) { - throw new RuntimeException("Unable to get instance of Unsafe.", e); - } - return inst; - } - - public void registerPackage(final String pkg) { - registeredPackages.add(pkg); - } - - /** - * Register a subclass of NSObject to allow the native side to send - * messages which in turn call java methods declared on the class. - * If a native class by the same name already exists, registerClass - * will simply return without doing anything. - * - * For a usage example, see the SubclassingTest. - */ - public boolean registerUserClass(Class clazz, Class clazzClazz) { - return subclassing.registerUserClass(clazz, clazzClazz); - } - -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/MacOSXFramework.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/MacOSXFramework.java deleted file mode 100644 index bd776688f7d..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/MacOSXFramework.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - - - -public class MacOSXFramework { - private static native long retainFramework(final String frameworkName); - private static native void releaseFramework(final long frameworkPtr); - private static native void getConstant(final long frameworkPtr, String symbol, final long bufferPtr, final int size); - - private final JObjCRuntime runtime; - protected final long[] nativeLibPtrs; - - final long getFrameworkPtr() { return nativeLibPtrs.length > 0 ? nativeLibPtrs[0] : 0; } - - private static long[] createFrameworkPtrsFromPaths(final String[] frameworkLibPaths) { - final long[] libPtrs = new long[frameworkLibPaths.length]; - for(int i = 0; i < libPtrs.length; i++){ - libPtrs[i] = retainFramework(frameworkLibPaths[i]); - if(libPtrs[i] == 0) throw new RuntimeException("Could not open library at " + frameworkLibPaths[i]); - } - return libPtrs; - } - - protected MacOSXFramework(final JObjCRuntime runtime, final String[] nativeLibPaths) { - runtime.assertOK(); - this.runtime = runtime; - this.nativeLibPtrs = createFrameworkPtrsFromPaths(nativeLibPaths); - } - - @Override protected final synchronized void finalize() throws Throwable { - for(long lib : nativeLibPtrs) - if(lib != 0) releaseFramework(lib); - } - - protected final JObjCRuntime getRuntime(){ return runtime; } - - protected void getConstant(final String symbol, final long retValPtr, final int size){ - assert size >= 0; - assert retValPtr != 0; - getConstant(getFrameworkPtr(), symbol, retValPtr, size); - } - - protected void getConstant(final String symbol, final NativeArgumentBuffer out, final int size){ - getConstant(symbol, out.retValPtr, size); - } - - protected void getConstant(final String symbol, final Struct out, final int size){ - getConstant(symbol, out.raw.bufferPtr, size); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/NSClass.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/NSClass.java deleted file mode 100644 index dfda99acf35..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/NSClass.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - -import java.lang.ref.WeakReference; -import java.lang.reflect.Constructor; - - -public class NSClass extends ID { - public static class NSClassNotFoundException extends RuntimeException{ - public NSClassNotFoundException(String m){ super(m); } - public NSClassNotFoundException(String m, Throwable cause){ super(m, cause); } - } - - static native long getNativeClassByName(String name); - static native long getSuperClassOfClass(long classPtr); - static native String getClassNameOfClass(long classPtr); - static native long getClass(long objPtr); - - public NSClass(final long ptr, final JObjCRuntime runtime) { - super(ptr, runtime); - } - - public NSClass(final String name, final JObjCRuntime runtime) { - this(getNativeClassByName(name), runtime); - if(ptr == 0) throw new NSClassNotFoundException("NSClass pointer is 0. Found no class named " + name); - } - - protected NSClass(final JObjCRuntime runtime){ - super(0, runtime); - final String sn = getClass().getSimpleName(); - final String name = sn.substring(0, sn.lastIndexOf("Class")); - ptr = getNativeClassByName(name); - if(ptr == 0) throw new NSClassNotFoundException("NSClass pointer is 0. Found no class named " + name); - } - - NSClass getSuperClass() { - return new NSClass(getSuperClassOfClass(ptr), runtime); - } - - String getClassName() { return getClassNameOfClass(ptr); } - - @Override protected NativeObjectLifecycleManager getNativeObjectLifecycleManager() { - return NativeObjectLifecycleManager.Nothing.INST; - } - - @Override public boolean equals(Object o){ - return (o instanceof NSClass) && (this.ptr == ((NSClass) o).ptr); - } - - // - - static T getObjCClassFor(final JObjCRuntime runtime, final long clsPtr){ - if (clsPtr == 0) return null; - - final WeakReference cachedObj = objectCache.get().get(clsPtr); - if(cachedObj != null && cachedObj.get() != null) return (T) cachedObj.get(); - - final T newObj = (T) createNewObjCClassFor(runtime, clsPtr); - objectCache.get().put(clsPtr, new WeakReference(newObj)); - return newObj; - } - - static T createNewObjCClassFor(final JObjCRuntime runtime, final long clsPtr) { - final Constructor ctor = getNSClassConstructorForClassPtr(runtime, clsPtr); - return (T) createNewObjCObjectForConstructor(ctor, clsPtr, runtime); - } - - @SuppressWarnings("unchecked") - static Constructor getNSClassConstructorForClassPtr(final JObjCRuntime runtime, final long clazzPtr){ - final Class clazz = getNSClassForClassPtr(runtime, clazzPtr); - Constructor ctor; - try { - ctor = clazz.getDeclaredConstructor(CTOR_ARGS); - } catch (SecurityException e) { - throw new RuntimeException(e); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - ctor.setAccessible(true); - return ctor; - } - - @SuppressWarnings("unchecked") - static Class getNSClassForClassPtr(final JObjCRuntime runtime, final long clazzPtr){ - final String className = NSClass.getClassNameOfClass(clazzPtr); - final Class clazz = (Class) runtime.getClassForNativeClassName(className + "Class"); - if(clazz == null){ - final long superClazzPtr = NSClass.getSuperClassOfClass(clazzPtr); - if(superClazzPtr != 0) - return getNSClassForClassPtr(runtime, superClazzPtr); - } - return clazz; - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/NativeArgumentBuffer.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/NativeArgumentBuffer.java deleted file mode 100644 index 7f8949a2b40..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/NativeArgumentBuffer.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - -import java.nio.ByteOrder; - -import com.apple.jobjc.Coder.PrimitivePointerCoder; - - -public final class NativeArgumentBuffer{ - private static final ThreadLocal threadLocal = new ThreadLocal(); - - static NativeArgumentBuffer getThreadLocalBuffer(final JObjCRuntime runtime) { - runtime.assertOK(); - final NativeArgumentBuffer alreadyCreated = threadLocal.get(); - if (alreadyCreated != null) return alreadyCreated; - - final NativeArgumentBuffer newThreadLocalState = new NativeArgumentBuffer(runtime); - threadLocal.set(newThreadLocalState); - return newThreadLocalState; - } - - final JObjCRuntime runtime; - - final NativeBuffer buffer; - - long argPtrsPtr; - long argValuesPtr; - final long retValPtr; - - private static final int MAX_ARGS = 512; - private static final int BUF_SIZE = MAX_ARGS * 8 * 2; - private static final int ARG_VALS_OFFSET = BUF_SIZE/2; - - private NativeArgumentBuffer(final JObjCRuntime runtime) { - runtime.assertOK(); - this.runtime = runtime; - this.buffer = new NativeBuffer(BUF_SIZE); - this.buffer.buffer.order(ByteOrder.nativeOrder()); - - reset(); - this.retValPtr = buffer.bufferPtr; - } - - - // Call before each new call - public void reset() { - argPtrsPtr = buffer.bufferPtr; - argValuesPtr = buffer.bufferPtr + ARG_VALS_OFFSET; - assert buffer.ptrInBounds(argValuesPtr); - } - - // Push a pointer to a block of memory - public void doPutArgPtr(long ptr) { - assert buffer.ptrInBounds(argPtrsPtr); - PrimitivePointerCoder.INST.push(runtime, argPtrsPtr, ptr); - argPtrsPtr += JObjCRuntime.PTR_LEN; - } - - // Call this after having written a value of size `sizeof` to `argValuesPtr`. - public void didPutArgValue(int sizeof) { - assert buffer.ptrInBounds(argValuesPtr); - doPutArgPtr(argValuesPtr); - argValuesPtr += sizeof; - } - - - @Override public String toString() { - final StringBuilder builder = new StringBuilder(); - final long bptr = buffer.bufferPtr; - - for(long i = bptr; i < bptr + ARG_VALS_OFFSET; i += JObjCRuntime.PTR_LEN){ - if(argPtrsPtr == i) - builder.append("*"); - builder.append(PrimitivePointerCoder.INST.popPtr(JObjCRuntime.inst(), i)); - builder.append(" "); - } - - builder.append("\n"); - - for(long i = bptr + ARG_VALS_OFFSET; i < bptr + BUF_SIZE; i += JObjCRuntime.PTR_LEN){ - if(argValuesPtr == i) - builder.append("*"); - builder.append(PrimitivePointerCoder.INST.popPtr(JObjCRuntime.inst(), i)); - builder.append(" "); - } - - return builder.toString(); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/NativeBuffer.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/NativeBuffer.java deleted file mode 100644 index 8630971c206..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/NativeBuffer.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - - -/** - * A wrapper around a direct ByteBuffer and its native pointer. For documentation, @see java.nio.ByteBuffer - */ -public class NativeBuffer { - static native long getPtrOfBuffer(final ByteBuffer byteBuffer); - - public final ByteBuffer buffer; - public final long bufferPtr; - - public NativeBuffer(final int capacity){ - this(ByteBuffer.allocateDirect(capacity)); - } - - /** - * Wrap a ByteBuffer and set the ByteOrder to nativeOrder. - */ - public NativeBuffer(ByteBuffer buffer){ - this.buffer = buffer; - this.bufferPtr = getPtrOfBuffer(buffer); - assert buffer != null; - assert bufferPtr != 0; - this.buffer.order(ByteOrder.nativeOrder()); - } - - public byte get() { return buffer.get(); } - public char getChar() { return buffer.getChar(); } - public double getDouble() { return buffer.getDouble(); } - public float getFloat() { return buffer.getFloat(); } - public int getInt() { return buffer.getInt(); } - public long getLong() { return buffer.getLong(); } - public short getShort() { return buffer.getShort(); } - public NativeBuffer put(byte b) { buffer.put(b); return this; } - public NativeBuffer put(NativeBuffer src) { buffer.put(src.buffer); return this; } - public NativeBuffer putChar(char c) { buffer.putChar(c); return this; } - public NativeBuffer putDouble(double d) { buffer.putDouble(d); return this; } - public NativeBuffer putFloat(float f) { buffer.putFloat(f); return this; } - public NativeBuffer putInt(int i) { buffer.putInt(i); return this; } - public NativeBuffer putLong(long l) { buffer.putLong(l); return this; } - public NativeBuffer putShort(short s) { buffer.putShort(s); return this; } - - public int capacity() { return buffer.capacity(); } - public int position() { return buffer.position(); } - public NativeBuffer position(int newPosition) { buffer.position(newPosition); return this; } - public NativeBuffer rewind(){ buffer.rewind(); return this; } - - public int limit() { return buffer.limit(); } - public NativeBuffer limit(final int sizeof) { buffer.limit(sizeof); return this; } - - public int remaining() { return buffer.remaining(); } - - public NativeBuffer slice(){ return new NativeBuffer(buffer.slice()); } - - @Override public String toString() { - final StringBuilder builder = new StringBuilder(); - - for(int i = 0; i < limit(); i += JObjCRuntime.PTR_LEN){ - if(position() == i) - builder.append("*"); - if(JObjCRuntime.IS32) - builder.append(buffer.getInt(i)); - else - builder.append(buffer.getLong(i)); - builder.append(" "); - } - - return builder.toString(); - } - - public long positionPtr() { - return bufferPtr + position(); - } - - /** - * bufferPtr <= ptr && ptr < bufferPtr + capacity(); - */ - public boolean ptrInBounds(final long ptr){ - return bufferPtr <= ptr && ptr < bufferPtr + capacity(); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/NativeObjectLifecycleManager.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/NativeObjectLifecycleManager.java deleted file mode 100644 index 993be3337fe..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/NativeObjectLifecycleManager.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - - -public abstract class NativeObjectLifecycleManager { - private static native void retainNativeObject(final long ptr); - private static native void releaseNativeObject(final long ptr); - private static native void freeNativeObject(final long ptr); - - abstract void begin(final long ptr); - abstract void end(final long ptr); - boolean shouldPreRetain() { return false; } - - public static class CFRetainRelease extends NativeObjectLifecycleManager { - public static final NativeObjectLifecycleManager INST = new CFRetainRelease(); - @Override void begin(final long ptr) { retainNativeObject(ptr); } - @Override void end(final long ptr) { releaseNativeObject(ptr); } - @Override boolean shouldPreRetain() { return true; } - } - - public static class Free extends NativeObjectLifecycleManager { - public static final NativeObjectLifecycleManager INST = new Free(); - @Override void begin(final long ptr) { } - @Override void end(final long ptr) { freeNativeObject(ptr); } - } - - public static class Nothing extends NativeObjectLifecycleManager { - public static final NativeObjectLifecycleManager INST = new Nothing(); - @Override void begin(final long ptr) { } - @Override void end(final long ptr) { } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Pointer.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Pointer.java deleted file mode 100644 index d5b83b93930..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Pointer.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - - -public class Pointer implements Comparable>{ - long ptr; - - protected Pointer(final long ptr) { - this.ptr = ptr; - getNativeObjectLifecycleManager().begin(ptr); - } - - @Override protected final synchronized void finalize() throws Throwable { - long pptr = ptr; - ptr = 0; - if (pptr != 0) getNativeObjectLifecycleManager().end(pptr); - } - - protected NativeObjectLifecycleManager getNativeObjectLifecycleManager() { - return NativeObjectLifecycleManager.Nothing.INST; - } - - @Override public boolean equals(Object o) { - return o instanceof Pointer && ptr == ((Pointer) o).ptr; - } - - @Override public int hashCode() { return (int)(ptr^(ptr>>>32)); } - - public int compareTo(Pointer o) { - if(this==o || ptr==o.ptr) return 0; - if(ptr < o.ptr) return -1; - return 1; - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/PrimitiveCoder.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/PrimitiveCoder.java deleted file mode 100644 index eab34a7e6af..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/PrimitiveCoder.java +++ /dev/null @@ -1,700 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; -import com.apple.jobjc.JObjCRuntime.Width; -// Auto generated by PrimitiveCoder.hs -// Do not edit by hand. -public abstract class PrimitiveCoder extends Coder{ - public PrimitiveCoder(int ffiTypeCode, String objCEncoding, Class jclass, Class jprim){ - super(ffiTypeCode, objCEncoding, jclass, jprim); - } - public final boolean popBoolean(NativeArgumentBuffer args){ - return popBoolean(args.runtime, args.retValPtr); - } - public abstract boolean popBoolean(JObjCRuntime runtime, long addr); - - public final void push(NativeArgumentBuffer args, boolean x){ - push(args.runtime, args.argValuesPtr, x); - args.didPutArgValue(sizeof()); - } - public abstract void push(JObjCRuntime runtime, long addr, boolean x); - - - public final byte popByte(NativeArgumentBuffer args){ - return popByte(args.runtime, args.retValPtr); - } - public abstract byte popByte(JObjCRuntime runtime, long addr); - - public final void push(NativeArgumentBuffer args, byte x){ - push(args.runtime, args.argValuesPtr, x); - args.didPutArgValue(sizeof()); - } - public abstract void push(JObjCRuntime runtime, long addr, byte x); - - - public final char popChar(NativeArgumentBuffer args){ - return popChar(args.runtime, args.retValPtr); - } - public abstract char popChar(JObjCRuntime runtime, long addr); - - public final void push(NativeArgumentBuffer args, char x){ - push(args.runtime, args.argValuesPtr, x); - args.didPutArgValue(sizeof()); - } - public abstract void push(JObjCRuntime runtime, long addr, char x); - - - public final short popShort(NativeArgumentBuffer args){ - return popShort(args.runtime, args.retValPtr); - } - public abstract short popShort(JObjCRuntime runtime, long addr); - - public final void push(NativeArgumentBuffer args, short x){ - push(args.runtime, args.argValuesPtr, x); - args.didPutArgValue(sizeof()); - } - public abstract void push(JObjCRuntime runtime, long addr, short x); - - - public final int popInt(NativeArgumentBuffer args){ - return popInt(args.runtime, args.retValPtr); - } - public abstract int popInt(JObjCRuntime runtime, long addr); - - public final void push(NativeArgumentBuffer args, int x){ - push(args.runtime, args.argValuesPtr, x); - args.didPutArgValue(sizeof()); - } - public abstract void push(JObjCRuntime runtime, long addr, int x); - - - public final long popLong(NativeArgumentBuffer args){ - return popLong(args.runtime, args.retValPtr); - } - public abstract long popLong(JObjCRuntime runtime, long addr); - - public final void push(NativeArgumentBuffer args, long x){ - push(args.runtime, args.argValuesPtr, x); - args.didPutArgValue(sizeof()); - } - public abstract void push(JObjCRuntime runtime, long addr, long x); - - - public final float popFloat(NativeArgumentBuffer args){ - return popFloat(args.runtime, args.retValPtr); - } - public abstract float popFloat(JObjCRuntime runtime, long addr); - - public final void push(NativeArgumentBuffer args, float x){ - push(args.runtime, args.argValuesPtr, x); - args.didPutArgValue(sizeof()); - } - public abstract void push(JObjCRuntime runtime, long addr, float x); - - - public final double popDouble(NativeArgumentBuffer args){ - return popDouble(args.runtime, args.retValPtr); - } - public abstract double popDouble(JObjCRuntime runtime, long addr); - - public final void push(NativeArgumentBuffer args, double x){ - push(args.runtime, args.argValuesPtr, x); - args.didPutArgValue(sizeof()); - } - public abstract void push(JObjCRuntime runtime, long addr, double x); - - -// native BOOL -> java boolean -public static final class BoolCoder extends PrimitiveCoder{ - public static final BoolCoder INST = new BoolCoder(); - public BoolCoder(){ super(FFI_SINT8, "B", Boolean.class, boolean.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, boolean x){ - rt.unsafe.putByte(addr, (byte) (x ? 1 : 0)); - } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ - return rt.unsafe.getByte(addr) != 0; - } - // for runtime coding - @Override public int sizeof(Width w){ - return 1; - } - @Override public void push(JObjCRuntime rt, long addr, Boolean x){ push(rt, addr, (boolean) x); } - @Override public Boolean pop(JObjCRuntime rt, long addr){ return popBoolean(rt, addr); } - // proxies for mixed encoding - - @Override public void push(JObjCRuntime rt, long addr, byte x){ push(rt, addr, (x != 0)); } - @Override public byte popByte(JObjCRuntime rt, long addr){ return ((byte)(popBoolean(rt, addr) ? 1 : 0)); } - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, (x != 0)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)(popBoolean(rt, addr) ? 1 : 0)); } - - @Override public void push(JObjCRuntime rt, long addr, short x){ push(rt, addr, (x != 0)); } - @Override public short popShort(JObjCRuntime rt, long addr){ return ((short)(popBoolean(rt, addr) ? 1 : 0)); } - - @Override public void push(JObjCRuntime rt, long addr, int x){ push(rt, addr, (x != 0)); } - @Override public int popInt(JObjCRuntime rt, long addr){ return ((int)(popBoolean(rt, addr) ? 1 : 0)); } - - @Override public void push(JObjCRuntime rt, long addr, long x){ push(rt, addr, (x != 0)); } - @Override public long popLong(JObjCRuntime rt, long addr){ return ((long)(popBoolean(rt, addr) ? 1 : 0)); } - - @Override public void push(JObjCRuntime rt, long addr, float x){ push(rt, addr, (x != 0)); } - @Override public float popFloat(JObjCRuntime rt, long addr){ return ((float)(popBoolean(rt, addr) ? 1 : 0)); } - - @Override public void push(JObjCRuntime rt, long addr, double x){ push(rt, addr, (x != 0)); } - @Override public double popDouble(JObjCRuntime rt, long addr){ return ((double)(popBoolean(rt, addr) ? 1 : 0)); } - - -} - -// native schar -> java byte -public static final class SCharCoder extends PrimitiveCoder{ - public static final SCharCoder INST = new SCharCoder(); - public SCharCoder(){ super(FFI_SINT8, "c", Byte.class, byte.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, byte x){ - rt.unsafe.putByte(addr, x); - } - @Override public byte popByte(JObjCRuntime rt, long addr){ - return rt.unsafe.getByte(addr); - } - // for runtime coding - @Override public int sizeof(Width w){ - return 1; - } - @Override public void push(JObjCRuntime rt, long addr, Byte x){ push(rt, addr, (byte) x); } - @Override public Byte pop(JObjCRuntime rt, long addr){ return popByte(rt, addr); } - // proxies for mixed encoding - @Override public void push(JObjCRuntime rt, long addr, boolean x){ push(rt, addr, ((byte)(x ? 1 : 0))); } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ return (popByte(rt, addr) != 0); } - - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, ((byte)x)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)popByte(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, short x){ push(rt, addr, ((byte)x)); } - @Override public short popShort(JObjCRuntime rt, long addr){ return ((short)popByte(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, int x){ push(rt, addr, ((byte)x)); } - @Override public int popInt(JObjCRuntime rt, long addr){ return ((int)popByte(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, long x){ push(rt, addr, ((byte)x)); } - @Override public long popLong(JObjCRuntime rt, long addr){ return ((long)popByte(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, float x){ push(rt, addr, ((byte)x)); } - @Override public float popFloat(JObjCRuntime rt, long addr){ return ((float)popByte(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, double x){ push(rt, addr, ((byte)x)); } - @Override public double popDouble(JObjCRuntime rt, long addr){ return ((double)popByte(rt, addr)); } - - -} - -// native uchar -> java byte -public static final class UCharCoder extends PrimitiveCoder{ - public static final UCharCoder INST = new UCharCoder(); - public UCharCoder(){ super(FFI_UINT8, "C", Byte.class, byte.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, byte x){ - rt.unsafe.putByte(addr, x); - } - @Override public byte popByte(JObjCRuntime rt, long addr){ - return rt.unsafe.getByte(addr); - } - // for runtime coding - @Override public int sizeof(Width w){ - return 1; - } - @Override public void push(JObjCRuntime rt, long addr, Byte x){ push(rt, addr, (byte) x); } - @Override public Byte pop(JObjCRuntime rt, long addr){ return popByte(rt, addr); } - // proxies for mixed encoding - @Override public void push(JObjCRuntime rt, long addr, boolean x){ push(rt, addr, ((byte)(x ? 1 : 0))); } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ return (popByte(rt, addr) != 0); } - - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, ((byte)x)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)popByte(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, short x){ push(rt, addr, ((byte)x)); } - @Override public short popShort(JObjCRuntime rt, long addr){ return ((short)popByte(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, int x){ push(rt, addr, ((byte)x)); } - @Override public int popInt(JObjCRuntime rt, long addr){ return ((int)popByte(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, long x){ push(rt, addr, ((byte)x)); } - @Override public long popLong(JObjCRuntime rt, long addr){ return ((long)popByte(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, float x){ push(rt, addr, ((byte)x)); } - @Override public float popFloat(JObjCRuntime rt, long addr){ return ((float)popByte(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, double x){ push(rt, addr, ((byte)x)); } - @Override public double popDouble(JObjCRuntime rt, long addr){ return ((double)popByte(rt, addr)); } - - -} - -// native sshort -> java short -public static final class SShortCoder extends PrimitiveCoder{ - public static final SShortCoder INST = new SShortCoder(); - public SShortCoder(){ super(FFI_SINT16, "s", Short.class, short.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, short x){ - rt.unsafe.putShort(addr, (short) x); - } - @Override public short popShort(JObjCRuntime rt, long addr){ - return rt.unsafe.getShort(addr); - } - // for runtime coding - @Override public int sizeof(Width w){ - return 2; - } - @Override public void push(JObjCRuntime rt, long addr, Short x){ push(rt, addr, (short) x); } - @Override public Short pop(JObjCRuntime rt, long addr){ return popShort(rt, addr); } - // proxies for mixed encoding - @Override public void push(JObjCRuntime rt, long addr, boolean x){ push(rt, addr, ((short)(x ? 1 : 0))); } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ return (popShort(rt, addr) != 0); } - - @Override public void push(JObjCRuntime rt, long addr, byte x){ push(rt, addr, ((short)x)); } - @Override public byte popByte(JObjCRuntime rt, long addr){ return ((byte)popShort(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, ((short)x)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)popShort(rt, addr)); } - - - @Override public void push(JObjCRuntime rt, long addr, int x){ push(rt, addr, ((short)x)); } - @Override public int popInt(JObjCRuntime rt, long addr){ return ((int)popShort(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, long x){ push(rt, addr, ((short)x)); } - @Override public long popLong(JObjCRuntime rt, long addr){ return ((long)popShort(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, float x){ push(rt, addr, ((short)x)); } - @Override public float popFloat(JObjCRuntime rt, long addr){ return ((float)popShort(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, double x){ push(rt, addr, ((short)x)); } - @Override public double popDouble(JObjCRuntime rt, long addr){ return ((double)popShort(rt, addr)); } - - -} - -// native ushort -> java short -public static final class UShortCoder extends PrimitiveCoder{ - public static final UShortCoder INST = new UShortCoder(); - public UShortCoder(){ super(FFI_UINT16, "S", Short.class, short.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, short x){ - rt.unsafe.putShort(addr, (short) x); - } - @Override public short popShort(JObjCRuntime rt, long addr){ - return rt.unsafe.getShort(addr); - } - // for runtime coding - @Override public int sizeof(Width w){ - return 2; - } - @Override public void push(JObjCRuntime rt, long addr, Short x){ push(rt, addr, (short) x); } - @Override public Short pop(JObjCRuntime rt, long addr){ return popShort(rt, addr); } - // proxies for mixed encoding - @Override public void push(JObjCRuntime rt, long addr, boolean x){ push(rt, addr, ((short)(x ? 1 : 0))); } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ return (popShort(rt, addr) != 0); } - - @Override public void push(JObjCRuntime rt, long addr, byte x){ push(rt, addr, ((short)x)); } - @Override public byte popByte(JObjCRuntime rt, long addr){ return ((byte)popShort(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, ((short)x)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)popShort(rt, addr)); } - - - @Override public void push(JObjCRuntime rt, long addr, int x){ push(rt, addr, ((short)x)); } - @Override public int popInt(JObjCRuntime rt, long addr){ return ((int)popShort(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, long x){ push(rt, addr, ((short)x)); } - @Override public long popLong(JObjCRuntime rt, long addr){ return ((long)popShort(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, float x){ push(rt, addr, ((short)x)); } - @Override public float popFloat(JObjCRuntime rt, long addr){ return ((float)popShort(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, double x){ push(rt, addr, ((short)x)); } - @Override public double popDouble(JObjCRuntime rt, long addr){ return ((double)popShort(rt, addr)); } - - -} - -// native sint -> java int -public static final class SIntCoder extends PrimitiveCoder{ - public static final SIntCoder INST = new SIntCoder(); - public SIntCoder(){ super(FFI_SINT32, "i", Integer.class, int.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, int x){ - rt.unsafe.putInt(addr, (int) x); - } - @Override public int popInt(JObjCRuntime rt, long addr){ - return rt.unsafe.getInt(addr); - } - // for runtime coding - @Override public int sizeof(Width w){ - return 4; - } - @Override public void push(JObjCRuntime rt, long addr, Integer x){ push(rt, addr, (int) x); } - @Override public Integer pop(JObjCRuntime rt, long addr){ return popInt(rt, addr); } - // proxies for mixed encoding - @Override public void push(JObjCRuntime rt, long addr, boolean x){ push(rt, addr, ((int)(x ? 1 : 0))); } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ return (popInt(rt, addr) != 0); } - - @Override public void push(JObjCRuntime rt, long addr, byte x){ push(rt, addr, ((int)x)); } - @Override public byte popByte(JObjCRuntime rt, long addr){ return ((byte)popInt(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, ((int)x)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)popInt(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, short x){ push(rt, addr, ((int)x)); } - @Override public short popShort(JObjCRuntime rt, long addr){ return ((short)popInt(rt, addr)); } - - - @Override public void push(JObjCRuntime rt, long addr, long x){ push(rt, addr, ((int)x)); } - @Override public long popLong(JObjCRuntime rt, long addr){ return ((long)popInt(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, float x){ push(rt, addr, ((int)x)); } - @Override public float popFloat(JObjCRuntime rt, long addr){ return ((float)popInt(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, double x){ push(rt, addr, ((int)x)); } - @Override public double popDouble(JObjCRuntime rt, long addr){ return ((double)popInt(rt, addr)); } - - -} - -// native uint -> java int -public static final class UIntCoder extends PrimitiveCoder{ - public static final UIntCoder INST = new UIntCoder(); - public UIntCoder(){ super(FFI_UINT32, "I", Integer.class, int.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, int x){ - rt.unsafe.putInt(addr, (int) x); - } - @Override public int popInt(JObjCRuntime rt, long addr){ - return rt.unsafe.getInt(addr); - } - // for runtime coding - @Override public int sizeof(Width w){ - return 4; - } - @Override public void push(JObjCRuntime rt, long addr, Integer x){ push(rt, addr, (int) x); } - @Override public Integer pop(JObjCRuntime rt, long addr){ return popInt(rt, addr); } - // proxies for mixed encoding - @Override public void push(JObjCRuntime rt, long addr, boolean x){ push(rt, addr, ((int)(x ? 1 : 0))); } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ return (popInt(rt, addr) != 0); } - - @Override public void push(JObjCRuntime rt, long addr, byte x){ push(rt, addr, ((int)x)); } - @Override public byte popByte(JObjCRuntime rt, long addr){ return ((byte)popInt(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, ((int)x)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)popInt(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, short x){ push(rt, addr, ((int)x)); } - @Override public short popShort(JObjCRuntime rt, long addr){ return ((short)popInt(rt, addr)); } - - - @Override public void push(JObjCRuntime rt, long addr, long x){ push(rt, addr, ((int)x)); } - @Override public long popLong(JObjCRuntime rt, long addr){ return ((long)popInt(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, float x){ push(rt, addr, ((int)x)); } - @Override public float popFloat(JObjCRuntime rt, long addr){ return ((float)popInt(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, double x){ push(rt, addr, ((int)x)); } - @Override public double popDouble(JObjCRuntime rt, long addr){ return ((double)popInt(rt, addr)); } - - -} - -// native slong -> java long -public static final class SLongCoder extends PrimitiveCoder{ - public static final SLongCoder INST = new SLongCoder(); - public SLongCoder(){ super((JObjCRuntime.IS64 ? (FFI_SINT64) : (FFI_SINT32)), "l", Long.class, long.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, long x){ - if(JObjCRuntime.IS64){ rt.unsafe.putLong(addr, (long) x); }else{ rt.unsafe.putInt(addr, (int) x); } - } - @Override public long popLong(JObjCRuntime rt, long addr){ - return (JObjCRuntime.IS64 ? (rt.unsafe.getLong(addr)) : (rt.unsafe.getInt(addr))); - } - // for runtime coding - @Override public int sizeof(Width w){ - switch(w){ - case W32: return 4; - case W64: return 8; - - default: return -1; - } - - } - @Override public void push(JObjCRuntime rt, long addr, Long x){ push(rt, addr, (long) x); } - @Override public Long pop(JObjCRuntime rt, long addr){ return popLong(rt, addr); } - // proxies for mixed encoding - @Override public void push(JObjCRuntime rt, long addr, boolean x){ push(rt, addr, ((long)(x ? 1 : 0))); } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ return (popLong(rt, addr) != 0); } - - @Override public void push(JObjCRuntime rt, long addr, byte x){ push(rt, addr, ((long)x)); } - @Override public byte popByte(JObjCRuntime rt, long addr){ return ((byte)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, ((long)x)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, short x){ push(rt, addr, ((long)x)); } - @Override public short popShort(JObjCRuntime rt, long addr){ return ((short)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, int x){ push(rt, addr, ((long)x)); } - @Override public int popInt(JObjCRuntime rt, long addr){ return ((int)popLong(rt, addr)); } - - - @Override public void push(JObjCRuntime rt, long addr, float x){ push(rt, addr, ((long)x)); } - @Override public float popFloat(JObjCRuntime rt, long addr){ return ((float)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, double x){ push(rt, addr, ((long)x)); } - @Override public double popDouble(JObjCRuntime rt, long addr){ return ((double)popLong(rt, addr)); } - - -} - -// native ulong -> java long -public static final class ULongCoder extends PrimitiveCoder{ - public static final ULongCoder INST = new ULongCoder(); - public ULongCoder(){ super((JObjCRuntime.IS64 ? (FFI_UINT64) : (FFI_UINT32)), "L", Long.class, long.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, long x){ - if(JObjCRuntime.IS64){ rt.unsafe.putLong(addr, (long) x); }else{ rt.unsafe.putInt(addr, (int) x); } - } - @Override public long popLong(JObjCRuntime rt, long addr){ - return (JObjCRuntime.IS64 ? (rt.unsafe.getLong(addr)) : (rt.unsafe.getInt(addr))); - } - // for runtime coding - @Override public int sizeof(Width w){ - switch(w){ - case W32: return 4; - case W64: return 8; - - default: return -1; - } - - } - @Override public void push(JObjCRuntime rt, long addr, Long x){ push(rt, addr, (long) x); } - @Override public Long pop(JObjCRuntime rt, long addr){ return popLong(rt, addr); } - // proxies for mixed encoding - @Override public void push(JObjCRuntime rt, long addr, boolean x){ push(rt, addr, ((long)(x ? 1 : 0))); } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ return (popLong(rt, addr) != 0); } - - @Override public void push(JObjCRuntime rt, long addr, byte x){ push(rt, addr, ((long)x)); } - @Override public byte popByte(JObjCRuntime rt, long addr){ return ((byte)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, ((long)x)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, short x){ push(rt, addr, ((long)x)); } - @Override public short popShort(JObjCRuntime rt, long addr){ return ((short)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, int x){ push(rt, addr, ((long)x)); } - @Override public int popInt(JObjCRuntime rt, long addr){ return ((int)popLong(rt, addr)); } - - - @Override public void push(JObjCRuntime rt, long addr, float x){ push(rt, addr, ((long)x)); } - @Override public float popFloat(JObjCRuntime rt, long addr){ return ((float)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, double x){ push(rt, addr, ((long)x)); } - @Override public double popDouble(JObjCRuntime rt, long addr){ return ((double)popLong(rt, addr)); } - - -} - -// native slonglong -> java long -public static final class SLongLongCoder extends PrimitiveCoder{ - public static final SLongLongCoder INST = new SLongLongCoder(); - public SLongLongCoder(){ super(FFI_SINT64, "q", Long.class, long.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, long x){ - rt.unsafe.putLong(addr, (long) x); - } - @Override public long popLong(JObjCRuntime rt, long addr){ - return rt.unsafe.getLong(addr); - } - // for runtime coding - @Override public int sizeof(Width w){ - return 8; - } - @Override public void push(JObjCRuntime rt, long addr, Long x){ push(rt, addr, (long) x); } - @Override public Long pop(JObjCRuntime rt, long addr){ return popLong(rt, addr); } - // proxies for mixed encoding - @Override public void push(JObjCRuntime rt, long addr, boolean x){ push(rt, addr, ((long)(x ? 1 : 0))); } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ return (popLong(rt, addr) != 0); } - - @Override public void push(JObjCRuntime rt, long addr, byte x){ push(rt, addr, ((long)x)); } - @Override public byte popByte(JObjCRuntime rt, long addr){ return ((byte)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, ((long)x)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, short x){ push(rt, addr, ((long)x)); } - @Override public short popShort(JObjCRuntime rt, long addr){ return ((short)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, int x){ push(rt, addr, ((long)x)); } - @Override public int popInt(JObjCRuntime rt, long addr){ return ((int)popLong(rt, addr)); } - - - @Override public void push(JObjCRuntime rt, long addr, float x){ push(rt, addr, ((long)x)); } - @Override public float popFloat(JObjCRuntime rt, long addr){ return ((float)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, double x){ push(rt, addr, ((long)x)); } - @Override public double popDouble(JObjCRuntime rt, long addr){ return ((double)popLong(rt, addr)); } - - -} - -// native ulonglong -> java long -public static final class ULongLongCoder extends PrimitiveCoder{ - public static final ULongLongCoder INST = new ULongLongCoder(); - public ULongLongCoder(){ super(FFI_UINT64, "Q", Long.class, long.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, long x){ - rt.unsafe.putLong(addr, (long) x); - } - @Override public long popLong(JObjCRuntime rt, long addr){ - return rt.unsafe.getLong(addr); - } - // for runtime coding - @Override public int sizeof(Width w){ - return 8; - } - @Override public void push(JObjCRuntime rt, long addr, Long x){ push(rt, addr, (long) x); } - @Override public Long pop(JObjCRuntime rt, long addr){ return popLong(rt, addr); } - // proxies for mixed encoding - @Override public void push(JObjCRuntime rt, long addr, boolean x){ push(rt, addr, ((long)(x ? 1 : 0))); } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ return (popLong(rt, addr) != 0); } - - @Override public void push(JObjCRuntime rt, long addr, byte x){ push(rt, addr, ((long)x)); } - @Override public byte popByte(JObjCRuntime rt, long addr){ return ((byte)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, ((long)x)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, short x){ push(rt, addr, ((long)x)); } - @Override public short popShort(JObjCRuntime rt, long addr){ return ((short)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, int x){ push(rt, addr, ((long)x)); } - @Override public int popInt(JObjCRuntime rt, long addr){ return ((int)popLong(rt, addr)); } - - - @Override public void push(JObjCRuntime rt, long addr, float x){ push(rt, addr, ((long)x)); } - @Override public float popFloat(JObjCRuntime rt, long addr){ return ((float)popLong(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, double x){ push(rt, addr, ((long)x)); } - @Override public double popDouble(JObjCRuntime rt, long addr){ return ((double)popLong(rt, addr)); } - - -} - -// native float -> java float -public static final class FloatCoder extends PrimitiveCoder{ - public static final FloatCoder INST = new FloatCoder(); - public FloatCoder(){ super(FFI_FLOAT, "f", Float.class, float.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, float x){ - rt.unsafe.putFloat(addr, (float) x); - } - @Override public float popFloat(JObjCRuntime rt, long addr){ - return rt.unsafe.getFloat(addr); - } - // for runtime coding - @Override public int sizeof(Width w){ - return 4; - } - @Override public void push(JObjCRuntime rt, long addr, Float x){ push(rt, addr, (float) x); } - @Override public Float pop(JObjCRuntime rt, long addr){ return popFloat(rt, addr); } - // proxies for mixed encoding - @Override public void push(JObjCRuntime rt, long addr, boolean x){ push(rt, addr, ((float)(x ? 1 : 0))); } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ return (popFloat(rt, addr) != 0); } - - @Override public void push(JObjCRuntime rt, long addr, byte x){ push(rt, addr, ((float)x)); } - @Override public byte popByte(JObjCRuntime rt, long addr){ return ((byte)popFloat(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, ((float)x)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)popFloat(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, short x){ push(rt, addr, ((float)x)); } - @Override public short popShort(JObjCRuntime rt, long addr){ return ((short)popFloat(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, int x){ push(rt, addr, ((float)x)); } - @Override public int popInt(JObjCRuntime rt, long addr){ return ((int)popFloat(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, long x){ push(rt, addr, ((float)x)); } - @Override public long popLong(JObjCRuntime rt, long addr){ return ((long)popFloat(rt, addr)); } - - - @Override public void push(JObjCRuntime rt, long addr, double x){ push(rt, addr, ((float)x)); } - @Override public double popDouble(JObjCRuntime rt, long addr){ return ((double)popFloat(rt, addr)); } - - -} - -// native double -> java double -public static final class DoubleCoder extends PrimitiveCoder{ - public static final DoubleCoder INST = new DoubleCoder(); - public DoubleCoder(){ super(FFI_DOUBLE, "d", Double.class, double.class); } - // compile time - @Override public void push(JObjCRuntime rt, long addr, double x){ - rt.unsafe.putDouble(addr, (double) x); - } - @Override public double popDouble(JObjCRuntime rt, long addr){ - return rt.unsafe.getDouble(addr); - } - // for runtime coding - @Override public int sizeof(Width w){ - return 8; - } - @Override public void push(JObjCRuntime rt, long addr, Double x){ push(rt, addr, (double) x); } - @Override public Double pop(JObjCRuntime rt, long addr){ return popDouble(rt, addr); } - // proxies for mixed encoding - @Override public void push(JObjCRuntime rt, long addr, boolean x){ push(rt, addr, ((double)(x ? 1 : 0))); } - @Override public boolean popBoolean(JObjCRuntime rt, long addr){ return (popDouble(rt, addr) != 0); } - - @Override public void push(JObjCRuntime rt, long addr, byte x){ push(rt, addr, ((double)x)); } - @Override public byte popByte(JObjCRuntime rt, long addr){ return ((byte)popDouble(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, char x){ push(rt, addr, ((double)x)); } - @Override public char popChar(JObjCRuntime rt, long addr){ return ((char)popDouble(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, short x){ push(rt, addr, ((double)x)); } - @Override public short popShort(JObjCRuntime rt, long addr){ return ((short)popDouble(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, int x){ push(rt, addr, ((double)x)); } - @Override public int popInt(JObjCRuntime rt, long addr){ return ((int)popDouble(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, long x){ push(rt, addr, ((double)x)); } - @Override public long popLong(JObjCRuntime rt, long addr){ return ((long)popDouble(rt, addr)); } - - @Override public void push(JObjCRuntime rt, long addr, float x){ push(rt, addr, ((double)x)); } - @Override public float popFloat(JObjCRuntime rt, long addr){ return ((float)popDouble(rt, addr)); } - - - -} - -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/SEL.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/SEL.java deleted file mode 100644 index 7e085f8d54d..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/SEL.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - - -public class SEL { - static native long getSelectorPtr(String selectorName); - static native String getSelectorName(long ptr); - - final long selPtr; - - SEL(long ptr) { - this.selPtr = ptr; - } - - public SEL(final String name) { - this(getSelectorPtr(name)); - } - - @Override public String toString(){ - return ((int)selPtr) + " / " + selPtr + " : " + getSelectorName(selPtr); - } - - /** - * Converts something like "performSelectorOnMainThread_withObject_wait" - * to "performSelectorOnMainThread:withObject:wait:" - */ - public static String selectorName(String jMethodName, boolean hasArgs){ - String b = jMethodName.replaceAll("_", ":"); - return hasArgs ? b + ":" : b; - } - - public static String jMethodName(String selectorName){ - return selectorName.replaceAll(":", "_").replaceAll("_$", ""); - } - - public static boolean validName(String selectorName){ - return selectorName.matches("^[a-zA-Z_][a-zA-Z0-9_:]*$"); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Struct.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Struct.java deleted file mode 100644 index b14e84dcaca..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Struct.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - - -/** - * A struct is malloced on the C heap and accessed in Java through a ByteBuffer. - */ -public abstract class Struct{ - protected final NativeBuffer raw; - private final JObjCRuntime runtime; - protected final JObjCRuntime getRuntime(){ return runtime; } - - /** - * Create a brand new struct from nothing. - */ - protected Struct(final JObjCRuntime runtime, final int SIZEOF){ - this(runtime, new NativeBuffer(SIZEOF), SIZEOF); - } - - /** - * Create a struct by taking ownership of an existing buffer. - * Used for struct fields of type struct. For example, the origin and size fields - * in NSRect would be initialized with this constructor. - */ - protected Struct(final JObjCRuntime runtime, final NativeBuffer buffer, final int SIZEOF){ - if(runtime == null) throw new NullPointerException("runtime"); - this.runtime = runtime; - this.raw = buffer; - this.raw.limit(SIZEOF); - } - - abstract public Coder getCoder(); -} diff --git a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Subclassing.java b/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Subclassing.java deleted file mode 100644 index c0e72b13e33..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/java/com/apple/jobjc/Subclassing.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.apple.jobjc; - -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.util.HashSet; -import java.util.Set; - -import com.apple.jobjc.Coder.PrimitivePointerCoder; -import com.apple.jobjc.Coder.VoidCoder; -import com.apple.jobjc.Invoke.MsgSend; - - -final class Subclassing { - static native long allocateClassPair(long superClass, String name); - static native boolean addIVarForJObj(long clazz); - static native boolean patchAlloc(long classPtr); - static native boolean addMethod(long cls, String name, Method jMethod, CIF cif, long cifPtr, String objCEncodedType); - static native void registerClassPair(long clazz); - - static native T getJObjectFromIVar(long objPtr); - static native void initJObjectToIVar(long objPtr, ID object); - - final Set registeredUserSubclasses = new HashSet(); - final JObjCRuntime runtime; - - Subclassing(JObjCRuntime runtime){ - this.runtime = runtime; - } - - boolean registerUserClass(final Class clazz, final Class clazzClazz) { - final String nativeClassName = clazz.getSimpleName(); - // Is it already registered? - if(0 != NSClass.getNativeClassByName(nativeClassName)) - return false; - - if(clazz.isAnonymousClass()) - throw new RuntimeException("JObjC cannot register anonymous classes."); - - // Verify superclass - long superClass = NSClass.getNativeClassByName(clazz.getSuperclass().getSimpleName()); - if(0 == superClass) - throw new RuntimeException(clazz.getSuperclass() + ", the superclass of " + clazz + ", must be a registered class."); - - runtime.registerPackage(clazz.getPackage().getName()); - - // Create class - long classPtr = Subclassing.allocateClassPair(superClass, nativeClassName); - if(classPtr == 0) throw new RuntimeException("objc_allocateClassPair returned 0."); - - // Add ivar to hold jobject - boolean addedI = Subclassing.addIVarForJObj(classPtr); - if(!addedI) throw new RuntimeException("class_addIvar returned false."); - - // Verify constructor - try { - clazz.getConstructor(ID.CTOR_ARGS); - } catch (Exception e) { - throw new RuntimeException("Could not access required constructor: " + ID.CTOR_ARGS, e); - } - - // Patch alloc to create corresponding jobject on invoke - patchAlloc(classPtr); - - // Add methods - Set takenSelNames = new HashSet(); - for(Method method : clazz.getDeclaredMethods()){ - // No overloading - String selName = SEL.selectorName(method.getName(), method.getParameterTypes().length > 0); - if(takenSelNames.contains(selName)) - throw new RuntimeException("Obj-C does not allow method overloading. The Objective-C selector '" - + selName + "' appears more than once in class " + clazz.getCanonicalName() + " / " + nativeClassName + "."); - - method.setAccessible(true); - - // Divine CIF - Coder returnCoder = Coder.getCoderAtRuntimeForType(method.getReturnType()); - Class[] paramTypes = method.getParameterTypes(); - Coder[] argCoders = new Coder[paramTypes.length]; - for(int i = 0; i < paramTypes.length; i++) - argCoders[i] = Coder.getCoderAtRuntimeForType(paramTypes[i]); - - CIF cif = new MsgSend(runtime, selName, returnCoder, argCoders).funCall.cif; - - // .. and objc encoding - StringWriter encType = new StringWriter(); - encType.append(returnCoder.getObjCEncoding()); - encType.append("@:"); - for(int i = 0; i < argCoders.length; i++) - encType.append(argCoders[i].getObjCEncoding()); - - // Add it! - boolean addedM = Subclassing.addMethod(classPtr, selName, method, cif, cif.cif.bufferPtr, encType.toString()); - if(!addedM) throw new RuntimeException("Failed to add method."); - takenSelNames.add(selName); - } - - // Seal it - Subclassing.registerClassPair(classPtr); - registeredUserSubclasses.add(classPtr); - - return true; - } - - boolean isUserClass(long clsPtr) { - return registeredUserSubclasses.contains(clsPtr); - } - - // Called from JNI - - private static void initJObject(final long objPtr){ -// System.err.println("initJObject " + objPtr + " / " + Long.toHexString(objPtr)); - ID newObj = ID.createNewObjCObjectFor(JObjCRuntime.inst(), objPtr, NSClass.getClass(objPtr)); -// System.err.println("... " + newObj); - initJObjectToIVar(objPtr, newObj); - } - - private static void invokeFromJNI(ID obj, Method method, CIF cif, long result, long args){ - assert obj != null; - assert obj.getClass().equals(method.getDeclaringClass()) : - obj.getClass().toString() + " != " + method.getDeclaringClass().toString(); - - final int argCount = method.getParameterTypes().length; - - // The first two args & coders are for objc id and sel. Skip them. - final Object[] argObjects = new Object[argCount]; - for(int i = 0; i < argCount; i++){ - final long argAddrAddr = args + ((i+2) * JObjCRuntime.PTR_LEN); - final long argAddr = PrimitivePointerCoder.INST.popPtr(obj.runtime, argAddrAddr); - argObjects[i] = cif.argCoders[i + 2].pop(obj.runtime, argAddr); - } - - Object retVal; - try { - retVal = method.invoke(obj, argObjects); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - - if(!(cif.returnCoder instanceof VoidCoder)) - cif.returnCoder.push(obj.runtime, result, retVal); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/core/native/CIF.m b/jdk/src/macosx/native/jobjc/src/core/native/CIF.m deleted file mode 100644 index 7aa4dd542a5..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/native/CIF.m +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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 - * 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. - */ - -#include "com_apple_jobjc_CIF.h" - -#define MACOSX -#include -#include - -#include "NativeBuffer.h" - -JNIEXPORT jint JNICALL Java_com_apple_jobjc_CIF_getSizeofCIF -(JNIEnv *env, jclass clazz) -{ - return (jint) sizeof(ffi_cif); -} - -JNIEXPORT jboolean JNICALL Java_com_apple_jobjc_CIF_prepCIF -(JNIEnv *env, jclass clazz, jlong jCIFPtr, jint jNargs, jlong jRetTypePtr, jlong jArgsPtr) -{ - ffi_cif *cif = jlong_to_ptr(jCIFPtr); - unsigned int nargs = jNargs; - ffi_type *rtype = jlong_to_ptr(jRetTypePtr); - ffi_type **atypes = jlong_to_ptr(jArgsPtr); - -// NSLog(@"rtype->(size: %d, alignment: %d, type: %d)", rtype->size, rtype->alignment, rtype->type); - return (jboolean) (FFI_OK == ffi_prep_cif(cif, FFI_DEFAULT_ABI, nargs, rtype, atypes)); -} diff --git a/jdk/src/macosx/native/jobjc/src/core/native/Coder.m b/jdk/src/macosx/native/jobjc/src/core/native/Coder.m deleted file mode 100644 index af3553949bf..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/native/Coder.m +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 - * 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. - */ - -#include "com_apple_jobjc_Coder.h" - -#include -#define MACOSX -#include -#include - -/* - * Class: com_apple_jobjc_Coder - * Method: getNativeFFITypeCodeForCode - * Signature: (I)J - */ -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_Coder_getNativeFFITypePtrForCode -(JNIEnv *env, jclass clazz, jint code) -{ - switch ((long)code) { - case com_apple_jobjc_Coder_FFI_VOID: return ptr_to_jlong(&ffi_type_void); - case com_apple_jobjc_Coder_FFI_PTR: return ptr_to_jlong(&ffi_type_pointer); - case com_apple_jobjc_Coder_FFI_SINT8: return ptr_to_jlong(&ffi_type_sint8); - case com_apple_jobjc_Coder_FFI_UINT8: return ptr_to_jlong(&ffi_type_uint8); - case com_apple_jobjc_Coder_FFI_SINT16: return ptr_to_jlong(&ffi_type_sint16); - case com_apple_jobjc_Coder_FFI_UINT16: return ptr_to_jlong(&ffi_type_uint16); - case com_apple_jobjc_Coder_FFI_SINT32: return ptr_to_jlong(&ffi_type_sint32); - case com_apple_jobjc_Coder_FFI_UINT32: return ptr_to_jlong(&ffi_type_uint32); - case com_apple_jobjc_Coder_FFI_SINT64: return ptr_to_jlong(&ffi_type_sint64); - case com_apple_jobjc_Coder_FFI_UINT64: return ptr_to_jlong(&ffi_type_uint64); - case com_apple_jobjc_Coder_FFI_FLOAT: return ptr_to_jlong(&ffi_type_float); - case com_apple_jobjc_Coder_FFI_DOUBLE: return ptr_to_jlong(&ffi_type_double); - case com_apple_jobjc_Coder_FFI_LONGDOUBLE: return ptr_to_jlong(&ffi_type_longdouble); - } - - return ptr_to_jlong(NULL); -} diff --git a/jdk/src/macosx/native/jobjc/src/core/native/FFIType.m b/jdk/src/macosx/native/jobjc/src/core/native/FFIType.m deleted file mode 100644 index 731397e1a01..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/native/FFIType.m +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 - * 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. - */ -#include -#include - -#include "com_apple_jobjc_FFIType.h" - -JNIEXPORT void JNICALL Java_com_apple_jobjc_FFIType_makeFFIType -(JNIEnv *env, jclass clazz, jlong ffi_type_jlong, jlong ffi_type_elements_jlong) -{ - ffi_type *type = jlong_to_ptr(ffi_type_jlong); - type->elements = jlong_to_ptr(ffi_type_elements_jlong); - type->type = FFI_TYPE_STRUCT; - type->size = type->alignment = 0; -} - -JNIEXPORT jint JNICALL Java_com_apple_jobjc_FFIType_getFFITypeSizeof -(JNIEnv *env, jclass clazz) -{ - return (jint) sizeof(ffi_type); -} diff --git a/jdk/src/macosx/native/jobjc/src/core/native/Function.m b/jdk/src/macosx/native/jobjc/src/core/native/Function.m deleted file mode 100644 index 9060a0fd158..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/native/Function.m +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 - * 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. - */ - -#include "com_apple_jobjc_Function.h" - -#define MACOSX -#include -#include - -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_Function_getFxnPtrForFunctionName -(JNIEnv *env, jclass clazz, jstring fxnName) -{ - const char *functionName = (*env)->GetStringUTFChars(env, fxnName, NULL); - void *fxnPtr = dlsym(RTLD_SELF, functionName); - (*env)->ReleaseStringUTFChars(env, fxnName, functionName); - return ptr_to_jlong(fxnPtr); -} - -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_Function_getFxnPtrForFunctionNameAndLib -(JNIEnv *env, jclass clazz, jlong frameworkPtr, jstring fxnName) -{ - void *frameworkHandle = jlong_to_ptr(frameworkPtr); - - const char *functionName = (*env)->GetStringUTFChars(env, fxnName, NULL); - void *fxnPtr = dlsym(frameworkHandle, functionName); - (*env)->ReleaseStringUTFChars(env, fxnName, functionName); - - return ptr_to_jlong(fxnPtr); -} diff --git a/jdk/src/macosx/native/jobjc/src/core/native/Invoke.m b/jdk/src/macosx/native/jobjc/src/core/native/Invoke.m deleted file mode 100644 index 28a11d92d80..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/native/Invoke.m +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -#include "com_apple_jobjc_Invoke_FunCall.h" -#include -#include -#include - -JNIEXPORT void JNICALL Java_com_apple_jobjc_Invoke_00024FunCall_invoke -(JNIEnv *env, jclass clazz, jlong cifPtr, jlong fxnPtr, jlong retValPtr, jlong argsPtr) -{ - ffi_cif *cif = jlong_to_ptr(cifPtr); - void *fxn = jlong_to_ptr(fxnPtr); - void *retVal = jlong_to_ptr(retValPtr); - void **args = jlong_to_ptr(argsPtr); - - ffi_call(cif, fxn, retVal, args); -} diff --git a/jdk/src/macosx/native/jobjc/src/core/native/MacOSXFramework.m b/jdk/src/macosx/native/jobjc/src/core/native/MacOSXFramework.m deleted file mode 100644 index 4609d79fdcd..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/native/MacOSXFramework.m +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 - * 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. - */ - -#include "com_apple_jobjc_MacOSXFramework.h" - -#include -#include - -/* - * Class: com_apple_jobjc_MacOSXFramework - * Method: retainFramework - * Signature: (Ljava/lang/String;)J - */ -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_MacOSXFramework_retainFramework -(JNIEnv *env, jclass clazz, jstring frameworkName) -{ - if (frameworkName == NULL) return ptr_to_jlong(NULL); - const char *frameworkNameCStr = (*env)->GetStringUTFChars(env, frameworkName, JNI_FALSE); - const void *library = dlopen(frameworkNameCStr, RTLD_LOCAL); - (*env)->ReleaseStringUTFChars(env, frameworkName, frameworkNameCStr); - return ptr_to_jlong(library); -} - -/* - * Class: com_apple_jobjc_MacOSXFramework - * Method: releaseFramework - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_com_apple_jobjc_MacOSXFramework_releaseFramework -(JNIEnv *env, jclass clazz, jlong frameworkPtr) -{ - dlclose(jlong_to_ptr(frameworkPtr)); -} - -JNIEXPORT void JNICALL Java_com_apple_jobjc_MacOSXFramework_getConstant -(JNIEnv *env, jclass clazz, jlong frameworkPtr, jstring constSymbol, jlong retBuffer, jint size) -{ - const char *symbol = (*env)->GetStringUTFChars(env, constSymbol, JNI_FALSE); - void *handle = frameworkPtr ? jlong_to_ptr(frameworkPtr) : RTLD_DEFAULT; - void *data = dlsym(handle, symbol); - (*env)->ReleaseStringUTFChars(env, constSymbol, symbol); - - if(!data) - (*env)->ThrowNew(env, (*env)->FindClass(env, "java/lang/RuntimeException"), dlerror()); - else - memcpy(jlong_to_ptr(retBuffer), data, (size_t) size); -} diff --git a/jdk/src/macosx/native/jobjc/src/core/native/NSClass.m b/jdk/src/macosx/native/jobjc/src/core/native/NSClass.m deleted file mode 100644 index 8ae15e3a368..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/native/NSClass.m +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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 - * 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. - */ - -#include "com_apple_jobjc_NSClass.h" -#include - -#include - -/* - * Class: com_apple_jobjc_NSClass - * Method: getNativeClassByName - * Signature: (JLjava/lang/String;)J - */ -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_NSClass_getNativeClassByName -(JNIEnv *env, jclass clazz, jstring className) -{ - if (className == NULL) return ptr_to_jlong(NULL); - const char *classNameCStr = (*env)->GetStringUTFChars(env, className, JNI_FALSE); - const id obj = objc_getClass(classNameCStr); - (*env)->ReleaseStringUTFChars(env, className, classNameCStr); - - if (obj == nil) return ptr_to_jlong(NULL); - return ptr_to_jlong(obj); -} - -/* - * Class: com_apple_jobjc_NSClass - * Method: getSuperClass - * Signature: (J)J - */ -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_NSClass_getSuperClassOfClass -(JNIEnv *env, jclass clazz, jlong clazzPtr) -{ - if (clazzPtr == 0L) return ptr_to_jlong(NULL); - const Class objClazz = (Class)jlong_to_ptr(clazzPtr); - return ptr_to_jlong(class_getSuperclass(objClazz)); -} - -/* - * Class: com_apple_jobjc_NSClass - * Method: getClassName - * Signature: (J)Ljava/lang/String; - */ -JNIEXPORT jstring JNICALL Java_com_apple_jobjc_NSClass_getClassNameOfClass -(JNIEnv *env, jclass clazz, jlong clazzPtr) -{ - const char *clazzName = (char *)class_getName((Class)jlong_to_ptr(clazzPtr)); - return (*env)->NewStringUTF(env, clazzName); -} - -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_NSClass_getClass -(JNIEnv *env, jclass clazz, jlong objPtr) -{ - id obj = (id)jlong_to_ptr(objPtr); - return ptr_to_jlong(object_getClass(obj)); -} diff --git a/jdk/src/macosx/native/jobjc/src/core/native/NativeBuffer.h b/jdk/src/macosx/native/jobjc/src/core/native/NativeBuffer.h deleted file mode 100644 index 0fafa6ef3a8..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/native/NativeBuffer.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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 - * 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. - */ - -/* - * NativeBuffer.h - * Copyright 2007 Apple Inc. All rights reserved. - * - */ - -#define BUFFER_AT(buffer, offset) (((UInt8 *)buffer) + offset) -#define GET_VALUE(type, buffer, offset) (*((type *)BUFFER_AT(buffer, offset))) -#define PUT_VALUE(type, buffer, offset, value) (*((type *)BUFFER_AT(buffer, offset)) = value) - -#define GET_INT_AT(buffer, offset) GET_VALUE(jint, buffer, offset) -#define GET_LONG_AT(buffer, offset) GET_VALUE(jlong, buffer, offset) - -#define PUT_INT_AT(buffer, offset, value) PUT_VALUE(jint, buffer, offset, value) -#define PUT_LONG_AT(buffer, offset, value) PUT_VALUE(jlong, buffer, offset, value) diff --git a/jdk/src/macosx/native/jobjc/src/core/native/NativeObjectLifecycleManager.m b/jdk/src/macosx/native/jobjc/src/core/native/NativeObjectLifecycleManager.m deleted file mode 100644 index 012f83a1d6a..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/native/NativeObjectLifecycleManager.m +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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 - * 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. - */ - -#include "com_apple_jobjc_NativeObjectLifecycleManager.h" - -#include - - -/* - * Class: com_apple_jobjc_NativeObjectLifecycleManager - * Method: retainNativeObject - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_com_apple_jobjc_NativeObjectLifecycleManager_retainNativeObject -(JNIEnv *env, jclass clazz, jlong ptr) -{ - if (ptr == 0L) return; - CFRetain(jlong_to_ptr(ptr)); -} - -/* - * Class: com_apple_jobjc_NativeObjectLifecycleManager - * Method: releaseNativeObject - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_com_apple_jobjc_NativeObjectLifecycleManager_releaseNativeObject -(JNIEnv *env, jclass clazz, jlong ptr) -{ - if (ptr == 0L) return; - CFRelease(jlong_to_ptr(ptr)); -} - -/* - * Class: com_apple_jobjc_NativeObjectLifecycleManager - * Method: freeNativeObject - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_com_apple_jobjc_NativeObjectLifecycleManager_freeNativeObject -(JNIEnv *env, jclass clazz, jlong ptr) -{ - if (ptr == 0L) return; - free(jlong_to_ptr(ptr)); -} diff --git a/jdk/src/macosx/native/jobjc/src/core/native/SEL.m b/jdk/src/macosx/native/jobjc/src/core/native/SEL.m deleted file mode 100644 index dc39ed10132..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/native/SEL.m +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -#include "com_apple_jobjc_SEL.h" - -#include -#include - -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_SEL_getSelectorPtr -(JNIEnv *env, jclass jclazz, jstring selName) -{ - const char *selNameAsChars = (*env)->GetStringUTFChars(env, selName, JNI_FALSE); - const SEL sel = sel_registerName(selNameAsChars); - (*env)->ReleaseStringUTFChars(env, selName, selNameAsChars); - return ptr_to_jlong((void*)sel); -} - -JNIEXPORT jstring JNICALL Java_com_apple_jobjc_SEL_getSelectorName -(JNIEnv *env, jclass jclazz, jlong selPtr) -{ - return (*env)->NewStringUTF(env, sel_getName(jlong_to_ptr(selPtr))); -} diff --git a/jdk/src/macosx/native/jobjc/src/core/native/Subclassing.m b/jdk/src/macosx/native/jobjc/src/core/native/Subclassing.m deleted file mode 100644 index 0e9d4651db8..00000000000 --- a/jdk/src/macosx/native/jobjc/src/core/native/Subclassing.m +++ /dev/null @@ -1,301 +0,0 @@ -/* - * 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 - * 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. - */ - -#include "com_apple_jobjc_Subclassing.h" - -#include -#include -#include - -#include -#include - -#include -#include - -#include - -// Subclassing of Obj-C classes in Java -// -// See: -// - Objective-C Runtime documentation -// - man ffi_prep_closure -// - Subclassing.java - - -#pragma mark Accessing object in IVar - -#define JOBJ_IVAR_NAME "jObjWrapper" -static jobject getJObjectFromIVar(id obj); - -jobject getJObjectFromIVar(id obj) -{ - JNFJObjectWrapper *wrapper = NULL; - object_getInstanceVariable(obj, JOBJ_IVAR_NAME, (void**) &wrapper); - return wrapper ? [wrapper jObject] : NULL; -} - -JNIEXPORT jobject JNICALL Java_com_apple_jobjc_Subclassing_getJObjectFromIVar -(JNIEnv *env, jclass jClass, jlong jPtr) -{ - id obj = (id) jlong_to_ptr(jPtr); - if(obj == NULL){ - (*env)->ThrowNew(env, (*env)->FindClass(env, - "java/lang/NullPointerException"), "obj"); - return NULL; - } - - JNFJObjectWrapper *wrapper; - - if(!object_getInstanceVariable(obj, JOBJ_IVAR_NAME, (void**) &wrapper)){ - NSLog(@"IVar '%s' not found. obj: %@", JOBJ_IVAR_NAME, obj); - (*env)->ThrowNew(env, (*env)->FindClass(env, "java/lang/RuntimeException"), - "Could not find instance variable that holds Java object."); - return NULL; - } - - return wrapper ? [wrapper jObject] : NULL; -} - -JNIEXPORT void JNICALL Java_com_apple_jobjc_Subclassing_initJObjectToIVar -(JNIEnv *env, jclass jClass, jlong jPtr, jobject jObject) -{ - id obj = (id) jlong_to_ptr(jPtr); - JNFJObjectWrapper *wrapper = [[JNFJObjectWrapper alloc] - initWithJObject:jObject withEnv:env]; - [wrapper retain]; - - if(!object_setInstanceVariable(obj, JOBJ_IVAR_NAME, wrapper)){ - NSLog(@"IVar '%s' not found. obj: %@", JOBJ_IVAR_NAME, obj); - (*env)->ThrowNew(env, (*env)->FindClass(env, "java/lang/RuntimeException"), - "Could not find instance variable that holds Java object."); - return; - } -} - -#pragma mark Registering class - -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_Subclassing_allocateClassPair -(JNIEnv *env, jclass clazz, jlong jSuperClass, jstring jName) -{ - const Class superClass = (Class)jlong_to_ptr(jSuperClass); - assert(superClass); - - const char *name = (*env)->GetStringUTFChars(env, jName, JNI_FALSE); - const Class newClass = objc_allocateClassPair(superClass, name, 0); - (*env)->ReleaseStringUTFChars(env, jName, name); - - return ptr_to_jlong(newClass); -} - -JNIEXPORT jboolean JNICALL Java_com_apple_jobjc_Subclassing_addIVarForJObj -(JNIEnv *env, jclass clazz, jlong jSynthClass) -{ - return class_addIvar( - jlong_to_ptr(jSynthClass), - JOBJ_IVAR_NAME, - sizeof(id), - (uint8_t)log2((double)sizeof(id)), - "@"); -} - -JNIEXPORT void JNICALL Java_com_apple_jobjc_Subclassing_registerClassPair -(JNIEnv *env, jclass clazz, jlong jClass) -{ - Class c = jlong_to_ptr(jClass); -// NSLog(@"Registering class pair %p / %s", c, class_getName(c)); - objc_registerClassPair(c); -} - - -#pragma mark Patching +alloc - -static id patchedAllocIMP(id obj, SEL sel); -static void addJavaInstance(id obj); - -JNIEXPORT jboolean JNICALL Java_com_apple_jobjc_Subclassing_patchAlloc -(JNIEnv *env, jclass clazz, jlong jNativeClass) -{ - Class metaClass = object_getClass(jlong_to_ptr(jNativeClass)); - return class_addMethod(metaClass, - sel_registerName("alloc"), - (IMP) patchedAllocIMP, - "@@:"); -} - -static id patchedAllocIMP(id cls, SEL sel){ - id inst = class_createInstance(cls, 0); - addJavaInstance(inst); - return inst; -} - -static void addJavaInstance(id obj){ -// NSLog(@"addJavaInstance %p", obj); -// NSLog(@"... calling up to Java"); - - static JNF_CLASS_CACHE(jc_Subclassing, "com/apple/jobjc/Subclassing"); - static JNF_STATIC_MEMBER_CACHE(jm_Subclassing_initJObject, - jc_Subclassing, - "initJObject", - "(J)V"); - - JNFThreadContext threadWasAttached = JNFThreadDetachOnThreadDeath; - JNIEnv *env = JNFObtainEnv(&threadWasAttached); - JNFCallStaticVoidMethod(env, jm_Subclassing_initJObject, - ptr_to_jlong(obj)); - - JNFReleaseEnv(env, &threadWasAttached); -} - - -#pragma mark Adding methods - -static ffi_closure *make_closure(ffi_cif *cif, void *user_data); -static void sel_closure_call(ffi_cif* cif, void* result, void** args, void* user_data); - -typedef struct closure_data_t{ - JNFJObjectWrapper *jMethod; - JNFJObjectWrapper *jCIF; -} closure_data_t; - -static ffi_closure *make_closure(ffi_cif *cif, void *user_data){ - // Allocate a page to hold the closure with read and write permissions. - ffi_closure *closure; - if ((closure = mmap(NULL, sizeof(ffi_closure), PROT_READ | PROT_WRITE, - MAP_ANON | MAP_PRIVATE, -1, (off_t) 0)) == (void*)-1) - { - fprintf(stderr, "mmap failed with errno: %d", errno); - return NULL; - } - - // Prepare the ffi_closure structure. - ffi_status status; - if ((status = ffi_prep_closure(closure, cif, sel_closure_call, (void *)user_data)) != FFI_OK) - { - fprintf(stderr, "ffi_prep_closure failed with ffi_status: %d", status); - munmap(closure, sizeof(ffi_closure)); - return NULL; - } - - // Ensure that the closure will execute on all architectures. - if (mprotect(closure, sizeof(closure), PROT_READ | PROT_EXEC) == -1) - { - fprintf(stderr, "mprotect failed with errno: %d", errno); - munmap(closure, sizeof(ffi_closure)); - return NULL; - } - return closure; -} - -JNIEXPORT jboolean JNICALL Java_com_apple_jobjc_Subclassing_addMethod -(JNIEnv *env, jclass clazz, jlong jClass, jstring jSelName, jobject jMethod, - jobject jCIF, jlong jCIFPtr, jstring jObjCEncodedType) -{ - ffi_cif *cif = jlong_to_ptr(jCIFPtr); - - closure_data_t *user_data = malloc(sizeof(closure_data_t)); - user_data->jMethod = [[JNFJObjectWrapper alloc] initWithJObject:jMethod withEnv:env]; - user_data->jCIF = [[JNFJObjectWrapper alloc] initWithJObject:jCIF withEnv:env]; - - ffi_closure *closure;; - if(!(closure = make_closure(cif, user_data))){ - [user_data->jMethod release]; - [user_data->jCIF release]; - free(user_data); - return NO; - } - - const Class objcClass = (Class)jlong_to_ptr(jClass); - - const char *selName = (*env)->GetStringUTFChars(env, jSelName, JNI_FALSE); - const char *objCEncodedType = (*env)->GetStringUTFChars(env, jObjCEncodedType, JNI_FALSE); - -// NSLog(@"Adding method '%s' :: '%s' to '%s' / %p", -// selName, -// objCEncodedType, -// class_getName(objcClass), -// objcClass); - - BOOL ret = class_addMethod(objcClass, sel_registerName(selName), (IMP) closure, objCEncodedType); - - (*env)->ReleaseStringUTFChars(env, jSelName, selName); - (*env)->ReleaseStringUTFChars(env, jObjCEncodedType, objCEncodedType); - - if(!ret){ - NSLog(@"class_addMethod failed"); - munmap(closure, sizeof(ffi_closure)); - [user_data->jMethod release]; - [user_data->jCIF release]; - free(user_data); - return NO; - } - - return ret; -} - -static void sel_closure_call(ffi_cif* cif, void* result, void** args, void* user_data) -{ - id obj = *(id*) args[0]; -// SEL sel = *(SEL*) args[1]; - -// NSLog(@"Subclassing: sel_closure_call: %p %p", obj, sel); -// NSLog(@"Subclassing: sel_closure_call: obj class: %@ sel name: %s", object_getClass(obj), sel_getName(sel)); - - jobject jObj = getJObjectFromIVar(obj); - - if(!jObj){ - addJavaInstance(obj); - jObj = getJObjectFromIVar(obj); - } - - closure_data_t *jmeta = user_data; - jobject jMethod = [jmeta->jMethod jObject]; - jobject jCIF = [jmeta->jCIF jObject]; - - JNFThreadContext threadWasAttached = JNFThreadDetachOnThreadDeath; - JNIEnv *env = JNFObtainEnv(&threadWasAttached); - - if((*env)->ExceptionOccurred(env)) goto bail; - - static JNF_CLASS_CACHE(jc, "com/apple/jobjc/Subclassing"); - static JNF_STATIC_MEMBER_CACHE(jm_invokeFromJNI, jc, "invokeFromJNI", - "(Lcom/apple/jobjc/ID;Ljava/lang/reflect/Method;Lcom/apple/jobjc/CIF;JJ)V"); - - JNFCallStaticVoidMethod(env, jm_invokeFromJNI, - jObj, - jMethod, - jCIF, - ptr_to_jlong(result), - ptr_to_jlong(args)); - -bail: - JNFReleaseEnv(env, &threadWasAttached); - - if((*env)->ExceptionOccurred(env)){ - NSLog(@"Exception!"); - (*env)->ExceptionDescribe(env); - } - JNFReleaseEnv(env, &threadWasAttached); -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/BootClassPathMinus.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/BootClassPathMinus.java deleted file mode 100644 index efbad58a104..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/BootClassPathMinus.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator; - -public class BootClassPathMinus { - - /* - * return the default boot class path with all parts mentioned in arguments removed - */ - public static void main(String[] args) { - String bootClassPath = System.getProperty("sun.boot.class.path"); - StringBuffer newPath = new StringBuffer(bootClassPath.length()); - String[] bootClassPathParts = bootClassPath.split(java.io.File.pathSeparator, 0); - for (String part : bootClassPathParts) { - boolean found = false; - for (String minus : args) { - if (part.endsWith(minus)) { - found = true; - } - } - if (!found) { - if (newPath.length() > 0) newPath.append(java.io.File.pathSeparatorChar); - newPath.append(part); - } - } - System.out.println(newPath.toString()); - } - -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/ClassConsolidator.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/ClassConsolidator.java deleted file mode 100644 index 69a872f8dbc..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/ClassConsolidator.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.apple.internal.jobjc.generator.model.Category; -import com.apple.internal.jobjc.generator.model.Clazz; -import com.apple.internal.jobjc.generator.model.Framework; - -public class ClassConsolidator { - private static String[] PREFERRED_FRAMEWORKS = { "Foundation", "AppKit" }; - - static void consolidateClassesForFrameworks(final List frameworks) throws Throwable { - System.out.println("--2-- Resolving duplicate classes:"); - final Map> allClasses = new HashMap>(); - - for (final Framework framework : frameworks) { - for (final Clazz clazz : framework.classes) { - final List existingClazzList = allClasses.get(clazz.name); - if(existingClazzList != null) - existingClazzList.add(clazz); - else - allClasses.put(clazz.name, new ArrayList(Arrays.asList(clazz))); - } - } - - final Map filteredClasses = new HashMap(); - final List> dreggs = new ArrayList>(); - - final Collection> clazzLists = allClasses.values(); - for (final List clazzList : clazzLists) { - if (clazzList.size() > 1) { - // add to the list for later analysis - dreggs.add(clazzList); - continue; - } - - // if there is only one class definition, go with it! - final Clazz clazz = clazzList.get(0); - filteredClasses.put(clazz.name, clazz); - } - - // figure out which class is the real class, and convert the rest to categories - for (final List dreg : dreggs) - deriveCategoriesFrom(dreg, filteredClasses); - - // patch up the inheritance hierarchy - System.out.println("Determining super classes:"); - for (final Framework framework : frameworks) - framework.resolveSuperClasses(filteredClasses); - } - - private static void deriveCategoriesFrom(final List clazzes, final Map filteredClasses) { - final List clazzesToDerive = new ArrayList(clazzes); - - for (final String preferredFrameworkName : PREFERRED_FRAMEWORKS) { - for (final Clazz clazz : clazzesToDerive) { - if (!preferredFrameworkName.equals(clazz.parent.name)) continue; - - System.out.print("\t" + clazz.parent.name + " owns \"" + clazz.name + "\", "); - addCategoriesAndPatchClasses(clazzes, clazz); - filteredClasses.put(clazz.name, clazz); - return; - } - } - - final List frameworkNameList = new ArrayList(clazzes.size()); - for (final Clazz clazz : clazzes) frameworkNameList.add(clazz.parent.name); - throw new RuntimeException("Could not derived a preferred framework for: " + clazzes.get(0).name + ", from (" + Utils.joinWComma(frameworkNameList) + ")"); - } - - private static void addCategoriesAndPatchClasses(final List clazzes, final Clazz clazz) { - final List fwNames = new ArrayList(clazzes.size()); - - for (final Clazz cls : clazzes) { - if (cls == clazz) continue; - fwNames.add(cls.parent.name); - cls.parent.classes.remove(cls); - cls.parent.categories.add(new Category(cls, clazz)); - } - - System.out.println("creating categories in: " + Utils.joinWComma(fwNames)); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/FileCopier.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/FileCopier.java deleted file mode 100644 index bcaf5bcb8c7..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/FileCopier.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator; - -import java.io.File; -import java.util.*; - -import com.apple.internal.jobjc.generator.classes.*; - -public class FileCopier { - public static List addSourceFilesFrom(final String srcPath) { - final List outputFileList = new ArrayList(); - - final List fileList = getFileList(srcPath); - for (final File file : fileList) { - outputFileList.add(new CopiedFile(file, ClassGenerator.JOBJC_PACKAGE, file.getName().replace("\\.java", ""))); - } - - return outputFileList; - } - - private static List getFileList(final String srcPath) { - final File srcRoot = new File(srcPath); - if (!srcRoot.exists()) throw new RuntimeException("Source root " + srcRoot + " does not exist. Nowhere to copy base runtime objects from."); - - final File targetDir = new File(srcRoot, ClassGenerator.JOBJC_PACKAGE.replaceAll("\\.", "\\/")); - if (!targetDir.exists() || !targetDir.isDirectory()) throw new RuntimeException("Base runtime object source directory " + targetDir + " does not exist. No runtime class files to copy."); - - final List fileList = new ArrayList(); - final File[] targetDirFileList = targetDir.listFiles(); - for (final File file : targetDirFileList) { - if (!file.isFile()) continue; - if (!file.getName().endsWith(".java")) continue; - fileList.add(file); - } - - return fileList; - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/FrameworkGenerator.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/FrameworkGenerator.java deleted file mode 100644 index 1f11ed9038b..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/FrameworkGenerator.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.apple.internal.jobjc.generator.model.Framework; -import com.apple.internal.jobjc.generator.model.Framework.FrameworkDependency; -import com.apple.internal.jobjc.generator.utils.Fp; -import com.apple.internal.jobjc.generator.utils.StructOffsetResolverBigBang; -import com.apple.jobjc.JObjCRuntime; - -public class FrameworkGenerator { - private static final String BRIDGESUPPORT_FILE_EXTENSION = "Full.bridgesupport"; - private static final String FRAMEWORK_MATCH = "^.*Full\\.bridgesupport$"; - private static final String FRAMEWORK_PRUNE = "^.*(PyObjC|/Versions|\\.lproj|/Headers|/PrivateHeaders).*$"; - - static List findFrameworkFilesIn(final File file) throws IOException{ - final List bridgeSupportFiles = Utils.find(file, FRAMEWORK_MATCH, FRAMEWORK_PRUNE); - System.out.println("found " + bridgeSupportFiles.size() + " frameworks"); - return bridgeSupportFiles; - } - - static List parseFrameworksFrom(final List bridgeSupportFiles) { - final List frameworks = new ArrayList(); - - System.out.println("Parsing XML"); - for (final File file : bridgeSupportFiles){ - Framework f = new Framework(extractFrameworkNameFrom(file), file); - try{ - f.load(); - frameworks.add(f); - System.out.println("Generator@" + JObjCRuntime.ARCH + " loaded " - + f.name + " (" + Fp.join(":", f.binaries) + ")"); - } - catch(Exception x){ - System.out.println("!! Generator@" + JObjCRuntime.ARCH + " failed to load " - + f.name + " (" + Fp.join(":", f.binaries) + "). SKIPPING"); - } - } - - System.out.println("Parsing dependencies"); - for (final Framework f : frameworks) f.parseDependencies(frameworks); - - Set alreadyWarnedDependency = new HashSet(); - for(final Framework f : frameworks) - for(final FrameworkDependency dep : f.dependencies) - if(dep.object == null && !alreadyWarnedDependency.contains(dep.name)){ - System.out.println(String.format("Warning: unresolved dependency: %1$30s -> %2$s", f.name, dep.name)); - alreadyWarnedDependency.add(dep.name); - } - if(alreadyWarnedDependency.size() > 0) - System.out.println("Unresolved dependencies lead to unresolved types."); - - Utils.topologicalSort(frameworks); - List cycle = Utils.getDependencyCycle(frameworks); - if(cycle != null) - System.out.println("Warning: cycle found in framework dependencies: " + Fp.join(" -> ", cycle)); - - System.out.println("Parsing types"); - for (final Framework f : frameworks){ - f.parseCFTypes(); - f.parseOpaques(); - } - for (final Framework f : frameworks) f.parseStructs(); - - new StructOffsetResolverBigBang().resolve(frameworks); - - System.out.println("Parsing classes"); - for (final Framework f : frameworks) f.parseClasses(); - - System.out.println("Parsing constants"); - for (final Framework f : frameworks) f.parseConstants(); - - System.out.println("Parsing functions"); - for (final Framework f : frameworks) f.parseFunctions(); - - return frameworks; - } - - private static String extractFrameworkNameFrom(final File file) { - final String fileName = file.getName(); - return fileName.substring(0, fileName.lastIndexOf(BRIDGESUPPORT_FILE_EXTENSION)); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/FunctionGenerator.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/FunctionGenerator.java deleted file mode 100644 index 37f67aa39bd..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/FunctionGenerator.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator; - -import java.io.PrintStream; -import java.io.StringWriter; - -import com.apple.internal.jobjc.generator.model.Arg; -import com.apple.internal.jobjc.generator.model.Function; -import com.apple.internal.jobjc.generator.model.Method; -import com.apple.internal.jobjc.generator.model.types.JType; -import com.apple.internal.jobjc.generator.utils.JavaLang.JLCall; -import com.apple.internal.jobjc.generator.utils.JavaLang.JLField; -import com.apple.internal.jobjc.generator.utils.JavaLang.JLMethod; -import com.apple.internal.jobjc.generator.utils.JavaLang.JLTertiary; -import com.apple.jobjc.Coder; -import com.apple.jobjc.Invoke; -import com.apple.jobjc.Invoke.FunCall; -import com.apple.jobjc.Invoke.MsgSend; - -public class FunctionGenerator { - private final static String VARARGS_NAME = "varargs"; - - private static String createFieldCache(final Class type, final Function fxn) { - final String identifier = makeInstanceName(fxn); - - JLField field = new JLField("private static", type.getCanonicalName(), identifier); - // It's okay to make it static, because the getter isn't static, so the only way to access it is through an instance. - JLMethod getter = new JLMethod("private final", type.getCanonicalName(), "get_" + identifier); - - JLCall createIt = new JLCall("new " + type.getCanonicalName()); - createIt.args.add(firstArg(fxn)); - createIt.args.add("\"" + fxn.name + "\""); - createIt.args.add(fxn.returnValue.type.getJType().getCoderDescriptor().getCoderInstanceName()); - for (final Arg arg : fxn.args) - createIt.args.add(arg.type.getJType().getCoderDescriptor().getCoderInstanceName()); - - getter.body.add("return " + new JLTertiary(identifier + " != null", identifier, identifier + " = " + createIt) + ";"); - - return field.toString() + getter.toString(); - } - - private static String createLocalForward(final Class type, final Function fxn) { - final String identifier = makeInstanceName(fxn); - return new JLField("final", type.getCanonicalName(), identifier, new JLCall("get_" + identifier)).toString(); - } - - private static String createLocalNew(final Class type, final Function fxn) { - final String identifier = makeInstanceName(fxn); - StringWriter out = new StringWriter(); - - out.append(String.format("%3$s[] argCoders = new %3$s[%1$d + %2$s.length];\n", fxn.args.size(), VARARGS_NAME, Coder.class.getCanonicalName())); - - for(int i = 0; i < fxn.args.size(); i++) - out.append(String.format("argCoders[%1$d] = %2$s;\n", i, fxn.args.get(0).type.getJType().getCoderDescriptor().getCoderInstanceName())); - - if(fxn.variadic){ - out.append(String.format("for(int i = %1$d; i < (%1$d + %2$s.length); i++)\n", fxn.args.size(), VARARGS_NAME)); - out.append(String.format("\targCoders[i] = %1$s.getCoderAtRuntime(%2$s[i - %3$s]);\n", Coder.class.getCanonicalName(), VARARGS_NAME, fxn.args.size())); - } - - out.append("final " + type.getCanonicalName() + " " + identifier + " = new " + type.getCanonicalName() + "(" + firstArg(fxn) + ", \"" + fxn.name + "\", " - + fxn.returnValue.type.getJType().getCoderDescriptor().getCoderInstanceName() + ", argCoders);"); - - return out.toString(); - } - - private static final String CONTEXT_NAME = "nativeBuffer"; - - public static void writeOutFunction(final PrintStream out, final Class type, final Function fxn, final String initWithObj) { - final String instName = makeInstanceName(fxn); - final JType returnJavaType = fxn.returnValue.type.getJType(); - - if(!fxn.variadic){ - out.print(createFieldCache(type, fxn)); - out.println(); - } - - JLMethod meth = new JLMethod("public", returnJavaType.getJavaReturnTypeName(), fxn.getJavaName()); - - for(Arg arg : fxn.args) - meth.args.add("final " + arg.type.getJType().getTypeNameAsParam() + " " + arg.javaName); - - if(fxn.variadic) - meth.args.add("final Object... " + VARARGS_NAME); - - if(fxn instanceof Method && ((Method)fxn).ignore){ - String suggestion = ((Method)fxn).suggestion == null ? "" : (" Suggested work-around: " + ((Method)fxn).suggestion); - meth.jdoc.add("@deprecated The framework recommends that this method be ignored. (It may be deprecated.)" + suggestion); - meth.attrs.add("@Deprecated"); - } - - // type mismatch warning - { - { - String retMsg = fxn.returnValue.type.getJType().getCoderDescriptor().mismatchMessage(); - if(retMsg != null){ - meth.jdoc.add("@deprecated Possible type mismatch: (return value) " + retMsg); - meth.attrs.add("@Deprecated"); - } - } - - for(int i = 0; i < fxn.args.size(); i++){ - final Arg arg = fxn.args.get(i); - String argMsg = arg.type.getJType().getCoderDescriptor().mismatchMessage(); - if(argMsg != null){ - meth.jdoc.add("@deprecated Possible type mismatch: (arg" + i + ": " + arg.javaName + ") " + argMsg); - meth.attrs.add("@Deprecated"); - } - } - } - - if(fxn.variadic) - meth.body.add(createLocalNew(coreType(fxn), fxn)); - else - meth.body.add(createLocalForward(coreType(fxn), fxn)); - - meth.body.add(returnJavaType.createDeclareBuffer(CONTEXT_NAME)); - meth.body.add(returnJavaType.createInit(CONTEXT_NAME, instName, initWithObj)); - - for(final Arg arg : fxn.args) - meth.body.add(arg.type.getJType().getCoderDescriptor().getPushStatementFor(CONTEXT_NAME, arg.javaName)); - - if(fxn.variadic){ - meth.body.add(String.format("for(int i = %1$d; i < (%1$d + %2$s.length); i++)", fxn.args.size(), VARARGS_NAME)); - meth.body.add(String.format("\targCoders[i].push(%1$s, %2$s[i - %3$d]);", CONTEXT_NAME, VARARGS_NAME, fxn.args.size())); - } - - meth.body.add(returnJavaType.createInvoke(CONTEXT_NAME, instName)); - meth.body.add(returnJavaType.createPop(CONTEXT_NAME)); - meth.body.add(returnJavaType.createReturn()); - - out.print(meth.toString()); - out.println(); - } - - private static Class coreType(final Function fxn){ - return fxn instanceof Method ? MsgSend.class : FunCall.class; - } - - private static String firstArg(Function fxn){ - return fxn instanceof Method ? "getRuntime()" : "this"; - } - - private static String makeInstanceName(Function fxn){ - String ext; - if(fxn instanceof Method){ - if(((Method) fxn).isClassMethod) ext = "CMetInst"; - else ext = "IMetInst"; - } - else - ext = "FxnInst"; - - return fxn.getJavaName() + "_" + ext; - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/Generator.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/Generator.java deleted file mode 100644 index f1411e83e7d..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/Generator.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator; - -import java.io.File; -import java.util.List; -import java.util.Map; - -import com.apple.internal.jobjc.generator.classes.MixedPrimitiveCoderClassFile; -import com.apple.internal.jobjc.generator.classes.OutputFile; -import com.apple.internal.jobjc.generator.model.Framework; -import com.apple.internal.jobjc.generator.model.coders.ComplexCoderDescriptor; -import com.apple.internal.jobjc.generator.model.types.Type; -import com.apple.internal.jobjc.generator.model.types.TypeCache; -import com.apple.internal.jobjc.generator.utils.Fp.Pair; - -public class Generator { - private static final String DEFAULT_FRAMEWORKS_PATH = "/System/Library/Frameworks"; - private static final String DEFAULT_OUTPUT_PATH = "/tmp/JObjC"; - - public static void main(final String...args) throws Throwable { - final Map argMap = Utils.getArgs(args); - - final String dst = get(argMap, "dst", DEFAULT_OUTPUT_PATH); - System.out.println("Cleaning up: " + dst); - final File dstLoc = new File(dst); - Utils.recDelete(dstLoc); - dstLoc.mkdirs(); - System.out.println("Outputting classes to: " + dst); - - final String frameworksPath = get(argMap, "frameworks", DEFAULT_FRAMEWORKS_PATH); - System.out.println("Searching for bridged frameworks in: " + frameworksPath); - - final List bridgeSupportFiles = FrameworkGenerator.findFrameworkFilesIn(new File(frameworksPath)); - final List frameworks = FrameworkGenerator.parseFrameworksFrom(bridgeSupportFiles); - - System.out.println("--1-- Generator: consolidateClassesForFrameworks"); - ClassConsolidator.consolidateClassesForFrameworks(frameworks); - - System.out.println("--1-- Generator: TypeCache load"); - TypeCache.inst().load(frameworks); - - System.out.println("--1-- Generator: disambiguateMethodNames"); - MethodDisambiguator.disambiguateMethodNames(); - - System.out.println("--1-- Generator: disambiguateFunctionsIn"); - MethodDisambiguator.disambiguateFunctionsIn(frameworks); - - System.out.println("--1-- Generator: generateClasses"); - final List sourceFiles = ClassGenerator.generateClasses(frameworks); - sourceFiles.add(new MixedPrimitiveCoderClassFile(ComplexCoderDescriptor.getMixedEncoders())); - - System.out.println("--1-- Generator: writing " + sourceFiles.size() + " files"); - for (final OutputFile sourceFile : sourceFiles) sourceFile.write(dstLoc); - - System.out.println("I have " + TypeCache.inst().getUnknownTypes().size() + " unresolved types."); - for (final Type type : TypeCache.inst().getUnknownTypes()) - System.out.println("[Warning] unknown type: " + type); - - for(Type type : TypeCache.inst().typesByNTypes.values()){ - if(!type.type32.getClass().equals(type.type64.getClass())){ - System.out.format("Type with differing NTypes: %1$15s: %2$s\n", type.name, new Pair(type.type32, type.type64)); - } - } - } - - private static String get(final Map defaults, final String key, final String defaultValue) { - final String value = defaults.get(key); - if (value != null) return value; - return defaultValue; - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/MethodDisambiguator.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/MethodDisambiguator.java deleted file mode 100644 index 5b8bcb2ec79..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/MethodDisambiguator.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator; - -import java.util.List; - -import com.apple.internal.jobjc.generator.model.Clazz; -import com.apple.internal.jobjc.generator.model.Framework; -import com.apple.internal.jobjc.generator.model.Function; -import com.apple.internal.jobjc.generator.model.types.TypeCache; - -public class MethodDisambiguator { - static void disambiguateMethodNames() { - // link all subclassers off their parents - for (final Clazz clazz : TypeCache.inst().getAllClasses()) { - final Clazz superClazz = clazz.superClass; - if (superClazz != null) superClazz.subClassers.add(clazz); - } - - // recursively call all subclassers, starting from NSObject on down - disambiguateMethodNamesFor(TypeCache.inst().getClassForName("NSObject")); - - // NSProxy does not appear to subclass from NSObject, but it is still a real full class...? - disambiguateMethodNamesFor(TypeCache.inst().getClassForName("NSProxy")); - } - - static void disambiguateMethodNamesFor(final Clazz clazz) { - clazz.disambiguateMethods(); - for (final Clazz subClazz : clazz.subClassers) { - disambiguateMethodNamesFor(subClazz); - } - } - - public static void disambiguateFunctionsIn(final List frameworks) { - for (final Framework framework : frameworks) { - disambiguateFunctionsInFramework(framework); - } - } - - static void disambiguateFunctionsInFramework(final Framework framework) { - for (final Function fxn : framework.functions) - fxn.disambiguateArgs(); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/RestrictedKeywords.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/RestrictedKeywords.java deleted file mode 100644 index aeaaeee548a..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/RestrictedKeywords.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -public class RestrictedKeywords { - static final String[] JAVA_KEYWORD_CONFLICTS = { - "wait", "null", "class", "new", "toString", "finalize", "boolean", "interface", "final", "static" - }; - - static final Set originalRestrictedSet = new HashSet(Arrays.asList(JAVA_KEYWORD_CONFLICTS)); - - public static Set getNewRestrictedSet() { - return new HashSet(originalRestrictedSet); - } - - public static boolean isRestricted(String s){ - return originalRestrictedSet.contains(s); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/Utils.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/Utils.java deleted file mode 100644 index 7a3459c2164..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/Utils.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.regex.Pattern; - -import com.apple.internal.jobjc.generator.model.Framework; -import com.apple.internal.jobjc.generator.model.Framework.FrameworkDependency; -import com.apple.internal.jobjc.generator.utils.Fp; - -public class Utils { - public static boolean isLeopard = System.getProperty("os.version").startsWith("10.5"); - public static boolean isSnowLeopard = System.getProperty("os.version").startsWith("10.6"); - - @SuppressWarnings("unchecked") - public static List list(final Object...args) { - final ArrayList list = new ArrayList(args.length); - for (final Object arg : args) list.add(arg); - return (List)list; - } - - /** - * A small implementation of UNIX find. - * @param matchRegex Only collect paths that match this regex. - * @param pruneRegex Don't recurse down a path that matches this regex. May be null. - * @throws IOException if File.getCanonicalPath() fails. - */ - public static List find(final File startpath, final String matchRegex, final String pruneRegex) throws IOException{ - final Pattern matchPattern = Pattern.compile(matchRegex, Pattern.CASE_INSENSITIVE); - final Pattern prunePattern = pruneRegex == null ? null : Pattern.compile(pruneRegex, Pattern.CASE_INSENSITIVE); - final Set visited = new HashSet(); - final List found = new ArrayList(); - class Search{ - void search(final File path) throws IOException{ - if(prunePattern != null && prunePattern.matcher(path.getAbsolutePath()).matches()) return; - String cpath = path.getCanonicalPath(); - if(!visited.add(cpath)) return; - if(matchPattern.matcher(path.getAbsolutePath()).matches()) - found.add(path); - if(path.isDirectory()) - for(File sub : path.listFiles()) - search(sub); - } - } - new Search().search(startpath); - return found; - } - - public static String joinWComma(final List list) { return Fp.join(", ", list); } - public static String joinWComma(final Object[] list) { return Fp.join(", ", Arrays.asList(list)); } - - public static class Substituter { - String str; - - public Substituter(final String str) { - this.str = str.replaceAll("\\#", "\t").replaceAll("\\~", "\n"); - } - - public void replace(final String key, final String value) { - str = str.replaceAll("\\$" + key, value); - } - - /** - * Apply String.format first, and then pass through Substituter. - */ - public static String format(String format, Object... args){ - return new Substituter(String.format(format, args)).toString(); - } - - @Override public String toString() { - return str; - } - } - - static Map getArgs(final String...args) { - final Map argMap = new HashMap(); - for (final String arg : args) { - final String[] splitArg = arg.split("\\="); - if (splitArg.length != 2) continue; - argMap.put(splitArg[0], splitArg[1]); - } - return argMap; - } - - static void recDelete(final File file) { - if (!file.exists()) return; - if (file.isDirectory()) for (final File f : file.listFiles()) recDelete(f); - file.delete(); - } - - public static String capitalize(String s){ - if(s.length() == 0) return s; - return Character.toString(Character.toUpperCase(s.charAt(0))) + s.substring(1); - } - - /** - * Sort frameworks by dependencies. If A is a dependency of B, - * then A will come before B in the list. - */ - public static void topologicalSort(final List frameworks) { - final Set visited = new TreeSet(); - final List sorted = new ArrayList(frameworks.size()); - class Rec{ - void visit(final Framework fw){ - if(!visited.add(fw)) return; - for(FrameworkDependency dep : fw.dependencies) - if(dep.object != null) - visit(dep.object); - sorted.add(fw); - } - } - for(Framework fw : frameworks) new Rec().visit(fw); - frameworks.clear(); - frameworks.addAll(sorted); - } - - /** - * If there is a cycle it is returned. Otherwise null is returned. - */ - public static List getDependencyCycle(List frameworks) { - @SuppressWarnings("serial") - class FoundCycle extends Throwable{ - public final List cycle; - public FoundCycle(List cycle){ - this.cycle = cycle; - } - }; - class Rec{ - void visit(final Framework fw, List visited) throws FoundCycle{ - visited = new LinkedList(visited); - if(visited.contains(fw)){ - visited.add(fw); - throw new FoundCycle(visited); - } - visited.add(fw); - for(FrameworkDependency dep : fw.dependencies) - if(dep.object != null) - visit(dep.object, visited); - } - } - try{ for(Framework fw : frameworks){ new Rec().visit(fw, new LinkedList()); }} - catch(FoundCycle x){ return x.cycle; } - return null; - } - - public static String getCanonicalPath(File file) throws RuntimeException{ - try { - return file.getCanonicalPath(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/CFTypeClassFile.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/CFTypeClassFile.java deleted file mode 100644 index 774cae18e6e..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/CFTypeClassFile.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.PrintStream; - -import com.apple.internal.jobjc.generator.model.CFType; -import com.apple.jobjc.Pointer; - -public class CFTypeClassFile extends GeneratedClassFile { - final CFType cftype; - - public CFTypeClassFile(final CFType cftype) { - super(cftype.parent.pkg, cftype.type.getJType().getJavaClassName(), com.apple.jobjc.CFType.class.getCanonicalName()); - this.cftype = cftype; - } - - @Override public void writeBeginning(PrintStream out){ - out.println("\tpublic " + className + "(" + Pointer.class.getName() + " ptr){"); - out.println("\t\tsuper(ptr);"); - out.println("\t}"); - out.println(""); - out.println("\tpublic " + className + "(long ptr){"); - out.println("\t\tsuper(ptr);"); - out.println("\t}"); - } - - @Override public void writeBody(PrintStream out){ - if(cftype.getTypeIdFunc != null){ - out.println("\tpublic static long getTypeId(){"); - out.println("\t\treturn " + RootJObjCClass.runtimeFrameworkInst(cftype.parent.name) + "." + cftype.getTypeIdFunc + "();"); - out.println("\t}"); - } - else - out.println("\t// getTypeIdFunc not found"); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/CategoryClassClassFile.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/CategoryClassClassFile.java deleted file mode 100644 index f89c24320cf..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/CategoryClassClassFile.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.PrintStream; -import java.util.HashSet; -import java.util.Set; - -import com.apple.internal.jobjc.generator.FunctionGenerator; -import com.apple.internal.jobjc.generator.model.Category; -import com.apple.internal.jobjc.generator.model.Method; -import com.apple.jobjc.JObjCRuntime; -import com.apple.jobjc.Invoke.MsgSend; - -public class CategoryClassClassFile extends AbstractObjCClassFile { - final Category category; - - public CategoryClassClassFile(final Category category) { - super(category.category, category.category.name + "Class", - category.category.superClass.getFullPath() + "Class"); - this.category = category; - } - - @Override public void writeBeginning(final PrintStream out) { - out.format( - "\t%1$s(%2$s runtime) {\n" + - "\t\tsuper(\"%3$s\", runtime);\n" + - "\t}\n", - className, JObjCRuntime.class.getCanonicalName(), category.category.superClass.name); - } - - @Override public void writeBody(final PrintStream out) { - Set written = new HashSet(); - for(final Method method : this.clazz.classMethods) - if(written.add(method.name)) - FunctionGenerator.writeOutFunction(out, MsgSend.class, method, "this"); - else - System.out.format("Duplicate method: %1$s %2$s -%3$s\n", clazz.parent.name, className, method.name); - } - - @Override protected boolean isFinal(){ return true; } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/CategoryClassFile.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/CategoryClassFile.java deleted file mode 100644 index c858546d092..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/CategoryClassFile.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.PrintStream; - -import com.apple.internal.jobjc.generator.model.Category; -import com.apple.jobjc.JObjCRuntime; - -public class CategoryClassFile extends JObjCClassFile { - private final Category category; - - public CategoryClassFile(final Category category) { - super(category.category); - this.category = category; - } - - @Override public void writeBeginning(final PrintStream out) { - String targetCls = category.category.superClass.getFullPath(); - out.format("\tpublic %1$s(final %2$s obj, final %3$s runtime) {\n" + - "\t\tsuper(obj, runtime);\n" + - "\t}\n", - className, targetCls, JObjCRuntime.class.getCanonicalName()); - super.writeBeginning(out); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/CopiedFile.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/CopiedFile.java deleted file mode 100644 index 7061b86be92..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/CopiedFile.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.*; - -public class CopiedFile extends OutputFile { - final File sourceFile; - - public CopiedFile(final File sourceFile, final String pkg, final String filename) { - super(pkg, filename); - this.sourceFile = sourceFile; - } - - @Override - public void write(final File parentDir) { - try { - final PrintStream out = open(parentDir); - final InputStream in = new FileInputStream(sourceFile); - - copy(in, out); - close(out); - } catch (final IOException e) { throw new RuntimeException(e); } - } - - private static void copy(final InputStream in, final PrintStream out) throws IOException { - int bit; - while (-1 != (bit = in.read())) { - out.write(bit); - } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/FrameworkClassFile.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/FrameworkClassFile.java deleted file mode 100644 index aade30f05fe..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/FrameworkClassFile.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.File; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.List; -import java.util.TreeSet; - -import com.apple.internal.jobjc.generator.FunctionGenerator; -import com.apple.internal.jobjc.generator.Utils; -import com.apple.internal.jobjc.generator.model.Category; -import com.apple.internal.jobjc.generator.model.Clazz; -import com.apple.internal.jobjc.generator.model.Constant; -import com.apple.internal.jobjc.generator.model.Framework; -import com.apple.internal.jobjc.generator.model.Function; -import com.apple.internal.jobjc.generator.model.NativeEnum; -import com.apple.internal.jobjc.generator.model.StringConstant; -import com.apple.internal.jobjc.generator.model.Struct; -import com.apple.internal.jobjc.generator.model.types.JType; -import com.apple.internal.jobjc.generator.model.types.JType.JStruct; -import com.apple.internal.jobjc.generator.utils.Fp; -import com.apple.internal.jobjc.generator.utils.JavaLang; -import com.apple.internal.jobjc.generator.utils.Fp.Map1; -import com.apple.internal.jobjc.generator.utils.JavaLang.JLCall; -import com.apple.internal.jobjc.generator.utils.JavaLang.JLField; -import com.apple.internal.jobjc.generator.utils.JavaLang.JLMethod; -import com.apple.internal.jobjc.generator.utils.JavaLang.JLReturn; -import com.apple.jobjc.JObjCRuntime; -import com.apple.jobjc.MacOSXFramework; -import com.apple.jobjc.Invoke.FunCall; - -public class FrameworkClassFile extends GeneratedClassFile { - final Framework framework; - - public FrameworkClassFile(final Framework framework) { - super(framework.pkg, framework.name + "Framework", MacOSXFramework.class.getName()); - this.framework = framework; - } - - @Override public void writeBeginning(final PrintStream out) { - List binPaths = Fp.map(new Map1(){ - public String apply(File a) { return "\"" + a.getAbsolutePath() + "\""; }}, - framework.binaries); - out.println(new Utils.Substituter( - "#public " + className + "(" + JObjCRuntime.class.getName() + " runtime) {~" + - "##super(runtime, new String[]{" + Fp.join(", ", binPaths) + "});~" + - "#}~" - )); - } - - @Override public void writeBody(final PrintStream out) { - for(final Struct struct : new ArrayList(framework.structs)){ - out.println("\tpublic " + struct.name + " make" + struct.name + "(){"); - out.println("\t\treturn new " + struct.name + "(getRuntime());"); - out.println("\t}"); - out.println("\tpublic " + struct.name + " make" + struct.name + "(com.apple.jobjc.NativeBuffer base){"); - out.println("\t\treturn new " + struct.name + "(getRuntime(), base);"); - out.println("\t}"); - } - - for(final NativeEnum nenum : framework.enums){ - if(nenum.ignore){ - out.println("\t/**"); - out.println("\t * @deprecated Suggestion: " + nenum.suggestion); - out.println("\t */"); - out.println("\t@Deprecated"); - } - out.println(String.format("\tpublic final %3$s %1$s(){ return %2$s; }", - nenum.name, nenum.valueToString(), nenum.type.getJType().getJavaReturnTypeName())); - } - - for(final Constant konst : framework.constants){ - String cacheName = "_" + konst.name; - final JType jtype = konst.type.getJType(); - final String cast = jtype.getReturnTypeCast() == null ? "" : "(" + jtype.getReturnTypeCast() + ")"; - out.println(); - - out.print(new JLField("private", jtype.getJavaTypeName(), cacheName, jtype.getDefaultReturnValue())); - - JLMethod reader = new JLMethod("public final", jtype.getJavaReturnTypeName(), konst.name); - reader.body.add("if(" + cacheName + " != " + jtype.getDefaultReturnValue() + ") return " + cast + cacheName + ";"); - - String contextName = jtype instanceof JStruct ? "returnValue" : "nativeBuffer"; - - if(jtype instanceof JStruct) - reader.body.add(((JStruct)jtype).createReturnValue()); - else - reader.body.add(jtype.createDeclareBuffer(contextName)); - - reader.body.add("getConstant(\"" + konst.name + "\", " + contextName + ", " + jtype.getCoderDescriptor().getCoderInstanceName() + ".sizeof());"); - - reader.body.add(jtype.createPop(contextName)); - reader.body.add(cacheName + " = returnValue;"); - reader.body.add(jtype.createReturn()); - - out.print(reader); - } - - for(final StringConstant konst : framework.stringConstants){ - if(Fp.any(new Map1(){ public Boolean apply(Constant a) { - return a.name.equals(konst.name); - }}, new ArrayList(framework.constants))){ - System.out.println("Warning: [" + framework.name + "] String constant " + konst.name + " is already defined in constants. Skipping."); - } - else{ - out.println("\tpublic final String " + konst.name + "(){ return \"" + escapeQuotes(konst.value) + "\"; }"); - } - } - - /** - * Order classes to get stable output - */ - TreeSet sortedClasses = new TreeSet(framework.classes); - for (final Clazz clazz : sortedClasses) { - final String classClassName = clazz.name + "Class"; - out.println(JavaLang.makeSingleton("_" + classClassName, clazz.name, classClassName, "getRuntime()")); - } - - for (final Category cat : framework.categories) { - final String classClassName = cat.category.name + "Class"; - out.println(JavaLang.makeSingleton("_" + classClassName, cat.category.name, classClassName, "getRuntime()")); - - JLMethod jlm = new JLMethod("public", cat.category.name, cat.category.name, "final " + cat.category.superClass.getFullPath() + " obj"); - jlm.body.add(new JLReturn(new JLCall("new " + cat.category.name, "obj", "getRuntime()"))); - out.println(jlm); - } - - for (final Function fxn : framework.functions){ - FunctionGenerator.writeOutFunction(out, FunCall.class, fxn, null); - } - } - - private String escapeQuotes(String s){ - return s.replace("\"", "\\\""); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/GeneratedClassFile.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/GeneratedClassFile.java deleted file mode 100644 index 0098d4d442c..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/GeneratedClassFile.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; - -public class GeneratedClassFile extends OutputFile { - protected final String className; - protected final String genericArgs; - protected final String superClass; - - public GeneratedClassFile(final String pkg, final String classname, final String superClass) { - this(pkg, classname, null, superClass); - } - - public GeneratedClassFile(final String pkg, final String classname, final String genericArgs, final String superClass) { - super(pkg, classname + ".java"); - this.className = classname; - this.genericArgs = genericArgs; - this.superClass = superClass; - } - - @Override - public void write(final File parentDir) { - try { - final PrintStream out = open(parentDir); - out.println("package " + pkg + ";"); - out.println(); - out.print("public " + (isFinal() ? "final" : "") + " class " + className); - if(genericArgs != null) out.print("<" + genericArgs + ">"); - if (superClass != null) out.print(" extends " + superClass); - out.println(" {"); - writeBeginning(out); - writeBody(out); - writeEnd(out); - out.println("}"); - close(out); - } catch (final IOException e) { throw new RuntimeException(e); } - } - - public void writeBeginning(final PrintStream out) { - - } - - public void writeBody(final PrintStream out) { - - } - - public void writeEnd(final PrintStream out) { - - } - - protected boolean isFinal(){ return false; } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/JObjCClassClassFile.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/JObjCClassClassFile.java deleted file mode 100644 index a22bb5b5fa3..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/JObjCClassClassFile.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.PrintStream; -import java.util.HashSet; -import java.util.Set; - -import com.apple.internal.jobjc.generator.ClassGenerator; -import com.apple.internal.jobjc.generator.FunctionGenerator; -import com.apple.internal.jobjc.generator.model.Clazz; -import com.apple.internal.jobjc.generator.model.Method; -import com.apple.jobjc.JObjCRuntime; -import com.apple.jobjc.Invoke.MsgSend; - -public class JObjCClassClassFile extends AbstractObjCClassFile { - public JObjCClassClassFile(final Clazz clazz) { - super(clazz, clazz.name + "Class", clazz.superClass != null ? clazz.superClass.getFullPath() + "Class" : ClassGenerator.JOBJC_PACKAGE + ".NSClass<" + clazz.name + ">"); - } - - @Override public void writeBeginning(final PrintStream out) { - out.format( - "\tpublic %1$s(%2$s runtime) {\n" + - "\t\tsuper(runtime);\n" + - "\t}\n", - className, JObjCRuntime.class.getCanonicalName()); - out.format( - "\tpublic %1$s(String name, %2$s runtime) {\n" + - "\t\tsuper(name, runtime);\n" + - "\t}\n", - className, JObjCRuntime.class.getCanonicalName()); - out.format( - "\tpublic %1$s(long ptr, %2$s runtime) {\n" + - "\t\tsuper(ptr, runtime);\n" + - "\t}\n", - className, JObjCRuntime.class.getCanonicalName()); - } - - @Override public void writeBody(final PrintStream out) { - Set written = new HashSet(); - for(final Method method : this.clazz.classMethods) - if(written.add(method.name)) - FunctionGenerator.writeOutFunction(out, MsgSend.class, method, "this"); - else - System.out.format("Duplicate method: %1$s %2$s -%3$s\n", clazz.parent.name, className, method.name); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/JObjCClassFile.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/JObjCClassFile.java deleted file mode 100644 index 276c76b3a97..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/JObjCClassFile.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.PrintStream; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import com.apple.internal.jobjc.generator.FunctionGenerator; -import com.apple.internal.jobjc.generator.model.Clazz; -import com.apple.internal.jobjc.generator.model.Method; -import com.apple.jobjc.JObjCRuntime; -import com.apple.jobjc.NativeObjectLifecycleManager; -import com.apple.jobjc.Invoke.MsgSend; - -public class JObjCClassFile extends AbstractObjCClassFile { - public JObjCClassFile(final Clazz clazz) { - super(clazz, clazz.name, - clazz.superClass == null ? "com.apple.jobjc.ID" - : clazz.superClass.getFullPath()); - } - - private static Map nolmForClass = - new TreeMap(); - static{ - nolmForClass.put("NSAutoreleasePool", NativeObjectLifecycleManager.Nothing.INST); - } - - @Override public void writeBeginning(final PrintStream out) { - out.format("\tpublic %1$s(final long objPtr, final %2$s runtime) {\n" + - "\t\tsuper(objPtr, runtime);\n" + - "\t}\n", - className, JObjCRuntime.class.getCanonicalName()); - - out.format("\tpublic %1$s(final %1$s obj, final %2$s runtime) {\n" + - "\t\tsuper(obj, runtime);\n" + - "\t}\n", - className, JObjCRuntime.class.getCanonicalName()); - - NativeObjectLifecycleManager nolm = nolmForClass.get(clazz.name); - if(nolm != null) - out.format("\t@Override\n"+ - "\tprotected %1$s getNativeObjectLifecycleManager() {\n" + - "\t\treturn %2$s.INST;\n" + - "\t}\n", - NativeObjectLifecycleManager.class.getCanonicalName(), nolm.getClass().getCanonicalName()); - } - - @Override public void writeBody(final PrintStream out) { - Set written = new HashSet(); - for(final Method method : this.clazz.instanceMethods) - if(written.add(method.name)) - FunctionGenerator.writeOutFunction(out, MsgSend.class, method, "this"); - else - System.out.format("Duplicate method: %1$s %2$s -%3$s\n", clazz.parent.name, className, method.name); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/MixedPrimitiveCoderClassFile.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/MixedPrimitiveCoderClassFile.java deleted file mode 100644 index ea28298bc48..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/MixedPrimitiveCoderClassFile.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.PrintStream; -import java.util.Collection; - -import com.apple.internal.jobjc.generator.ClassGenerator; -import com.apple.internal.jobjc.generator.model.coders.ComplexCoderDescriptor.MixedEncodingDescriptor; -import com.apple.jobjc.PrimitiveCoder; - -public class MixedPrimitiveCoderClassFile extends GeneratedClassFile { - private static final String MULTI_CODER_CLASSNAME = "MixedPrimitiveCoder"; - public static final String FULL_MULTI_CODER_CLASSNAME = ClassGenerator.JOBJC_PACKAGE + "." + MULTI_CODER_CLASSNAME; - - final Collection coderDescs; - - public MixedPrimitiveCoderClassFile(final Collection coderDescs) { - super(ClassGenerator.JOBJC_PACKAGE, MULTI_CODER_CLASSNAME, "java.lang.Object"); - this.coderDescs = coderDescs; - } - - @Override - public void writeBody(final PrintStream out) { - for (final MixedEncodingDescriptor desc : coderDescs) { - out.println("\tpublic static final " + PrimitiveCoder.class.getCanonicalName() + " " + desc.getMixedName() + " = " + desc.getDefinition() + ";"); - } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/OpaqueClassFile.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/OpaqueClassFile.java deleted file mode 100644 index c7fa5d7f131..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/OpaqueClassFile.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.PrintStream; - -import com.apple.internal.jobjc.generator.model.Opaque; -import com.apple.jobjc.Pointer; - -public class OpaqueClassFile extends GeneratedClassFile { - final Opaque opaque; - - public OpaqueClassFile(final Opaque opaque) { - super(opaque.parent.pkg, opaque.type.getJType().getJavaClassName(), com.apple.jobjc.Opaque.class.getCanonicalName()); - this.opaque = opaque; - } - - @Override public void writeBeginning(PrintStream out){ - out.println("\t// " + opaque.type); - out.println("\t// " + opaque.type.getJType()); - out.println(""); - out.println("\tpublic " + className + "(" + Pointer.class.getName() + " ptr){"); - out.println("\t\tsuper(ptr);"); - out.println("\t}"); - out.println(""); - out.println("\tpublic " + className + "(long ptr){"); - out.println("\t\tsuper(ptr);"); - out.println("\t}"); - } - -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/OutputFile.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/OutputFile.java deleted file mode 100644 index 615bb24acfa..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/OutputFile.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.*; - -public abstract class OutputFile { - final String pkg; - final String fileName; - - public OutputFile(final String pkg, final String filename) { - this.pkg = pkg; - this.fileName = filename; - } - - public PrintStream open(final File parentDir) throws IOException { - final File pkgDir = new File(parentDir, pkg.replace('.', '/')); - pkgDir.mkdirs(); - final File classFile = new File(pkgDir, fileName); - classFile.createNewFile(); - return new PrintStream(classFile); - } - - public void close(final PrintStream out) { - out.close(); - } - - public abstract void write(final File parentDir); - - public boolean isClass(final Class clazz) { - final String pkgName = clazz.getPackage().getName(); - if (!pkgName.equals(pkg)) return false; - - return fileName.contains(clazz.getSimpleName()); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/RootJObjCClass.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/RootJObjCClass.java deleted file mode 100644 index a581d1ce2ee..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/RootJObjCClass.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.PrintStream; -import java.util.List; - -import com.apple.internal.jobjc.generator.ClassGenerator; -import com.apple.internal.jobjc.generator.model.Framework; -import com.apple.internal.jobjc.generator.utils.JavaLang; -import com.apple.internal.jobjc.generator.utils.JavaLang.JLCtor; -import com.apple.internal.jobjc.generator.utils.JavaLang.JLField; -import com.apple.internal.jobjc.generator.utils.JavaLang.JLMethod; -import com.apple.jobjc.JObjCRuntime; - -public class RootJObjCClass extends GeneratedClassFile { - private static final String JOBJC_CLASSNAME = "JObjC"; - public static final String FULL_JOBJC_CLASSNAME = ClassGenerator.JOBJC_PACKAGE + "." + JOBJC_CLASSNAME; - public static final String JOBJC_RUNTIME_INST = FULL_JOBJC_CLASSNAME + ".getInstance()"; - public static final String JOBJC_RUNTIME_INST_R = FULL_JOBJC_CLASSNAME + ".getInstance(getRuntime())"; - - public static final String runtimeFrameworkInst(String fwname){ - return JOBJC_RUNTIME_INST + "." + fwname + "()"; - } - - public static final String runtimeFrameworkInstR(String fwname){ - return JOBJC_RUNTIME_INST_R + "." + fwname + "()"; - } - - final List frameworks; - - public RootJObjCClass(final List frameworks) { - super(ClassGenerator.JOBJC_PACKAGE, JOBJC_CLASSNAME, "java.lang.Object"); - this.frameworks = frameworks; - } - - @Override public void writeBeginning(final PrintStream out) { - out.print(new JLField("private static", JOBJC_CLASSNAME, "instance")); - out.print(new JLField("private final", JObjCRuntime.class.getName(), "runtime")); - - JLMethod getInstR = new JLMethod("public static", JOBJC_CLASSNAME, "getInstance", "final JObjCRuntime runtime"); - getInstR.body.add("if(runtime == null) throw new NullPointerException(\"runtime\");"); - getInstR.body.add("if(instance == null) instance = new JObjC(runtime);"); - getInstR.body.add("return instance;"); - out.print(getInstR); - - JLMethod getInst = new JLMethod("public static", JOBJC_CLASSNAME, "getInstance"); - getInst.body.add("return getInstance(JObjCRuntime.getInstance());"); - out.print(getInst); - - JLCtor ctor = new JLCtor("private", JOBJC_CLASSNAME, "final JObjCRuntime runtime"); - ctor.body.add("this.runtime = runtime;"); - for (final Framework f : frameworks) - ctor.body.add("runtime.registerPackage(\"" + f.pkg + "\");"); - out.print(ctor); - } - - @Override public void writeBody(final PrintStream out) { - for (final Framework f : frameworks) - out.println(JavaLang.makeSingleton("_" + f.name, f.name, f.pkg + "." + f.name + "Framework", "runtime")); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/StructClassFile.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/StructClassFile.java deleted file mode 100644 index 597d30a5818..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/classes/StructClassFile.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.classes; - -import java.io.PrintStream; - -import com.apple.internal.jobjc.generator.model.Struct; -import com.apple.internal.jobjc.generator.model.Struct.Field; -import com.apple.internal.jobjc.generator.model.coders.CoderDescriptor; -import com.apple.internal.jobjc.generator.model.types.JType; -import com.apple.internal.jobjc.generator.model.types.JType.JStruct; -import com.apple.internal.jobjc.generator.model.types.NType.NBitfield; -import com.apple.internal.jobjc.generator.model.types.NType.NStruct; -import com.apple.internal.jobjc.generator.utils.Fp; -import com.apple.internal.jobjc.generator.utils.Fp.Map1; -import com.apple.jobjc.JObjCRuntime; -import com.apple.jobjc.Coder.StructCoder; - -public class StructClassFile extends GeneratedClassFile { - final Struct struct; - - public StructClassFile(final Struct struct) { - super(struct.parent.pkg, struct.name, com.apple.jobjc.Struct.class.getName()); - this.struct = struct; - } - - @Override public boolean isFinal(){ return true; } - - @Override public void writeBeginning(final PrintStream out) { - out.println(); - out.println("\tpublic static int SIZEOF = " + JObjCRuntime.class.getName() + ".IS64 ? " - + ((NStruct) struct.type.type64).sizeof64() + " : " + ((NStruct) struct.type.type32).sizeof32() + ";"); - out.println(); - out.format("\tpublic final static %1$s getStructCoder(){ return coder; }\n", StructCoder.class.getCanonicalName()); - out.format("\t@Override public final %1$s getCoder(){ return coder; }\n", StructCoder.class.getCanonicalName()); - out.format("\tprivate final static %1$s coder = new %1$s(SIZEOF%2$s%3$s){\n", StructCoder.class.getCanonicalName(), - (struct.fields.size() > 0 ? ",\n\t\t" : ""), - Fp.join(",\n\t\t", Fp.map(new Map1(){ - public String apply(Field a) { - return a.type.getJType().getCoderDescriptor().getCoderInstanceName(); - }}, struct.fields))); - out.format("\t\t@Override protected %1$s newInstance(%2$s runtime){ return new %1$s(runtime); }\n", - struct.name, - JObjCRuntime.class.getCanonicalName()); - out.println("\t};"); - out.println(); - out.println("\t" + struct.name + "(final " + JObjCRuntime.class.getCanonicalName() + " runtime){"); - out.println("\t\tsuper(runtime, SIZEOF);"); - out.println("\t}"); - out.println(); - out.println("\tpublic " + struct.name + "(final " + JObjCRuntime.class.getCanonicalName() + " runtime, final com.apple.jobjc.NativeBuffer buffer) {"); - out.println("\t\tsuper(runtime, buffer, SIZEOF);"); - out.println("\t}"); - } - - @Override public void writeBody(final PrintStream out) { - for(Struct.Field field : struct.fields){ - if(field.type.type64 instanceof NStruct && field.type.type32 instanceof NStruct) - writeStructField(field, out); - else - writeField(field, out); - } - } - - private void writeField(final Struct.Field field, final PrintStream out){ - if(field.type.type32 instanceof NBitfield){ - out.format("\t// Skipping bitfield '%1$s'\n", field.name); - return; - } - String privName = field.name + "__"; - String offsetName = field.name.toUpperCase() + "_OFFSET"; - JType jtype = field.type.getJType(); - String retType = jtype.getJavaReturnTypeName(); - CoderDescriptor cdesc = jtype.getCoderDescriptor(); - out.println(); - out.println("\tprivate static final int " + offsetName + " = " + JObjCRuntime.class.getName() - + ".IS64 ? " + field.field64.offset64() + " : " + field.field32.offset32() + ";"); - - out.println("\t//" + cdesc.getClass().toString()); - out.println("\tpublic " + retType + " " + getterName(field) + "(){"); - out.println(jtype.createPopAddr("getRuntime()", "this.raw.bufferPtr + " + offsetName)); - out.println(jtype.createReturn()); - out.println("\t}"); - out.println(); - out.println("\tpublic void " + setterName(field.name) + "(final " + retType + " " + privName + "){"); - out.println("\t\t" + cdesc.getPushAddrStatementFor("getRuntime()", "this.raw.bufferPtr + " + offsetName, privName)); - out.println("\t}"); - } - - private void writeStructField(final Struct.Field field, final PrintStream out){ - if(field.type.getJType() == null || !(field.type.getJType() instanceof JStruct)){ - out.println("\t// Found bad JavaType (" + field.type.getJType() + ") for field (" + field.name + ") of type (" + field.type + ")"); - return; - } - String privName = field.name + "__"; - String offsetName = field.name.toUpperCase() + "_OFFSET"; - JStruct jstype = (JStruct) field.type.getJType(); - String retTypeName = jstype.getJavaReturnTypeName(); - out.println(); - out.println("\tprivate static final int " + offsetName + " = " + JObjCRuntime.class.getName() + ".IS64" - + " ? " + field.field64.offset64() + " : " + field.field32.offset32() + ";"); - - out.println("\tprivate " + retTypeName + " " + privName + " = null;"); - out.println("\tpublic " + retTypeName + " " + getterName(field) + "(){"); - out.println("\t\tif(null==" + privName + "){"); - out.println("\t\t\tthis.raw.position(" + offsetName + ");"); - out.println("\t\t\t" + privName + " = " + RootJObjCClass.runtimeFrameworkInstR(struct.parent.name) + ".make" + jstype.struct.name + "(this.raw.slice());"); - out.println("\t\t}"); - out.println("\t\treturn " + privName + ";"); - out.println("\t}"); - } - - private String getterName(Struct.Field field) { - if(com.apple.internal.jobjc.generator.RestrictedKeywords.isRestricted(field.name)) - return field.name + field.type.getJType().getAppendableDescription(); - return field.name; - } - - private String setterName(String name) { - return "set" + name.substring(0, 1).toUpperCase() + name.substring(1); - } - - @Override public void writeEnd(final PrintStream out) { - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/CFType.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/CFType.java deleted file mode 100644 index d71eec5fe8a..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/CFType.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model; - -import java.util.List; - -import org.w3c.dom.Node; - -import com.apple.internal.jobjc.generator.classes.CFTypeClassFile; -import com.apple.internal.jobjc.generator.classes.OutputFile; - -public class CFType extends TypeElement implements OutputFileGenerator { - public final String getTypeIdFunc; - public final String tollfree; - - public CFType(final Node node, final Framework parent) { - super(node, getAttr(node, "name"), parent); - getTypeIdFunc = getAttr(node, "gettypeid_func"); - tollfree = getAttr(node, "tollfree"); - } - - public void generateClasses(final List generatedClassFiles) { - generatedClassFiles.add(new CFTypeClassFile(this)); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Category.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Category.java deleted file mode 100644 index 8bd50646992..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Category.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model; - -import java.util.List; - -import com.apple.internal.jobjc.generator.classes.CategoryClassClassFile; -import com.apple.internal.jobjc.generator.classes.CategoryClassFile; -import com.apple.internal.jobjc.generator.classes.OutputFile; - -public class Category implements OutputFileGenerator{ - public final Clazz category; - - public Category(Clazz fromClass, Clazz target) { - this.category = new Clazz(fromClass.name + "Category", fromClass.classMethods, fromClass.instanceMethods, target, fromClass.parent); - } - - public void generateClasses(List generatedClassFiles) { - generatedClassFiles.add(new CategoryClassFile(this)); - generatedClassFiles.add(new CategoryClassClassFile(this)); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Clazz.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Clazz.java deleted file mode 100644 index 3571974ccdb..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Clazz.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import com.apple.internal.jobjc.generator.RestrictedKeywords; -import com.apple.internal.jobjc.generator.classes.JObjCClassClassFile; -import com.apple.internal.jobjc.generator.classes.JObjCClassFile; -import com.apple.internal.jobjc.generator.classes.OutputFile; -import com.apple.jobjc.MacOSXFramework; -import com.apple.jobjc.SuperClassExtractor; -import com.apple.jobjc.UnsafeRuntimeAccess; -import com.apple.jobjc.NSClass.NSClassNotFoundException; -import com.apple.jobjc.SEL; - -public class Clazz extends Element implements OutputFileGenerator { - private final Map instanceMethodsByName = new HashMap(); - private final Map classMethodsByName = new HashMap(); - - public final List classMethods; - public final List instanceMethods; - - public final List subClassers = new ArrayList(0); - public Clazz superClass; - - public Clazz(String name, List classMethods, List instanceMethods, Clazz superClass, Framework parent){ - super(name, parent); - this.classMethods = classMethods; - this.instanceMethods = instanceMethods; - this.superClass = superClass; - } - - public Clazz(final Node classNode, final Framework parent) { - super(classNode, parent); - this.classMethods = new ArrayList(); - this.instanceMethods = new ArrayList(); - - final NodeList methodNodes = classNode.getChildNodes(); - for (int i = 0; i < methodNodes.getLength(); i++) { - final Node node = methodNodes.item(i); - if (!"method".equals(node.getLocalName())) continue; - - final String selName = Element.getAttr(node, "selector"); - if(selName == null || !SEL.validName(selName)){ - System.err.format("Warning: Discarding method %1$s:%2$s:%3$s" - + " -- Invalid selector name. Verify.\n", - parent.name, name, selName); - continue; - } - - final Method method = new Method(node, parent); - if (method.isClassMethod) { - classMethods.add(method); - } else { - instanceMethods.add(method); - } - } - } - - public String getPackage() { - return parent.pkg; - } - - public String getFullPath(){ - return parent.pkg + "." + name; - } - - @Override - public String toString() { - return super.toString() + " " + classMethods + " " + instanceMethods; - } - - public boolean doesActuallyExist(){ - try{ - UnsafeRuntimeAccess.getNSClass(parent.load(), name); - }catch(NSClassNotFoundException x){ - return false; - } - return true; - } - - void resolveSuperClass(final MacOSXFramework nativeFramework, final Map allClasses) throws Throwable { - superClass = SuperClassExtractor.getSuperClassFor(name, nativeFramework, allClasses); - } - - public void disambiguateMethods() { - disambiguateMethods(instanceMethods, instanceMethodsByName); - disambiguateMethods(classMethods, classMethodsByName); - } - - private void disambiguateMethods(final List methods, final Map methodMap) { - final Set existingMethodNames = RestrictedKeywords.getNewRestrictedSet(); - for (final Method method : methods) { - method.disambiguateNameAndArgs(this, existingMethodNames); - methodMap.put(method.javaName, method); - } - } - - public void generateClasses(final List generatedClassFiles) { - generatedClassFiles.add(new JObjCClassClassFile(this)); - generatedClassFiles.add(new JObjCClassFile(this)); - } - - Method getParentMethodMatchingName(final String methodName) { - if(superClass == null) return null; - Method m = superClass.getMethodNamed(methodName); - if(m != null) return m; - return superClass.getParentMethodMatchingName(methodName); - } - - private Method getMethodNamed(final String methodName) { - final Method instanceMethod = instanceMethodsByName.get(methodName); - if (instanceMethod != null) return instanceMethod; - - final Method classMethod = classMethodsByName.get(methodName); - if (classMethod != null) return classMethod; - - return null; - } - - int compareTo(Clazz o) { - return toString().compareTo(o.toString()); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Element.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Element.java deleted file mode 100644 index 47fff332e6b..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Element.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; - -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import com.apple.internal.jobjc.generator.model.types.Type; -import com.apple.internal.jobjc.generator.utils.ObjectInspector; - -/** - * Subclasses must implement ctor(Node, P) - */ -public class Element

> implements Comparable>{ - public final String name; - public final P parent; - - public Element(final String name, final P parent) { - this.name = Type.cleanName(name); - this.parent = parent; - } - - public Element(final Node node, final P parent) { - this(getAttr(node, "name"), parent); - } - - public static String getAttr(final Node node, final String key) { - final NamedNodeMap attrs = node.getAttributes(); - if (attrs == null) return null; - final Node name = attrs.getNamedItem(key); - if (name == null) return null; - return name.getNodeValue(); - } - - static

, T extends Element

> List getNodesFor(final Node parentNode, final String selection, final Class clazz, final P parent) { - Constructor ctor; - try { - ctor = clazz.getConstructor(new Class[] { Node.class, parent.getClass() }); - } catch (Exception e) { - throw new RuntimeException(e); - } - - final NodeList childNodes = parentNode.getChildNodes(); - final List nodes = new ArrayList(); - for (int i = 0; i < childNodes.getLength(); i++) { - final Node node = childNodes.item(i); - if (!selection.equals(node.getLocalName())) continue; - - T obj; - try { - obj = ctor.newInstance(new Object[] { node, parent }); - } catch (InvocationTargetException e) { - throw new RuntimeException(e.getCause()); - } catch (Exception e) { - throw new RuntimeException(e); - } - nodes.add(obj); - } - - return nodes; - } - - @Override public String toString() { - return name; - } - - public String reflectOnMySelf() { - return ObjectInspector.inspect(this); - } - - public int compareTo(Element o) { - return name.compareTo(o.name); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/ElementWType.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/ElementWType.java deleted file mode 100644 index 8bb31b9449e..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/ElementWType.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model; - -import com.apple.internal.jobjc.generator.model.types.NType; -import org.w3c.dom.Node; - -import com.apple.internal.jobjc.generator.model.types.Type; -import com.apple.internal.jobjc.generator.utils.NTypeParser; - -/** - * An ElementWType has a type but does not necessarily represent a type. Examples are constants, enums, arguments, return values. - */ -public class ElementWType

> extends Element

{ - public final Type type; - - public ElementWType(final String name, final Type t, final P parent) { - super(name, parent); - this.type = t; - } - - public ElementWType(final Node node, final Type t, final P parent) { - super(node, parent); - this.type = t; - } - - public ElementWType(final Node node, final String declType, final P parent) { - super(node, parent); - final String type32 = getAttr(node, "type"); - final String type64 = getAttr(node, "type64"); - this.type = Type.getType(declType, - type32 == null ? NType.NUnknown.inst() : NTypeParser.parseFrom(type32), - type64 == null ? null : NTypeParser.parseFrom(type64)); - } - - public ElementWType(final Node node, final P parent){ - this(node, getAttr(node, "declared_type"), parent); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Framework.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Framework.java deleted file mode 100644 index a63be7d4106..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Framework.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - -import org.w3c.dom.Node; -import org.xml.sax.InputSource; - -import com.apple.internal.jobjc.generator.ClassGenerator; -import com.apple.internal.jobjc.generator.Utils; -import com.apple.internal.jobjc.generator.classes.FrameworkClassFile; -import com.apple.internal.jobjc.generator.classes.OutputFile; -import com.apple.internal.jobjc.generator.utils.Fp; -import com.apple.internal.jobjc.generator.utils.Fp.Map1; -import com.apple.jobjc.MacOSXFramework; -import com.apple.jobjc.UnsafeRuntimeAccess; - -public class Framework extends Element> implements OutputFileGenerator { - public final String path; - public final String pkg; - public final List binaries; - public MacOSXFramework nativeFramework; - - public MacOSXFramework load(){ - if(nativeFramework == null){ - String[] bins = new String[binaries.size()]; - for(int i = 0; i < binaries.size(); ++i) - bins[i] = Utils.getCanonicalPath(binaries.get(i)); - nativeFramework = UnsafeRuntimeAccess.getFramework(bins); - } - return nativeFramework; - } - - public File getMainFrameworkBinary(){ return binaries.get(0); } - - final Node rootNode; - - public Set classes; - public List structs; - public List cfTypes; - public List opaques; - public List constants; - public List stringConstants; - public List enums; - public List functions; - public List functionAliases; - public List informalProtocols; - public List protocols; - public List categories; - public List dependencies; - - public static class FrameworkDependency extends Element{ - final String path; - public Framework object = null; - - public FrameworkDependency(final Node node, final Framework parent) { - super(getAttr(node, "path").replaceFirst("^.*/([^/]+)\\.framework$", "$1"), parent); - this.path = getAttr(node, "path"); - } - } - - public static final XPath XPATH = XPathFactory.newInstance().newXPath(); - public Framework(final String name, final File bsFile) { - super(name, null); - try { - final File pathf = bsFile.getCanonicalFile().getParentFile().getParentFile().getParentFile(); - path = pathf.getParentFile().getParentFile().getCanonicalPath(); - } catch (IOException x) { - throw new RuntimeException(x); - } - binaries = findBinaries(path, name); - - pkg = ClassGenerator.JOBJC_PACKAGE + "." + name.toLowerCase(); - try { - rootNode = (Node)XPATH.evaluate("signatures", new InputSource(bsFile.getAbsolutePath()), XPathConstants.NODE); - } catch (final XPathExpressionException e) { throw new RuntimeException(e); } - protocols = new ArrayList(); - categories = new ArrayList(); - } - - private static List findBinaries(final String rootPath, final String name){ - List bins = new ArrayList(2); - - File mainBin = new File(rootPath, name); - if(mainBin.exists()) bins.add(mainBin); - - File bsBin = new File(rootPath, "Resources/BridgeSupport/" + name + ".dylib"); - if(bsBin.exists()) bins.add(bsBin); - - return bins; - } - - public void parseDependencies(final Collection frameworks) { - // Parse - dependencies = getNodesFor(rootNode, "depends_on", FrameworkDependency.class, this); - // Resolve - for(final FrameworkDependency dep : dependencies) - dep.object = Fp.find(new Map1(){ - public Boolean apply(Framework f) { - return f.path.equals(dep.path); - }}, frameworks); - } - - public void parseStructs() { - structs = getNodesFor(rootNode, "struct", Struct.class, this); - - // HACK BS bug #6100313 - if(Utils.isSnowLeopard && name.equals("IOBluetooth")) - structs.remove(getStructByName("BluetoothHCIRequestNotificationInfo")); - - // GLIFunctionDispatch is frequently out of sync in BS / system - if(name.equals("OpenGL")) - structs.remove(getStructByName("GLIFunctionDispatch")); - } - - public void parseCFTypes() { - cfTypes = getNodesFor(rootNode, "cftype", CFType.class, this); - } - - public void parseOpaques() { - opaques = getNodesFor(rootNode, "opaque", Opaque.class, this); - } - - public void parseConstants() { - constants = getNodesFor(rootNode, "constant", Constant.class, this); - stringConstants = getNodesFor(rootNode, "string_constant", StringConstant.class, this); - enums = getNodesFor(rootNode, "enum", NativeEnum.class, this); - } - - public void parseFunctions() { - functions = getNodesFor(rootNode, "function", Function.class, this); - functionAliases = getNodesFor(rootNode, "function_alias", FunctionAlias.class, this); - } - - public void parseClasses() { - classes = new HashSet(getNodesFor(rootNode, "class", Clazz.class, this)); - classes = Fp.filterSet(new Map1(){ - public Boolean apply(Clazz a) { - if(a.doesActuallyExist()) - return true; - else{ - System.out.println("Could not find class " + name + ":" + a.name + " in runtime. Discarding."); - return false; - } - }}, classes); - informalProtocols = getNodesFor(rootNode, "informal_protocol", InformalProtocol.class, this); - } - - public void resolveSuperClasses(final Map allClasses) throws Throwable { - load(); - for (final Clazz clazz : classes) - clazz.resolveSuperClass(nativeFramework, allClasses); - } - - public void generateClasses(final List generatedClassFiles) { - generatedClassFiles.add(new FrameworkClassFile(this)); - - final List> generatorLists = - Utils.list(new ArrayList(classes), structs, cfTypes, opaques, categories); - for (final List generators : generatorLists) { - for (final OutputFileGenerator generator : generators) - generator.generateClasses(generatedClassFiles); - } - } - - @Override public String toString() { return reflectOnMySelf(); } - - public Struct getStructByName(final String stname) { - return Fp.find(new Fp.Map1(){ - public Boolean apply(Struct a) { - return stname.equals(a.name); - }}, structs); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Function.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Function.java deleted file mode 100644 index c08d99925e9..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Function.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model; - -import java.util.*; - -import org.w3c.dom.*; - -import com.apple.internal.jobjc.generator.RestrictedKeywords; - -public class Function extends Element { - public final boolean variadic; - public final List args; - public final ReturnValue returnValue; - - public Function(final Node node, final Framework parent) { - this(node, getAttr(node, "name"), parent); - } - - public Function(final Node node, final String name, final Framework parent) { - super(name, parent); - - this.variadic = "true".equals(getAttr(node, "variadic")); - this.args = new ArrayList(); - - ReturnValue returnValue = null; - - final NodeList children = node.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - final Node child = children.item(i); - final String childName = child.getLocalName(); - - if ("retval".equals(childName)) { - returnValue = new ReturnValue(child, this); - } - - if ("arg".equals(childName)) { - final Arg arg = new Arg(child, this); - if (arg.name == null || "".equals(arg.name)) { - arg.javaName = "arg" + i; - } - args.add(arg); - } - } - - if (returnValue == null) returnValue = ReturnValue.VOID; - this.returnValue = returnValue; - } - - public String getJavaName(){ return name; } - - public void disambiguateArgs() { - final Set priorArgs = RestrictedKeywords.getNewRestrictedSet(); - for (int i = 0; i < args.size(); i++) { - final Arg arg = args.get(i); - if (priorArgs.contains(arg.name)) arg.javaName = arg.javaName + i; - priorArgs.add(arg.javaName); - } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Method.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Method.java deleted file mode 100644 index a1099078a4d..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Method.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model; - -import java.util.Set; -import org.w3c.dom.Node; -import com.apple.jobjc.SEL; -import com.apple.internal.jobjc.generator.Utils; - -public class Method extends Function { - public final boolean isClassMethod; - - public String javaName; - - public boolean ignore; - public String suggestion; - - public Method(final Node node, final Framework fw) { - super(node, getAttr(node, "selector"), fw); - this.javaName = SEL.jMethodName(name); - this.isClassMethod = "true".equals(getAttr(node, "class_method")); - this.ignore = "true".equals(getAttr(node, "ignore")); - this.suggestion = getAttr(node, "suggestion"); - } - - @Override public String getJavaName(){ return javaName; } - - @Override public String toString() { - return returnValue + " " + super.toString() + args; - } - - public boolean returnTypeEquals(final ReturnValue returnValueIn) { - return returnValue.type.getJType().getJavaReturnTypeName().equals(returnValueIn.type.getJType().getJavaReturnTypeName()); - } - - public void disambiguateNameAndArgs(final Clazz parentClazz, final Set existingMethodNames) { - javaName = getDisambiguatedNameFor(parentClazz, javaName, existingMethodNames); - disambiguateArgs(); - } - - private String getDisambiguatedNameFor(final Clazz parentClazz, final String proposedName, final Set existingNames) { - // Does this method override a parent class method and change the return type? Example: IOBlueToothSDPUUID length - { - final Method superClassMethod = parentClazz.getParentMethodMatchingName(proposedName); - if (superClassMethod != null && !superClassMethod.returnValue.equals(returnValue)) { - final String usingReturnType = createMethodNameAppendingReturnType(proposedName); - if(existingNames.add(usingReturnType)) - return usingReturnType; - } - } - - if(existingNames.add(proposedName)) - return proposedName; - - final String usingReturnType = createMethodNameAppendingReturnType(proposedName); - if(existingNames.add(usingReturnType)) - return usingReturnType; - - throw new RuntimeException("Unable to disambiguate method: " + this); - } - - private String createMethodNameAppendingReturnType(final String proposedName) { - return proposedName + Utils.capitalize(returnValue.type.getJType().getAppendableDescription().replaceAll(".+\\.", "")); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/NativeEnum.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/NativeEnum.java deleted file mode 100644 index e6bbd9b0652..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/NativeEnum.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model; - -import java.util.Arrays; - -import org.w3c.dom.Node; - -import com.apple.internal.jobjc.generator.model.types.Type; -import com.apple.internal.jobjc.generator.model.types.JType.JPrimitive; -import com.apple.internal.jobjc.generator.model.types.NType.NPrimitive; -import com.apple.internal.jobjc.generator.utils.Fp; -import com.apple.jobjc.JObjCRuntime; - -public class NativeEnum extends ElementWType { - public final String value, value64, le_value, be_value; - public boolean ignore; - public String suggestion; - public NativeEnum(final Node node, final Framework parent) { - super(node, typeForEnum(getAttr(node, "name"), - getAttr(node, "value"), getAttr(node, "value64"), - getAttr(node, "le_value"), getAttr(node, "be_value"), - getAttr(node, "ignore")), parent); - this.value = getAttr(node, "value"); - this.value64 = getAttr(node, "value64"); - this.le_value = getAttr(node, "le_value"); - this.be_value = getAttr(node, "be_value"); - String ignoreS = getAttr(node, "ignore"); - this.ignore = ignoreS == null ? false : Boolean.parseBoolean(ignoreS); - this.suggestion = getAttr(node, "suggestion"); - assert valueToString() != null; - } - - private static Type typeForEnum(String name, String value32, String value64, String le_value, String be_value, String ignore){ - if("true".equals(ignore)) return Type.getType(null, NPrimitive.inst('i'), null); - - NumTest[] tests = new NumTest[]{new IntTest(), new LongTest(), new FloatTest(), new DoubleTest()}; - for(NumTest t : tests) - if(t.confirm(value32, value64, le_value, be_value)) - return t.getType(); - - throw new NumberFormatException(String.format("Failed to parse type for enum: %1$s = 32: %2$s / 64: %3$s / le: %4$s / be: %5$s\n", - name, value32, value64, le_value, be_value)); - } - - public String valueToString(){ - if(ignore == true) return "0"; - JPrimitive jprim = (JPrimitive) type.getJType(); - if(le_value == null && be_value == null){ - if(value == null && value64 != null) - return value64 + jprim.getLiteralSuffix(); - else if(value != null && value64 == null) - return value + jprim.getLiteralSuffix(); - else - return String.format("(%1$s.IS64 ? %2$s%4$s : %3$s%4$s)", JObjCRuntime.class.getName(), - value64, value, jprim.getLiteralSuffix()); - } - else if(value == null && value64 == null){ - return String.format("(%1$s.IS_BIG_ENDIAN ? %2$s%4$s : %3$s%4$s)", - JObjCRuntime.class.getName(), be_value, le_value, jprim.getLiteralSuffix()); - } - - throw new RuntimeException("Unable to produce a value for enum " + name); - } - - // Used to find the best type to use for the enum. - - static abstract class NumTest{ - public boolean confirm(String... values){ - return Fp.all(new Fp.Map1(){ - public Boolean apply(String a) { - try{ return a == null || confirm(a); } - catch(Exception x){ return false; } - }}, - Arrays.asList(values)); - } - - public abstract boolean confirm(String v); - public abstract Type getType(); - } - - static class IntTest extends NumTest{ - @Override public boolean confirm(String v) { - Integer.parseInt(v); - return true; - } - - @Override public Type getType() { return Type.getType(null, NPrimitive.inst('i'), null); } - } - - static class LongTest extends NumTest{ - @Override public boolean confirm(String v) { - Long.parseLong(v); - return true; - } - - @Override public Type getType() { return Type.getType(null, NPrimitive.inst('l'), null); } - } - - static class FloatTest extends NumTest{ - @Override public boolean confirm(String v) { - return Float.parseFloat(v) == Double.parseDouble(v); - } - - @Override public Type getType() { return Type.getType(null, NPrimitive.inst('f'), null); } - } - - static class DoubleTest extends NumTest{ - @Override public boolean confirm(String v) { - double d = Double.parseDouble(v); - return !Double.isInfinite(d) && !Double.isNaN(d); - } - - @Override public Type getType() { return Type.getType(null, NPrimitive.inst('d'), null); } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/OutputFileGenerator.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/OutputFileGenerator.java deleted file mode 100644 index ac4b71d4d31..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/OutputFileGenerator.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model; - -import java.util.List; - -import com.apple.internal.jobjc.generator.classes.OutputFile; - -public interface OutputFileGenerator { - public void generateClasses(final List generatedClassFiles); -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Struct.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Struct.java deleted file mode 100644 index b583cdbf59c..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/Struct.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model; - -import java.util.List; - -import org.w3c.dom.Node; - -import com.apple.internal.jobjc.generator.classes.OutputFile; -import com.apple.internal.jobjc.generator.classes.StructClassFile; -import com.apple.internal.jobjc.generator.model.types.Type; -import com.apple.internal.jobjc.generator.model.types.NType.NField; -import com.apple.internal.jobjc.generator.model.types.NType.NStruct; -import com.apple.internal.jobjc.generator.utils.Fp; -import com.apple.internal.jobjc.generator.utils.QA; -import com.apple.internal.jobjc.generator.utils.Fp.Map2; - -/** - * A struct has the following restrictions: - * - * - type32.fields.count == type64.fields.count - * - forAll i: type32.field[i].name == type64.field[i].name - * - forAll i: type32.field[i].class == type64.field[i].class - */ -public class Struct extends TypeElement implements OutputFileGenerator { - public final List fields; - public static class Field{ - public final String name; - public final Type type; - public final NField field32, field64; - public Field(String name, NField field32, NField field64) { - QA.nonNull(name); - this.name = name; - // TODO really should have a declared_type attr. See if BS patch is possible. - this.type = Type.getType(null, field32.type, field64.type); - this.field32 = field32; - this.field64 = field64; - } - } - - public Struct(final Node node, final Framework parent) throws Throwable { - super(node, getAttr(node, "name"), parent); - NStruct nstruct32 = (NStruct) type.type32; - NStruct nstruct64 = (NStruct) type.type64; - this.fields = Fp.map2(new Map2(){ - public Field apply(NField f32, NField f64) { - assert f32.name.equals(f64.name); - return new Field(f32.name, f32, f64); - } - }, nstruct32.fields, nstruct64.fields); - } - - public void generateClasses(final List generatedClassFiles) { - generatedClassFiles.add(new StructClassFile(this)); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/coders/CoderDescriptor.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/coders/CoderDescriptor.java deleted file mode 100644 index b7a734fa975..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/coders/CoderDescriptor.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model.coders; - -import com.apple.internal.jobjc.generator.model.types.JType.JStruct; -import com.apple.jobjc.Coder; -import com.apple.jobjc.Coder.IDCoder; -import com.apple.jobjc.Coder.NSClassCoder; -import com.apple.jobjc.Coder.PointerCoder; -import com.apple.jobjc.Coder.PrimitivePointerCoder; -import com.apple.jobjc.Coder.SELCoder; -import com.apple.jobjc.Coder.UnknownCoder; -import com.apple.jobjc.Coder.VoidCoder; - -public class CoderDescriptor { - public static final CoderDescriptor VOID_DESC = new CoderDescriptor(VoidCoder.INST, null, null); - - final Coder coder; - private final String coderInstanceName; - final String pushName; - final String popName; - - public String mismatchMessage(){ return null; } - - public CoderDescriptor(final Coder coder, final String pushName, final String popName) { - this.coder = coder; - this.coderInstanceName = coder.getClass().getCanonicalName() + ".INST"; - if (coderInstanceName == null) throw new NullPointerException(); - - this.pushName = pushName; - this.popName = popName; - } - - public CoderDescriptor(final String pushName, final String popName) { - this.coder = null; - this.coderInstanceName = null; - this.pushName = pushName; - this.popName = popName; - } - - public CoderDescriptor(final Coder coder) { this(coder, "push", "pop"); } - public CoderDescriptor(){ this("push", "pop"); } - - public String getPopStatementFor(final String contextName, final String returnValueType, final String returnValueName, final String transform) { - return "final " + returnValueType + " " + returnValueName + " = " + "(" + returnValueType + ") " + (transform == null ? "" : transform) - + "(" + getCoderInstanceName() + "." + popName + "(" + contextName + "));"; - } - - public final String getPushStatementFor(final String contextName, final String argumentName) { - return getCoderInstanceName() + "." + pushName + "(" + contextName + ", " + argumentName + ");"; - } - - public String getPopAddrStatementFor(final String runtime, final String addr, final String returnValueType, final String returnValueName, final String transform) { - return "final " + returnValueType + " " + returnValueName + " = " + "(" + returnValueType + ") " + (transform == null ? "" : transform) - + "(" + getCoderInstanceName() + "." + popName + "(" + runtime + ", " + addr + "));"; - } - - public final String getPushAddrStatementFor(final String runtime, final String addr, final String argumentName) { - return getCoderInstanceName() + "." + pushName + "(" + runtime + ", " + addr + ", " + argumentName + ");"; - } - - public String getCoderInstanceName() { return coderInstanceName; } - public Coder getCoder() { return coder; } - public String getDefaultReturnValue() { return "null"; } - - // - // Specialized - // - - static public class UnknownCoderDescriptor extends CoderDescriptor { - public static final CoderDescriptor UNKNOWN_DESC = new UnknownCoderDescriptor(); - public UnknownCoderDescriptor() { super(UnknownCoder.INST); } - } - - static public class PrimitivePointerCoderDescriptor extends CoderDescriptor { - public static final PrimitivePointerCoderDescriptor POINTER_DESC = new PrimitivePointerCoderDescriptor(); - public PrimitivePointerCoderDescriptor() { super(PrimitivePointerCoder.INST, "push", "popPtr"); } - } - - static public class PointerCoderDescriptor extends CoderDescriptor { - public static final PointerCoderDescriptor INST = new PointerCoderDescriptor(); - public PointerCoderDescriptor() { super(PointerCoder.INST); } - } - - static public class SELCoderDescriptor extends CoderDescriptor { - public static final SELCoderDescriptor INST = new SELCoderDescriptor(); - public SELCoderDescriptor() { super(SELCoder.INST); } - } - - static public class IDCoderDescriptor extends CoderDescriptor { - public static final IDCoderDescriptor INST = new IDCoderDescriptor(); - public IDCoderDescriptor() { super(IDCoder.INST); } - } - - static public class NSClassCoderDescriptor extends CoderDescriptor { - public static final NSClassCoderDescriptor INST = new NSClassCoderDescriptor(); - public NSClassCoderDescriptor() { super(NSClassCoder.INST); } - } - - static public class StructCoderDescriptor extends CoderDescriptor { - public final JStruct jstruct; - public StructCoderDescriptor(JStruct jst) { this.jstruct = jst; } - @Override public String getCoderInstanceName(){ return jstruct.getJavaTypeName() + ".getStructCoder()"; } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/coders/ComplexCoderDescriptor.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/coders/ComplexCoderDescriptor.java deleted file mode 100644 index 929b0744ec3..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/coders/ComplexCoderDescriptor.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model.coders; - -import java.util.HashMap; -import java.util.TreeSet; -import java.util.Map; -import java.util.Set; - -import com.apple.internal.jobjc.generator.classes.MixedPrimitiveCoderClassFile; -import com.apple.internal.jobjc.generator.model.types.NType; -import com.apple.internal.jobjc.generator.model.types.NType.NPrimitive; -import com.apple.internal.jobjc.generator.utils.Fp.Pair; -import com.apple.jobjc.JObjCRuntime; - -/** - * Used to code two primitives of different 32/64 types. - */ -public class ComplexCoderDescriptor extends CoderDescriptor { - static Map, ComplexCoderDescriptor> cache = new HashMap, ComplexCoderDescriptor>(); - static Set mixedEncodingDescriptors = new TreeSet(); - - public static Set getMixedEncoders() { return mixedEncodingDescriptors; } - - public static ComplexCoderDescriptor getCoderDescriptorFor(final NType nt32, final NType nt64) { - Pair cacheKey = new Pair(nt32, nt64); - if(cache.containsKey(cacheKey)) return cache.get(cacheKey); - - final PrimitiveCoderDescriptor desc32 = PrimitiveCoderDescriptor.getCoderDescriptorFor((NPrimitive) nt32); - final PrimitiveCoderDescriptor desc64 = PrimitiveCoderDescriptor.getCoderDescriptorFor((NPrimitive) nt64); - - final ComplexCoderDescriptor newDesc = nt32.equals(nt64) ? new ComplexCoderDescriptor(desc64) : new MixedEncodingDescriptor(desc32, desc64); - cache.put(cacheKey, newDesc); - if(newDesc instanceof MixedEncodingDescriptor) - mixedEncodingDescriptors.add((MixedEncodingDescriptor) newDesc); - - return newDesc; - } - - protected final PrimitiveCoderDescriptor desc64; - - public ComplexCoderDescriptor(final PrimitiveCoderDescriptor desc64) { - super(desc64.coder, desc64.pushName, desc64.popName); - this.desc64 = desc64; - } - - public String getName() { return desc64.javaPrimitiveClazz.getName(); } - @Override public String getDefaultReturnValue() { return desc64.defaultReturnValue; } - public String getJavaObjectClass() { return desc64.javaObjectClazz.getName(); } - public String getDefinition() { return get64CoderName(); } - public String getCoderAccessor() { return get64CoderName(); } - String get64CoderName() { return desc64.getCoderInstanceName(); } - - // ** Subclasses - // ------------- - - public static class MixedEncodingDescriptor extends ComplexCoderDescriptor implements java.lang.Comparable { - protected final PrimitiveCoderDescriptor desc32; - - public MixedEncodingDescriptor(final PrimitiveCoderDescriptor desc32, final PrimitiveCoderDescriptor desc64) { - super(desc64); - this.desc32 = desc32; - } - - @Override public String getDefinition() { return JObjCRuntime.class.getName() + ".IS64 ? " + get64CoderName() + " : " + get32CoderName(); } - @Override public String getCoderAccessor() { return MixedPrimitiveCoderClassFile.FULL_MULTI_CODER_CLASSNAME + "." + getMixedName(); } - String get32CoderName() { return desc32.getCoderInstanceName(); } - @Override public String getCoderInstanceName(){ return getCoderAccessor(); } - @Override public String toString() { return getMixedName(); } - - public String getMixedName() { - final String coder32Name = getBaseNameOfCoder(desc32.primitiveCoderName); - final String coder64Name = getBaseNameOfCoder(desc64.primitiveCoderName); - return coder32Name + coder64Name + "Coder"; - } - - static String getBaseNameOfCoder(final String coderName) { return coderName.substring(0, coderName.indexOf("Coder")); } - public int compareTo(Object _o) { MixedEncodingDescriptor o = (MixedEncodingDescriptor)_o; return getMixedName().compareTo(o.getMixedName()); } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/coders/PrimitiveCoderDescriptor.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/coders/PrimitiveCoderDescriptor.java deleted file mode 100644 index 82684415120..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/coders/PrimitiveCoderDescriptor.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model.coders; - -import java.util.HashMap; -import java.util.Map; - -import com.apple.internal.jobjc.generator.model.types.NType.NPrimitive; -import com.apple.jobjc.Coder; -import com.apple.jobjc.PrimitiveCoder; -import com.apple.jobjc.PrimitiveCoder.BoolCoder; -import com.apple.jobjc.PrimitiveCoder.SCharCoder; -import com.apple.jobjc.PrimitiveCoder.SIntCoder; -import com.apple.jobjc.PrimitiveCoder.SLongCoder; -import com.apple.jobjc.PrimitiveCoder.SLongLongCoder; -import com.apple.jobjc.PrimitiveCoder.SShortCoder; -import com.apple.jobjc.PrimitiveCoder.UCharCoder; -import com.apple.jobjc.PrimitiveCoder.UIntCoder; -import com.apple.jobjc.PrimitiveCoder.ULongCoder; -import com.apple.jobjc.PrimitiveCoder.ULongLongCoder; -import com.apple.jobjc.PrimitiveCoder.UShortCoder; -import com.apple.internal.jobjc.generator.Utils; - -public class PrimitiveCoderDescriptor extends CoderDescriptor { - static Map descriptors = new HashMap(); - - public static PrimitiveCoderDescriptor getCoderDescriptorFor(NPrimitive nt) { - return getCoderDescriptorFor(nt.type); - } - - public static PrimitiveCoderDescriptor getCoderDescriptorFor(char c) { - final PrimitiveCoderDescriptor desc = descriptors.get(c); - if (desc != null) return desc; - final PrimitiveCoderDescriptor newDesc = createCoderDescriptorFor(c); - descriptors.put(c, newDesc); - return newDesc; - } - - public static PrimitiveCoderDescriptor createCoderDescriptorFor(final char encoding) { - switch(encoding) { - case 'B': return new PrimitiveCoderDescriptor(BoolCoder.INST, "false"); - - case 'c': return new PrimitiveCoderDescriptor(SCharCoder.INST, "0"); - case 'C': return new PrimitiveCoderDescriptor(UCharCoder.INST, "0"); - - case 's': return new PrimitiveCoderDescriptor(SShortCoder.INST, "0"); - case 'S': return new PrimitiveCoderDescriptor(UShortCoder.INST, "0"); - - case 'i': return new PrimitiveCoderDescriptor(SIntCoder.INST, "0"); - case 'I': return new PrimitiveCoderDescriptor(UIntCoder.INST, "0"); - - case 'l': return new PrimitiveCoderDescriptor(SLongCoder.INST, "0"); - case 'L': return new PrimitiveCoderDescriptor(ULongCoder.INST, "0", "x86_64: no suitable Java primitive for unsigned long."); - case 'q': return new PrimitiveCoderDescriptor(SLongLongCoder.INST, "0"); - case 'Q': return new PrimitiveCoderDescriptor(ULongLongCoder.INST, "0", "x86_64: no suitable Java primitive for unsigned long long."); - - case 'f': return new PrimitiveCoderDescriptor(PrimitiveCoder.FloatCoder.INST, "0"); - case 'd': return new PrimitiveCoderDescriptor(PrimitiveCoder.DoubleCoder.INST, "0"); - default: throw new RuntimeException("unknown encoding: " + encoding); - } - } - - public final Class javaPrimitiveClazz; - final Class javaObjectClazz; - final String defaultReturnValue; - final String primitiveCoderName; - final String _mismatchMessage; - - public PrimitiveCoderDescriptor(final Coder coder, final String defaultRetVal) { - this(coder, defaultRetVal, null); - } - - public PrimitiveCoderDescriptor(final Coder coder, - final String defaultReturnValue, final String mismatchMessage) { - super(coder, "push", "pop" + Utils.capitalize(coder.getJavaPrimitive().getSimpleName())); - this.javaPrimitiveClazz = coder.getJavaPrimitive(); - this.javaObjectClazz = coder.getJavaClass(); - this.defaultReturnValue = defaultReturnValue; - this.primitiveCoderName = coder.getClass().getSimpleName(); - this._mismatchMessage = mismatchMessage; - } - - @Override public PrimitiveCoder getCoder(){ return (PrimitiveCoder) super.getCoder(); } - @Override public String mismatchMessage(){ return _mismatchMessage; } - @Override public String getDefaultReturnValue() { return defaultReturnValue; } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/JType.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/JType.java deleted file mode 100644 index 56e0f4b2386..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/JType.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model.types; - -import com.apple.internal.jobjc.generator.classes.RootJObjCClass; -import com.apple.internal.jobjc.generator.model.CFType; -import com.apple.internal.jobjc.generator.model.Clazz; -import com.apple.internal.jobjc.generator.model.Opaque; -import com.apple.internal.jobjc.generator.model.Struct; -import com.apple.internal.jobjc.generator.model.coders.CoderDescriptor; -import com.apple.internal.jobjc.generator.model.coders.ComplexCoderDescriptor; -import com.apple.internal.jobjc.generator.model.coders.CoderDescriptor.IDCoderDescriptor; -import com.apple.internal.jobjc.generator.model.coders.CoderDescriptor.NSClassCoderDescriptor; -import com.apple.internal.jobjc.generator.model.coders.CoderDescriptor.PointerCoderDescriptor; -import com.apple.internal.jobjc.generator.model.coders.CoderDescriptor.SELCoderDescriptor; -import com.apple.internal.jobjc.generator.model.coders.CoderDescriptor.StructCoderDescriptor; -import com.apple.internal.jobjc.generator.model.coders.CoderDescriptor.UnknownCoderDescriptor; -import com.apple.internal.jobjc.generator.model.types.NType.NPrimitive; -import com.apple.jobjc.ID; -import com.apple.jobjc.NSClass; -import com.apple.jobjc.NativeArgumentBuffer; -import com.apple.jobjc.Pointer; -import com.apple.jobjc.SEL; - -public abstract class JType { - public abstract String getJavaTypeName(); - public String getJavaClassName() { return getJavaTypeName().substring(getJavaTypeName().lastIndexOf('.') + 1); } - public String getJavaReturnTypeName() { return getJavaTypeName(); } - public String getReturnTypeCast() { return null; } - public String getTypeNameAsParam() { return getJavaTypeName(); } - - public abstract CoderDescriptor getCoderDescriptor(); - public String getDefaultReturnValue() { return "null"; } - public String getAppendableDescription() { return getJavaTypeName().substring(getJavaTypeName().lastIndexOf('.') + 1); } - - /** - * Used for primitive types (like int) that can't be used as generic arguments. This returns an appropriate Java class (like Integer). - */ - public JType getParameterizableType() { return this; } - - // - // Writer ops - // - - public String createDeclareBuffer(String contextName) { - return "final " + NativeArgumentBuffer.class.getName() + " " + contextName + " = getRuntime().getThreadLocalState();"; - } - - public String createInit(final String contextName, final String functionIdentifier, final String initWithObj) { - return functionIdentifier + ".init(" + contextName + (initWithObj != null ? ", " + initWithObj : "") + ");"; - } - - public String createInvoke(final String contextName, final String functionIdentifier) { - return functionIdentifier + ".invoke(" + contextName + ");"; - } - - public String createPop(final String contextName) { - return getCoderDescriptor().getPopStatementFor(contextName, getJavaTypeName(), "returnValue", null); - } - - public String createPopAddr(final String runtime, final String addr) { - return getCoderDescriptor().getPopAddrStatementFor(runtime, addr, getJavaTypeName(), "returnValue", null); - } - - public String createReturn() { - final String preCast = getReturnTypeCast(); - return "return " + (preCast == null ? "" : "(" + preCast + ")") + "returnValue;"; - } - - // - // Specialized - // - - static public class JUnknown extends JType { - final Type type; - protected JUnknown(final Type type) { - this.type = type; - TypeCache.inst().getUnknownTypes().add(type); - } - @Override public String getJavaTypeName() { return "Object /* " + type + " */"; } - @Override public String getAppendableDescription() { return "Unknown"; } - @Override public CoderDescriptor getCoderDescriptor() { return UnknownCoderDescriptor.UNKNOWN_DESC; } - } - - static class JVoid extends JType { - public static JVoid INST = new JVoid(); - @Override public String getJavaTypeName() { return "Void"; } - @Override public String getJavaReturnTypeName() { return "void"; } - @Override public CoderDescriptor getCoderDescriptor(){ return CoderDescriptor.VOID_DESC; } - @Override public String createPop(final String contextName){ return ""; } - @Override public String createReturn(){ return ""; } - }; - - static class JSelector extends JType { - public static JSelector INST = new JSelector(); - @Override public String getJavaTypeName() { return SEL.class.getName(); } - @Override public CoderDescriptor getCoderDescriptor() { return SELCoderDescriptor.INST; } - }; - - static class JCFType extends JType{ - final CFType cfType; - public JCFType(final CFType cfType){ this.cfType = cfType; } - @Override public String getJavaTypeName() { return cfType.parent.pkg + "." + cfType.name + "CFType"; } - @Override public CoderDescriptor getCoderDescriptor() { return PointerCoderDescriptor.INST; } - @Override public String createPop(final String contextName) { - return "\t\t" + getCoderDescriptor().getPopStatementFor(contextName, getJavaReturnTypeName(), "returnValue", "new " + getJavaTypeName()); - } - } - - static class JOpaque extends JType{ - final Opaque opaque; - public JOpaque(final Opaque opaque){ this.opaque = opaque; } - @Override public String getJavaTypeName() { return opaque.parent.pkg + "." + opaque.name + "Opaque"; } - @Override public CoderDescriptor getCoderDescriptor() { return PointerCoderDescriptor.INST; } - @Override public String createPop(final String contextName) { - return "\t\t" + getCoderDescriptor().getPopStatementFor(contextName, getJavaReturnTypeName(), "returnValue", "new " + getJavaTypeName()); - } - } - - static class JPointer extends JType { - static JType VOID_PTR = new JPointer(JVoid.INST); - - final JType subject; - protected JPointer(final JType javaType) { this.subject = javaType; } - - @Override public String getJavaTypeName() { return Pointer.class.getName() + "<" + subject.getParameterizableType().getJavaTypeName() + ">"; } - @Override public String getAppendableDescription() { return "PointerTo" + subject.getAppendableDescription(); } - @Override public CoderDescriptor getCoderDescriptor() { return PointerCoderDescriptor.INST; } - } - - static class JObject extends JType { - public static JType ID_TYPE = new JType() { - @Override public String getJavaTypeName() { return ID.class.getName(); } - @Override public String getJavaReturnTypeName() { return " T"; } - @Override public String getReturnTypeCast() { return "T"; } - @Override public CoderDescriptor getCoderDescriptor() { return IDCoderDescriptor.INST; } - }; - - final Type type; - final Clazz clazz; - - public JObject(final Type type, final Clazz clazz) { - this.type = type; - this.clazz = clazz; - } - - @Override public String getJavaTypeName() { return clazz.getFullPath();} - @Override public CoderDescriptor getCoderDescriptor() { return IDCoderDescriptor.INST; } - } - - static class JClass extends JType { - public static JClass INST = new JClass(); - @Override public String getJavaTypeName() { return NSClass.class.getName(); } - @Override public String getJavaReturnTypeName() { return " T"; } - @Override public String getTypeNameAsParam() { return super.getTypeNameAsParam(); } - @Override public String getReturnTypeCast() { return "T"; } - @Override public CoderDescriptor getCoderDescriptor() { return NSClassCoderDescriptor.INST; } - }; - - public static class JStruct extends JType { - public final Struct struct; - public JStruct(final Struct struct) { this.struct = struct; } - - @Override public String getJavaTypeName() { return struct.parent.pkg + "." + struct.name; } - @Override public String getJavaReturnTypeName() { return getJavaTypeName(); } - - StructCoderDescriptor coderDescriptor = new StructCoderDescriptor(this); - @Override public CoderDescriptor getCoderDescriptor() { return coderDescriptor; } - - public String createReturnValue() { - return "\t\t" + getJavaReturnTypeName() + " returnValue = " + RootJObjCClass.runtimeFrameworkInstR(struct.parent.name) - + ".make" + struct.name + "();"; - } - - @Override public String createInvoke(final String contextName, final String functionIdentifier) { - return createReturnValue() + "\n\t\t" + functionIdentifier + ".invoke(" + contextName + ", returnValue);"; - } - - @Override public String createPop(final String contextName){ return ""; } - } - - public static class JPrimitive extends JType { - final Type type; - final ComplexCoderDescriptor coderDescriptor; - final JType parameterizable; - - public JPrimitive(final Type type, final ComplexCoderDescriptor coderDesc) { - this.type = type; - this.coderDescriptor = coderDesc; - - this.parameterizable = new JType() { - @Override public String getJavaTypeName() { return coderDescriptor.getJavaObjectClass(); } - @Override public CoderDescriptor getCoderDescriptor() { throw new RuntimeException(); } - }; - } - - @Override public String getJavaTypeName() { return coderDescriptor.getName(); } - @Override public String getDefaultReturnValue() { return coderDescriptor.getDefaultReturnValue(); } - @Override public JType getParameterizableType() { return parameterizable; } - @Override public CoderDescriptor getCoderDescriptor() { return coderDescriptor; } - - /** - * Return the suffix placed on java literals to indicate the type. If none applies, return ' '. - */ - public char getLiteralSuffix() { - char t = ((NPrimitive)type.type64).type; - switch(t){ - case 'l': case 'L': case 'f': case 'd': return t; - case 'q': case 'Q': return 'L'; - } - return ' '; - } - } - -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/NType.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/NType.java deleted file mode 100644 index 3c6d644eece..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/NType.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model.types; - -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.apple.internal.jobjc.generator.Utils; -import com.apple.internal.jobjc.generator.model.coders.PrimitiveCoderDescriptor; -import com.apple.internal.jobjc.generator.utils.Fp; -import com.apple.internal.jobjc.generator.utils.NTypePrinter; -import com.apple.internal.jobjc.generator.utils.QA; -import com.apple.jobjc.JObjCRuntime.Width; - -/** - * NType (Native Type) bridges the type and type64 attributes in BridgeSupport. - * - * For example: - * - *

- *   type="c"                 // BridgeSupport attribute
- *   (NPrimitive type: 'c')   // Java object (in sexp form here, for readability)
- *
- *   type="^v"
- *   (NPointer subject: (NVoid))
- *
- *   type="{foo_t="a"c"b"b8"c"[32^v]}"
- *   (NStruct
- *     name: "foo_t"
- *     fields:
- *       (List
- *         0: (NField name:"a" type: (NPrimitive type: 'c'))
- *         1: (NField name:"b" type: (NBitfield size: 8))
- *         2: (NField name:"c" type:
- *              (NArray size: 32
- *                      type: (NPointer subject: (NVoid))))))
- * 
- */ -public abstract class NType implements Comparable{ - public final Map sizeof; - - public NType(Map sizeof) { - this.sizeof = sizeof; - } - - public NType(){ - this(new HashMap()); - } - - public NType(int sz32, int sz64){ - this(); - this.sizeof.put(Width.W32, sz32); - this.sizeof.put(Width.W64, sz32); - } - - public int sizeof32(){ return sizeof.get(Width.W32); } - public int sizeof64(){ return sizeof.get(Width.W64); } - - protected abstract boolean equals2(NType nt); - - private String _toString; - @Override public String toString(){ return _toString != null ? _toString : (_toString = NTypePrinter.inst().print(this)); } - @Override public boolean equals(Object o) { - return o!=null && (o==this || (getClass().isInstance(o) - && this.sizeof.equals(((NType) o).sizeof) - && equals2((NType) o))); - } - public int compareTo(NType o){ return toString().compareTo(o.toString()); } - - // ** NType subclasses - // ------------------- - - public static class NBitfield extends NType{ - public final int length; - - public NBitfield(int length){ - super(-1, -1); - this.length = length; - } - - @Override protected boolean equals2(NType nt) { return ((NBitfield) nt).length == length; } - @Override public int hashCode() { return Integer.valueOf(length).hashCode(); } - } - - public static class NPrimitive extends NType{ - public static Collection CODES = Arrays.asList( - 'B', 'c', 'C', 's', 'S', 'i', 'I', 'l', 'L', 'q', 'Q', 'f', 'd'); - - public final char type; - - protected NPrimitive(char c){ - super(PrimitiveCoderDescriptor.createCoderDescriptorFor(c).getCoder().sizeof(Width.W32), - PrimitiveCoderDescriptor.createCoderDescriptorFor(c).getCoder().sizeof(Width.W64)); - type = c; - } - private static final Map cache = new HashMap(); - public static final NPrimitive inst(final char c){ - if(!cache.containsKey(c)) cache.put(c, new NPrimitive(c)); - return cache.get(c); - } - - @Override protected boolean equals2(NType nt) { return ((NPrimitive)nt).type == type; } - @Override public int hashCode() { return Character.valueOf(type).hashCode(); } - } - - public static class NVoid extends NType{ - protected NVoid(){ super(); } - private final static NVoid INST = new NVoid(); - public static NVoid inst() { return INST; } - - @Override protected boolean equals2(NType nt) { return true; } - } - - public static class NPointer extends NType{ - public final NType subject; - - public NPointer(NType subject){ - super(4, 8); - QA.nonNull(subject); - this.subject = subject; - } - - @Override protected boolean equals2(NType nt) { return ((NPointer)nt).subject.equals(subject); } - @Override public int hashCode() { return subject.hashCode(); } - } - - public static class NObject extends NType{ - protected NObject(){ super(4, 8); } - private final static NObject INST = new NObject(); - public static NObject inst() { return INST; } - - @Override protected boolean equals2(NType nt) { return true; } - } - - public static class NClass extends NType{ - protected NClass(){ super(4, 8); } - private final static NClass INST = new NClass(); - public static NClass inst() { return INST; } - - @Override protected boolean equals2(NType nt) { return true; } - } - - public static class NSelector extends NType{ - protected NSelector(){ super(4, 8); } - private final static NSelector INST = new NSelector(); - public static NSelector inst() { return INST; } - - @Override protected boolean equals2(NType nt) { return true;} - } - - public static class NField{ - public final Map offset; - public final String name; - public final NType type; - - public NField(String name, NType type, Map offset) { - QA.nonNull(name, type, offset); - this.name = name; - this.type = type; - this.offset = offset; - } - - public NField(String name, NType type) { - this(name, type, new HashMap()); - } - - public int offset32(){ return offset.get(Width.W32); } - public int offset64(){ return offset.get(Width.W64); } - - @Override public int hashCode() { return name.hashCode() + type.hashCode(); } - @Override public boolean equals(Object o) { - return o!=null && (o==this || - (o instanceof NField - && this.offset.equals(((NField) o).offset) - && ((NField) o).name.equals(this.name) - && ((NField) o).type.equals(this.type))); - } - } - - public static class NStruct extends NType{ - public final String name; - public final List fields; - - public NStruct(String name, List fields, Map sizeof){ - super(sizeof); - QA.nonNull(name, fields); - this.name = name; - this.fields = fields; - } - - public NStruct(String name, List fields){ - super(); - QA.nonNull(name, fields); - this.name = name; - this.fields = fields; - } - - @Override protected boolean equals2(NType nt) { - return ((NStruct)nt).name.equals(name) && ((NStruct)nt).fields.equals(fields); - } - - @Override public int hashCode() { return name.hashCode() + fields.hashCode(); } - } - - // A Union is like a Struct, but the offset of every field is 0. - public static class NUnion extends NStruct{ - public NUnion(String concreteName, List fields){ - super(concreteName, fields); - assert Fp.all(hasZeroOffsets, fields) : Utils.joinWComma(fields); - } - - public NUnion(String name, List fields, Map sizeof) { - super(name, fields, sizeof); - assert Fp.all(hasZeroOffsets, fields) : Utils.joinWComma(fields); - } - - public static final Fp.Map1 hasZeroOffsets = new Fp.Map1(){ - public Boolean apply(NField a) { - for(int i : a.offset.values()) - if(i != 0) - return false; - return true; - }}; - public static final Fp.Map1 zeroOffsets = new Fp.Map1(){ - public NField apply(NField a) { - Map off = new HashMap(); - for(Width w : a.offset.keySet()) - off.put(w, 0); - return new NField(a.name, a.type, off); - }}; - } - - public static class NArray extends NType{ - public final int length; - public final NType type; - - public NArray(int length, NType type){ - QA.nonNull(type); - this.length = length; - this.type = type; - } - - @Override protected boolean equals2(NType nt) { return ((NArray)nt).length == length && ((NArray)nt).type.equals(type); } - @Override public int hashCode(){ return Long.valueOf(length).hashCode() + type.hashCode(); } - } - - // Seems to be used for callbacks - public static class NUnknown extends NType{ - protected NUnknown(){ super(); } - private final static NUnknown INST = new NUnknown(); - public static NUnknown inst() { return INST; } - - @Override protected boolean equals2(NType nt) { return true;} - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/Type.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/Type.java deleted file mode 100644 index 740e68154b2..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/Type.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model.types; - -import java.util.ArrayList; -import java.util.List; -import java.util.HashMap; -import java.util.Map; - -import com.apple.internal.jobjc.generator.model.types.NType.NObject; -import com.apple.internal.jobjc.generator.model.types.NType.NPointer; -import com.apple.internal.jobjc.generator.model.types.NType.NPrimitive; -import com.apple.internal.jobjc.generator.model.types.NType.NVoid; -import com.apple.internal.jobjc.generator.model.types.NType.NStruct; -import com.apple.internal.jobjc.generator.model.types.NType.NField; -import com.apple.internal.jobjc.generator.utils.NTypeMerger; -import com.apple.internal.jobjc.generator.utils.QA; -import com.apple.internal.jobjc.generator.utils.Fp.Pair; -import com.apple.internal.jobjc.generator.utils.NTypeMerger.MergeFailed; - -public class Type implements Comparable{ - public static Type VOID = Type.getType("void", NVoid.inst(), null); - public static Type VOID_PTR = Type.getType("void*", new NPointer(NVoid.inst()), null); - - final public String name; - final public NType type32; - final public NType type64; - - // HACK BS bug where some types have inconsistent definitions in the metadata, - // e.g. (l / i) in some places and just (l) (and thus (l / l)) in others. - // This is a mapping from the type name to a Type object with the correct definition. - private static final Map exceptions; - static { - exceptions = new HashMap(); - exceptions.put("OSStatus", getType("OSStatus", new NPrimitive('l'), new NPrimitive('i'))); // (l / i) vs. (l) - exceptions.put("CGFloat", getType("CGFloat", new NPrimitive('f'), new NPrimitive('d'))); // (f / d) vs. (f) - exceptions.put("NSRect", getType("NSRect", getNSRectType(), getCGRectType())); // ({{_NSPoint}{_NSSize}} / {{CGPoint}{CGSize}}) vs. ({{_NSPoint}{_NSSize}}) - exceptions.put("NSPoint", getType("NSPoint", getNSPointType(), getCGPointType())); // (_NSPoint / CGPoint) vs. (_NSPoint) - exceptions.put("NSSize", getType("NSSize", getNSSizeType(), getCGSizeType())); // (_NSSize / CGSize) vs. (_NSSize) - exceptions.put("NSInteger", getType("NSInteger", new NPrimitive('i'), new NPrimitive('q'))); // (i / q) vs. (i) - exceptions.put("NSPointArray", getType("NSPointArray", new NPointer(getNSPointType()), new NPointer(getCGPointType()))); // (^_NSPoint / ^CGPoint) vs. (^_NSPoint) - exceptions.put("NSMultibyteGlyphPacking", getType("NSMultibyteGlyphPacking", new NPrimitive('I'), new NPrimitive('Q'))); // (I / Q) vs. (I) - exceptions.put("CFTypeRef", getType("CFTypeRef", new NPointer(NVoid.inst()), new NPointer(NVoid.inst()))); // (^v, ^v) vs. (@, @) - } - - public static Type getType(final String name, final NType t32, final NType t64){ - return TypeCache.inst().pingType(new Type(name, t32, t64)); - } - - private Type(final String name, final NType t32, final NType t64) { - QA.nonNull(t32); - this.name = cleanName(name); - this.type32 = t32; - this.type64 = t64 == null || t32.equals(t64) ? t32 : t64; - } - - private JType _getJType; - public JType getJType() { - return _getJType!=null ? _getJType : (_getJType = TypeToJType.inst().getJTypeFor(TypeCache.inst().pingType(this))); - } - - private String _toString; - @Override public String toString() { - return _toString != null ? _toString : (_toString = name + " " + new Pair(type32, type64).toString()); - } - - @Override public boolean equals(Object o){ - if(o==null || !(o instanceof Type)) return false; - Type t = (Type) o; - return QA.bothNullOrEquals(t.name, this.name) - && t.type32.equals(this.type32) - && t.type64.equals(this.type64); - } - - @Override public int hashCode(){ - return (name == null ? 0 : name.hashCode()) - + type32.hashCode() + type64.hashCode(); - } - - public int compareTo(Type o) { return toString().compareTo(o.toString()); } - - public static Type merge(Type a, Type b) throws MergeFailed{ - if(a!=null && b==null) return a; - if(a==null && b!=null) return b; - if(QA.bothNullOrEquals(a, b)) return a; - if (exceptions.containsKey(a.name)) return exceptions.get(a.name); // HACK BS bug - if(a.name != null && b.name != null && !a.name.equals(b.name)){ - System.out.println("Merging:"); - System.out.println("\ta.....: " + a.toString()); - System.out.println("\tb.....: " + b.toString()); - } - final Type merged = new Type(NTypeMerger.inst().mergeName(a.name, b.name), - NTypeMerger.inst().merge(a.type32, b.type32), - NTypeMerger.inst().merge(a.type64, b.type64)); - if(a.name != null && b.name != null && !a.name.equals(b.name)){ - System.out.println("\tmerged: " + merged.toString()); - } - return merged; - } - - // HACK BS bug where sometimes the name is declared as "id fields = new ArrayList(); - fields.add(new NField("origin", getCGPointType())); - fields.add(new NField("size", getCGSizeType())); - return new NStruct("CGRect", fields); - } - - private static NType getNSRectType() { - List fields = new ArrayList(); - fields.add(new NField("origin", getNSPointType())); - fields.add(new NField("size", getNSSizeType())); - return new NStruct("_NSRect", fields); - } - - private static NType getCGPointType() { - List fields = new ArrayList(); - fields.add(new NField("x", new NPrimitive('d'))); - fields.add(new NField("y", new NPrimitive('d'))); - return new NStruct("CGPoint", fields); - } - - private static NType getNSPointType() { - List fields = new ArrayList(); - fields.add(new NField("x", new NPrimitive('f'))); - fields.add(new NField("y", new NPrimitive('f'))); - return new NStruct("_NSPoint", fields); - } - - private static NType getCGSizeType() { - List fields = new ArrayList(); - fields.add(new NField("width", new NPrimitive('d'))); - fields.add(new NField("height", new NPrimitive('d'))); - return new NStruct("CGSize", fields); - } - - private static NType getNSSizeType() { - List fields = new ArrayList(); - fields.add(new NField("width", new NPrimitive('f'))); - fields.add(new NField("height", new NPrimitive('f'))); - return new NStruct("_NSSize", fields); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/TypeCache.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/TypeCache.java deleted file mode 100644 index dabf0d99ff2..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/TypeCache.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model.types; - -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import com.apple.internal.jobjc.generator.model.CFType; -import com.apple.internal.jobjc.generator.model.Clazz; -import com.apple.internal.jobjc.generator.model.Framework; -import com.apple.internal.jobjc.generator.model.Opaque; -import com.apple.internal.jobjc.generator.model.Struct; -import com.apple.internal.jobjc.generator.utils.Fp.Pair; - -/** - * Central store for types found in the frameworks. - */ -public class TypeCache { - private static TypeCache INST = new TypeCache(); - public static TypeCache inst(){ return INST; } - protected TypeCache(){} - - /** - * When a new Type is discovered, pass it through here to - * hit the cache, potentially merge with other types, etc. - * - * Always do: - * - * Type type = TypeCache.inst().pingType(new Type(a,b,c)); - * - * because this should return a better merge for you. - */ - public Type pingType(final Type type_){ - Type typex = type_; - - // XXX Exception for void* clashes: void* (^{OpaqueCMProfileRef}), void* (^{X}), etc - if("void*".equals(typex.name) && getTypeByName(typex.name)!=null) - return getTypeByName(typex.name); - - if(typex.name != null) - typex = Type.merge(typex, getTypeByName(typex.name)); - else // type.name == null - typex = Type.merge(typex, getTypeByNTypes(new Pair(typex.type32, typex.type64))); - putTypeByName(typex.name, typex); - putTypeByNTypes(new Pair(typex.type32, typex.type64), typex); - return typex; - } - - public final Map typesByName = new HashMap(); - public Type getTypeByName(final String name) { return typesByName.get(Type.cleanName(name)); } - public void putTypeByName(String name, Type type) { if(name!=null) typesByName.put(name, type); } - - public final Map, Type> typesByNTypes = new HashMap, Type>(); - public Type getTypeByNTypes(Pair pair) { return typesByNTypes.get(pair); } - public void putTypeByNTypes(Pair pair, Type type) { if(pair!=null) typesByNTypes.put(pair, type); } - - private final Map classesByName = new HashMap(); - private final Map structsByName = new HashMap(); - private final Map cfTypesByName = new HashMap(); - private final Map opaquesByName = new HashMap(); - - public void load(final List frameworks) { - for (final Framework framework : frameworks) { - for (final Clazz obj : framework.classes) { - final Clazz previous = classesByName.put(obj.name, obj); - if(previous != null) - throw new RuntimeException(String.format( - "TypeCache: naming collision: class name: %1$-10s -- framework1: %2$-10s -- framework2: %3$-10s \n", - obj.name, obj.parent.name, previous.parent.name)); - } - - for (final Struct obj : framework.structs) { - final Struct previous = structsByName.put(obj.name, obj); - if(previous != null) - throw new RuntimeException(String.format( - "TypeCache: naming collision: name: %1$-10s -- type1: %2$-10s -- type2: %3$-10s \n", - obj.name, obj.type, previous.type)); - } - - for (final CFType obj : framework.cfTypes) { - final CFType previous = cfTypesByName.put(obj.name, obj); - if(previous != null) - throw new RuntimeException(String.format( - "TypeCache: naming collision: name: %1$-10s -- type1: %2$-10s -- type2: %3$-10s \n", - obj.name, obj.type, previous.type)); - } - - for (final Opaque obj : framework.opaques) { - final Opaque previous = opaquesByName.put(obj.name, obj); - if(previous != null) - throw new RuntimeException(String.format( - "TypeCache: naming collision: name: %1$-10s -- type1: %2$-10s -- type2: %3$-10s \n", - obj.name, obj.type, previous.type)); - } - } - } - - public Collection getAllClasses() { return classesByName.values(); } - public Clazz getClassForName(final String className) { return classesByName.get(className); } - public Struct getStructForName(final String declaredType) { return structsByName.get(declaredType); } - public CFType getCFTypeForName(final String declaredType) { return cfTypesByName.get(declaredType); } - public Opaque getOpaqueForName(final String declaredType) { return opaquesByName.get(declaredType); } - - final Set unknownTypes = new TreeSet(); - public Set getUnknownTypes() { return unknownTypes; } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/TypeToJType.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/TypeToJType.java deleted file mode 100644 index 82ee3f7aaef..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/model/types/TypeToJType.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.model.types; - -import com.apple.internal.jobjc.generator.model.CFType; -import com.apple.internal.jobjc.generator.model.Clazz; -import com.apple.internal.jobjc.generator.model.Opaque; -import com.apple.internal.jobjc.generator.model.Struct; -import com.apple.internal.jobjc.generator.model.coders.ComplexCoderDescriptor; -import com.apple.internal.jobjc.generator.model.types.JType.JCFType; -import com.apple.internal.jobjc.generator.model.types.JType.JClass; -import com.apple.internal.jobjc.generator.model.types.JType.JObject; -import com.apple.internal.jobjc.generator.model.types.JType.JOpaque; -import com.apple.internal.jobjc.generator.model.types.JType.JPointer; -import com.apple.internal.jobjc.generator.model.types.JType.JPrimitive; -import com.apple.internal.jobjc.generator.model.types.JType.JSelector; -import com.apple.internal.jobjc.generator.model.types.JType.JStruct; -import com.apple.internal.jobjc.generator.model.types.JType.JUnknown; -import com.apple.internal.jobjc.generator.model.types.JType.JVoid; -import com.apple.internal.jobjc.generator.model.types.NType.NClass; -import com.apple.internal.jobjc.generator.model.types.NType.NObject; -import com.apple.internal.jobjc.generator.model.types.NType.NPointer; -import com.apple.internal.jobjc.generator.model.types.NType.NPrimitive; -import com.apple.internal.jobjc.generator.model.types.NType.NSelector; -import com.apple.internal.jobjc.generator.model.types.NType.NStruct; -import com.apple.internal.jobjc.generator.model.types.NType.NVoid; -import com.apple.internal.jobjc.generator.utils.Fp.CacheMap; -import com.apple.internal.jobjc.generator.utils.Fp.Dispatcher; -import com.apple.internal.jobjc.generator.utils.Fp.Map0; - -public class TypeToJType { - private static TypeToJType INST = new TypeToJType(); - public static TypeToJType inst(){ return INST; } - - private CacheMap cache = new CacheMap(); - public JType getJTypeFor(final Type type){ - return cache.get(type, new Map0(){ - public JType apply() { - try { - return Dispatcher.dispatch(TypeToJType.this.getClass(), TypeToJType.this, "accept", type, type.type32, type.type64); - } catch (NoSuchMethodException e) { - return new JUnknown(type); - } - }}); - } - - protected JType accept(Type type, NObject nt32, NObject nt64){ - if ("id".equals(type.name)) return JObject.ID_TYPE; - - final String className = type.name.replaceAll("\\*$", ""); - assert !className.endsWith("*"); - - final Clazz clazz = TypeCache.inst().getClassForName(className); - if (clazz == null) return new JUnknown(type); - // TODO Instead of JUnknown, ID_TYPE might be more appropriate. Investigate. - - return new JObject(type, clazz); - } - - protected JType accept(Type type, NPointer nt32, NPointer nt64){ - final CFType cfType = TypeCache.inst().getCFTypeForName(type.name); - if(cfType != null) return new JCFType(cfType); - - final Opaque opaque = TypeCache.inst().getOpaqueForName(type.name); - if(opaque != null) return new JOpaque(opaque); - - if("void*".equals(type.name)) return JPointer.VOID_PTR; - - if(type.name != null && type.name.endsWith("*")){ - final String subDeclaredType = type.name.substring(0, type.name.length() - 1); - final Type subType = TypeCache.inst().getTypeByName(subDeclaredType); - if (subType == null) return new JUnknown(type); - // TODO Instead of JUnknown, VOID_PTR might be a good fallback. Investigate. - - final JType javaType = TypeToJType.inst().getJTypeFor(subType).getParameterizableType(); - - final JPointer pointer = new JPointer(javaType); - return pointer; - } - - return new JUnknown(type); - } - - protected JType accept(Type type, NPrimitive nt32, NPrimitive nt64){ - final ComplexCoderDescriptor coderDesc = ComplexCoderDescriptor.getCoderDescriptorFor(type.type32, type.type64); - if (coderDesc == null) return null; - return new JPrimitive(type, coderDesc); - } - - protected JType accept(Type type, NVoid nt32, NVoid nt64){ - return JVoid.INST; - } - - protected JType accept(Type type, NSelector nt32, NSelector nt64){ - return JSelector.INST; - } - - protected JType accept(Type type, NClass nt32, NClass nt64){ - return JClass.INST; - } - - protected JType accept(Type type, NStruct nt32, NStruct nt64){ - Struct st = TypeCache.inst().getStructForName(type.name); - return st != null ? new JStruct(st) : new JUnknown(type); - // TODO We could probably generate a struct here based on the type. But we need access to its parent framework. - // Maybe we could use a fallback anonymous struct, but we need the SIZEOF. - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/Fp.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/Fp.java deleted file mode 100644 index 5c7db20c91b..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/Fp.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.utils; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -/** - * Functional programming constructs and utilities. Java for Lisp and Haskell nerds. - */ -public abstract class Fp { - /** - * Multiple dynamic dispatch (multi-methods) for Java. - * - * This is implemented with Java reflection: - * Class.getDeclaredMethod and Method.invoke. - * It is about 20-40 times slower than chains of - * "if instanceof" statements. - */ - public static abstract class Dispatcher{ - /** - * Shorthand, works only if no arg is null. - */ - public static final R dispatch(Class clazz, Object instance, String method, Object... args) throws NoSuchMethodException{ - Class[] types = new Class[args.length]; - for(int i = 0; i < args.length; i++) types[i] = args[i].getClass(); - return (R) dispatch(clazz, instance, method, args, types); - } - - /** - * Dispatch `args` of `types` to `method` on `clazz` for `instance`. If `method` is static, `instance` should be null. - */ - public static final R dispatch(Class clazz, Object instance, String method, Object[] args, Class[] types) throws NoSuchMethodException{ - try{ - java.lang.reflect.Method m = clazz.getDeclaredMethod(method, types); - m.setAccessible(true); - return (R) m.invoke(instance, args); - } - catch(NoSuchMethodException x){ - if(clazz.getSuperclass() != null) return (R) dispatch(clazz.getSuperclass(), instance, method, args, types); - else throw x; - } - catch(Exception x){ - throw new RuntimeException(x); - } - } - } - - /** - * The "Maybe" type encapsulates an optional value. A value of type - * "Maybe a" either contains a value of type "a" (represented as "Just a"), - * or it is empty (represented as "Nothing"). - * - * http://haskell.org/ghc/docs/latest/html/libraries/base/Data-Maybe.html - */ - public static abstract class Maybe{ - public abstract boolean isJust(); - public abstract boolean isNothing(); - public abstract A fromJust() throws ClassCastException; - public abstract A fromMaybe(final A fallback); - - public static class Nothing extends Maybe{ - @Override public A fromJust() throws ClassCastException { throw new ClassCastException("Cannot extract value from Nothing."); } - @Override public A fromMaybe(A fallback) { return fallback; } - @Override public boolean isJust() { return false; } - @Override public boolean isNothing() { return true; } - } - public static class Just extends Maybe{ - public final A a; - public Just(A a){ this.a = a; } - @Override public A fromJust(){ return a; } - @Override public A fromMaybe(A fallback) { return a; } - @Override public boolean isJust() { return true; } - @Override public boolean isNothing() { return false; } - } - } - - public static class NonNull{ - public final A obj; - public NonNull(A o){ - if(o==null) throw new RuntimeException("o may not be null."); - this.obj = o; - } - } - - // Closures - public static interface Map0{ A apply(); } - public static interface Map1{ B apply(final A a); } - public static interface Map2{ C apply(final A a, final B b); } - - public static class CacheMap,V>{ - private Map cache = new TreeMap(); - public V get(K key, Map0 create){ - if(cache.containsKey(key)) return cache.get(key); - V value = create.apply(); - cache.put(key, value); - return value; - } - } - - public static class Curry2to1 implements Map1{ - private Map2 target; private A a; - public Curry2to1(Map2 targett, A aa) { target = targett; a = aa; } - public C apply(B b) { return target.apply(a, b); } - } - - // Tuple - public static class Pair implements Comparable>{ - public final A a; public final B b; - public Pair(final A aa, final B bb){ a=aa; b=bb; } - @Override public int hashCode(){ return (a==null ? 0 : a.hashCode()) + (b==null ? 0 : b.hashCode()); } - @Override public boolean equals(Object o){ - if(!(o instanceof Pair)) return false; - Pair p = (Pair) o; - return QA.bothNullOrEquals(a, p.a) && QA.bothNullOrEquals(b, p.b); - } - @Override public String toString(){ return "(" + a + ", " + b + ")"; } - public int compareTo(Pair o){ return toString().compareTo(o.toString()); } - } - - /** - * @return [fn(x) | x <- items] - */ - public static List map(Map1 fn, final Collection xs){ - ArrayList rs = new ArrayList(xs.size()); - for(A x : xs) rs.add(fn.apply(x)); - return rs; - } - - public static List map2(Map2 fn, final Collection as, final Collection bs){ - assert as.size() == bs.size(); - ArrayList cs = new ArrayList(as.size()); - Iterator aiter = as.iterator(); - Iterator biter = bs.iterator(); - while(aiter.hasNext() && biter.hasNext()) - cs.add(fn.apply(aiter.next(), biter.next())); - return cs; - } - - /** - * Same as map, but does not retain results. - */ - public static void each(Map1 fn, final Collection xs){ - for(A x : xs) fn.apply(x); - } - - /** - * @return [x | x <- items, take(x)] - */ - public static List filter(Map1 take, final Collection xs){ - List rs = new ArrayList(xs.size()); - for(A x : xs) if(take.apply(x)) rs.add(x); - return rs; - } - - /** - * @return [x | x <- items, take(x)] - */ - public static Set filterSet(Map1 take, final Collection xs){ - Set rs = new HashSet(xs.size()); - for(A x : xs) if(take.apply(x)) rs.add(x); - return rs; - } - - /** - * @return the first x in items that satisfies take(x), or null if none - */ - public static X find(Map1 take, final Collection xs){ - for(X x : xs) if(take.apply(x)) return x; - return null; - } - - public static A foldl(final Map2 f, A a, final Collection xs){ - for(B b : xs) a = f.apply(a, b); - return a; - } - - /** - * @return All x : p(x) == true - */ - public static boolean all(Map1 p, Collection xs) { - for(A x : xs) if(!p.apply(x)) return false; - return true; - } - - /** - * @return Any x : p(x) == true - */ - public static boolean any(Map1 p, Collection xs) { - for(A x : xs) if(p.apply(x)) return true; - return false; - } - - public static String join(final String sep, final Collection xs) { - if(xs.size() == 0) return ""; - if(xs.size() == 1) return xs.iterator().next().toString(); - return Fp.foldl(new Fp.Map2(){ - public String apply(String a, A b) { - String sb = b==null? "null" : b.toString(); - return a == null ? sb : a + sep + sb; - }}, null, xs); - } - - public static Map2 operatorPlus = new Map2(){ - public Integer apply(Integer a, Integer b) { return (int)a + (int)b;} - }; - - public static int sum(Collection xs){ return foldl(operatorPlus, 0, xs); } - - public static List append(Collection xs, Collection ys) { - List rs = new ArrayList(xs.size() + ys.size()); - rs.addAll(xs); - rs.addAll(ys); - return rs; - } - - public static Set appendSet(Collection xs, Collection ys) { - Set rs = new HashSet(xs.size() + ys.size()); - rs.addAll(xs); - rs.addAll(ys); - return rs; - } - - public static Map litMap(K key, V value, Object... pairs){ - Map ret = new HashMap(1 + pairs.length/2); - ret.put(key, value); - for(int i = 0; i < pairs.length; i += 2) - ret.put(pairs[i], pairs[i+1]); - return ret; - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/JavaLang.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/JavaLang.java deleted file mode 100644 index 799ab7770d3..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/JavaLang.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.utils; - -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -import com.apple.internal.jobjc.generator.Utils; -import com.apple.internal.jobjc.generator.Utils.Substituter; - -/** - * Utility for generating Java source code. - */ -public abstract class JavaLang { - - public static String makeSingleton(final String instanceVariable, final String methodName, final String className, final String...constructorArgs) { - return generateSingleton(new Substituter( - "#private $CLASS $IVAR = null;~" + - "#public $CLASS $METHOD() {~" + - "##return $IVAR != null ? $IVAR : ($IVAR = new $CLASS($CTORARGS));~" + - "#}~"), - instanceVariable, methodName, className, constructorArgs); - } - - public static String makeStaticSingleton(final String instanceVariable, final String methodName, final String className, final String...constructorArgs) { - return generateSingleton(new Substituter( - "#private static $CLASS $IVAR = null;~" + - "#public static $CLASS $METHOD() {~" + - "##return $IVAR != null ? $IVAR : ($IVAR = new $CLASS($CTORARGS));~" + - "#}~"), - instanceVariable, methodName, className, constructorArgs); - } - - private static String generateSingleton(final Substituter singleton, final String instanceVariable, final String methodName, final String className, final String...constructorArgs) { - singleton.replace("IVAR", instanceVariable); - singleton.replace("METHOD", methodName); - singleton.replace("CLASS", className); - singleton.replace("CTORARGS", Utils.joinWComma(constructorArgs)); - return singleton.toString(); - } - - /// - - public static class JLTertiary{ - public Object cond, tExp, fExp; - public JLTertiary(){} - public JLTertiary(Object cond, Object tExp, Object fExp){ - this.cond = cond; - this.tExp = tExp; - this.fExp = fExp; - } - @Override public String toString() { - return "((" + cond + ")\n\t? (" + tExp + ")\n\t: (" + fExp + "))"; - } - } - - public static class JLCall{ - public String fun; - public List args = new ArrayList(); - public JLCall(String fun, Object... args){ - this.fun = fun; - this.args.addAll(Arrays.asList(args)); - } - @Override public String toString(){ - return fun + "(" + Fp.join(", ", args) + ")"; - } - } - - public static class JLField{ - public Set mods = new TreeSet(); - public String type; - public String name; - public Object value; - - public JLField(String mods, String type, String name){ - this(mods, type, name, null); - } - - public JLField(String mods, String type, String name, Object value){ - this.mods.addAll(Arrays.asList(mods.split("\\s"))); - this.type = type; - this.name = name; - this.value = value; - } - - @Override public String toString(){ - return "\t" + Fp.join(" ", mods) + " " + type + " " + name + (value==null ? "" : " = " + value) + ";\n"; - } - } - - public static class JLCtor extends JLMethod{ - public JLCtor(String mods, String name, Object... args) { - super(mods, "", name, args); - } - - @Override public String toString(){ - this.type = ""; - return super.toString(); - } - } - - public static class JLReturn{ - public Object target; - public JLReturn(Object target){ - this.target = target; - } - @Override public String toString(){ - return "return " + target + ";"; - } - } - - public static class JLMethod{ - public List jdoc = new ArrayList(); - public Set attrs = new TreeSet(); - public Set mods = new TreeSet(); - public String type; - public String name; - public List args = new ArrayList(); - public List body = new ArrayList(); - - public JLMethod(){} - public JLMethod(String mods, String type, String name, Object... args) { - this.mods.addAll(Arrays.asList(mods.split("\\s"))); - this.type = type; - this.name = name; - this.args.addAll(Arrays.asList(args)); - } - - @Override public String toString(){ - StringWriter out = new StringWriter(); - if(jdoc.size() > 0){ - out.append("\t/**\n"); - out.append("\t * " + Fp.join("\n\t * ", jdoc)); - out.append("\t */\n"); - } - out.append("\t" + Fp.join(" ", attrs) + " " + Fp.join(" ", mods) + " " + type + " " + name + "(" + Fp.join(", ", args) + "){\n"); - out.append("\t\t" + Fp.join("\n\t\t", body) + "\n"); - out.append("\t}\n"); - return out.toString(); - } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/NTypeMerger.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/NTypeMerger.java deleted file mode 100644 index a1ad5658050..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/NTypeMerger.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.utils; - -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.apple.internal.jobjc.generator.model.types.NType; -import com.apple.internal.jobjc.generator.model.types.NType.NArray; -import com.apple.internal.jobjc.generator.model.types.NType.NBitfield; -import com.apple.internal.jobjc.generator.model.types.NType.NClass; -import com.apple.internal.jobjc.generator.model.types.NType.NField; -import com.apple.internal.jobjc.generator.model.types.NType.NObject; -import com.apple.internal.jobjc.generator.model.types.NType.NPointer; -import com.apple.internal.jobjc.generator.model.types.NType.NPrimitive; -import com.apple.internal.jobjc.generator.model.types.NType.NSelector; -import com.apple.internal.jobjc.generator.model.types.NType.NStruct; -import com.apple.internal.jobjc.generator.model.types.NType.NUnion; -import com.apple.internal.jobjc.generator.model.types.NType.NUnknown; -import com.apple.internal.jobjc.generator.model.types.NType.NVoid; -import com.apple.internal.jobjc.generator.utils.Fp.Dispatcher; -import com.apple.internal.jobjc.generator.utils.Fp.Map2; -import com.apple.jobjc.JObjCRuntime.Width; - -/** - * Merges two NTypes. All merge does is fill out missing information. It doesn't choose the larger primitive when there's a conflict or anything like that. - * - * Example: - *
- * a: {_NSRect={_NSPoint="x"f"y"f}"size"{_NSSize=ff}}
- * b: {_NSRect="origin"{_NSPoint=ff}{_NSSize="width"f"height"f}}
- * c: {_NSRect="origin"{_NSPoint="x"f"y"f}"size"{_NSSize="width"f"height"f}}
- *
- */ -public class NTypeMerger { - public static class MergeFailed extends RuntimeException{ - public MergeFailed(String reason, Object a, Object b){ - super(reason - + " -- (" + a.getClass().getSimpleName() + ") a: " + a - + " -- (" + b.getClass().getSimpleName() + ") b: " + b); - } - } - - private static NTypeMerger INST = new NTypeMerger(); - public static NTypeMerger inst(){ return INST; } - - /** - * Merge a and b. - */ - public NType merge(NType a, NType b) throws MergeFailed{ - if(a!=null && b==null) return a; - if(a==null && b!=null) return b; - if(a==null && b==null) return null; - if(a.equals(b)) return a; - try { - return Dispatcher.dispatch(getClass(), this, "accept", a, b); - } catch (NoSuchMethodException e) { - throw new MergeFailed("a and b are of different NType", a, b); - } - } - - private static Collection emptyNames = Arrays.asList(null, "", "?"); - /** - * Merge two identifiers: - * - If they're equal, return one. - * - If one is null, "", "?", return the other one. - * - else throw MergeFailed - * - * Exception: Due to a bug in BridgeSupport, this will return - * a (the first arg) instead of throwing MergeFailed. - */ - public String mergeName(String a, String b) throws MergeFailed{ - if(QA.bothNullOrEquals(a, b)) return a; - if(emptyNames.contains(a) && !emptyNames.contains(b)) return b; - if(emptyNames.contains(b) && !emptyNames.contains(a)) return a; - return a; // HACK BS bug #5954843 -// throw new MergeFailed("a and b have different names"); - } - - private Map mergeMap(Map a, Map b) throws MergeFailed{ - if(a.equals(b)) return a; - Map ret = new HashMap(); - Set keys = new HashSet(Fp.append(a.keySet(), b.keySet())); - for(Object key : keys){ - Object ai = a.get(key); - Object bi = b.get(key); - if(ai != null && bi == null) ret.put(key, ai); - else if(ai == null && bi != null) ret.put(key, bi); - else if(ai.equals(bi)) ret.put(key, ai); - else throw new MergeFailed("a and b are different", ai, bi); - } - return ret; - } - - public Map mergeSizeOf(Map a, Map b) throws MergeFailed{ - return mergeMap(a, b); - } - - public Map mergeOffset(Map a, Map b) throws MergeFailed{ - return mergeMap(a, b); - } - - // - - private void mustEqual(NType a, NType b){ - if(!a.equals(b)) throw new MergeFailed("a must equal b", a, b); - } - - protected NType accept(NBitfield a, NBitfield b) { - mustEqual(a, b); - return a; - } - - protected NType accept(NPrimitive a, NPrimitive b) { - mustEqual(a, b); - return a; - } - - protected NType accept(NPointer a, NPointer b) { - return new NPointer(NTypeMerger.inst().merge(a.subject, b.subject)); - } - - // Merge structs - - protected NField mergeNFields(NField a, NField b) { - return new NField(mergeName(a.name, b.name), - NTypeMerger.inst().merge(a.type, b.type), - mergeOffset(a.offset, b.offset)); - } - - protected NStruct mergeStructs(NStruct a, NStruct b){ - if(a.fields.size() != b.fields.size()) - throw new MergeFailed("a and b have different numbers of fields", a, b); - - List fields = Fp.map2(new Map2(){ - public NField apply(NField f32, NField f64) { return mergeNFields(f32, f64); } - }, a.fields, b.fields); - - return new NStruct(mergeName(a.name, b.name), - fields, mergeSizeOf(a.sizeof, b.sizeof)); - } - - protected NType accept(NStruct a, NStruct b) { - return mergeStructs(a, b); - } - - protected NType accept(NUnion a, NUnion b) { - NStruct nst = mergeStructs(a, b); - return new NUnion(nst.name, Fp.map(NUnion.zeroOffsets, nst.fields), nst.sizeof); - } - - protected NType accept(NArray a, NArray b) { - if(a.length != b.length) - throw new MergeFailed("a and b are of different sizes", a, b); - return new NArray(a.length, NTypeMerger.inst().merge(a.type, b.type)); - } - - protected NType accept(NVoid a, NVoid b) { return NVoid.inst(); } - protected NType accept(NObject a, NObject b) { return NObject.inst(); } - protected NType accept(NClass a, NClass b) { return NClass.inst(); } - protected NType accept(NSelector a, NSelector b) { return NSelector.inst(); } - protected NType accept(NUnknown a, NUnknown b) { return NUnknown.inst(); } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/NTypeParser.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/NTypeParser.java deleted file mode 100644 index 850076280a2..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/NTypeParser.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.utils; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.apple.internal.jobjc.generator.model.types.NType; -import com.apple.internal.jobjc.generator.model.types.NType.NArray; -import com.apple.internal.jobjc.generator.model.types.NType.NBitfield; -import com.apple.internal.jobjc.generator.model.types.NType.NClass; -import com.apple.internal.jobjc.generator.model.types.NType.NObject; -import com.apple.internal.jobjc.generator.model.types.NType.NPointer; -import com.apple.internal.jobjc.generator.model.types.NType.NPrimitive; -import com.apple.internal.jobjc.generator.model.types.NType.NSelector; -import com.apple.internal.jobjc.generator.model.types.NType.NStruct; -import com.apple.internal.jobjc.generator.model.types.NType.NUnion; -import com.apple.internal.jobjc.generator.model.types.NType.NUnknown; -import com.apple.internal.jobjc.generator.model.types.NType.NVoid; - -/** - * NTypeParser (Native Type Parser) parses type & type64 attributes from BridgeSupport. - * - * See Obj-C Language: Type Encodings - */ -public abstract class NTypeParser { - // ** Parser entry point - - private static Map cached = new HashMap(); - public static NType parseFrom(String s) { - if(!cached.containsKey(s)) cached.put(s, parseFrom(new StringStream(s))); - return cached.get(s); - } - - // ** Parser driver - - private static List PARSERS = new ArrayList( - Arrays.asList(new NBitfieldParser(), new NPrimitiveParser(), new NVoidParser(), - new NPointerParser(), new NStructParser(), new NUnionParser(), - new NObjectParser(), new NClassParser(), new NSelectorParser(), - new NArrayParser(), new NUnknownParser(), new NSpecifierParser())); - - protected static NType parseFrom(StringStream ss) { - if(ss.left() == 0) - return null; - try{ - for(NTypeParser nt : PARSERS) - if(nt.parsePossible(ss)) - return nt.parse(ss); - } - catch(RuntimeException x){ - throw new RuntimeException("Exception while parsing '" + ss.remainingToString() - + "' from '" + ss.toString() + "'", x); - } - throw new RuntimeException("Found no parser for '" + ss.remainingToString() - + "' from '" + ss.toString() + "'"); - } - - // ** Methods for parsers - - protected abstract boolean parsePossible(StringStream ss); - protected abstract NType parse(StringStream ss); - - // ** Individual parsers - - public static class NBitfieldParser extends NTypeParser{ - @Override protected boolean parsePossible(StringStream ss) { - return ss.left() >= 2 && ss.peekAt(0) == 'b' && Character.isDigit(ss.peekAt(1)); - } - - @Override protected NType parse(StringStream ss) { - assert parsePossible(ss); - ss.eat('b'); - return new NBitfield(Integer.parseInt(ss.readWhileDigits())); - } - } - - public static class NPrimitiveParser extends NTypeParser{ - @Override protected boolean parsePossible(StringStream ss) { - return NPrimitive.CODES.contains(ss.peek()); - } - - @Override protected NType parse(StringStream ss) { - assert parsePossible(ss); - return NPrimitive.inst(ss.read()); - } - } - - public static class NVoidParser extends NTypeParser{ - @Override protected boolean parsePossible(StringStream ss) { - return ss.peek() == 'v'; - } - - @Override protected NType parse(StringStream ss) { - ss.eat('v'); - return NVoid.inst(); - } - } - - public static class NPointerParser extends NTypeParser{ - private static NPointer CHAR_PTR = new NPointer(NPrimitive.inst('C')); - - @Override protected boolean parsePossible(StringStream ss) { - return (ss.left() >= 2 && ss.peek() == '^') || (ss.peek() == '*'); - } - - @Override protected NType parse(StringStream ss) { - if(ss.peek() == '*'){ - ss.eat('*'); - return CHAR_PTR; - } - else{ - ss.eat('^'); - return new NPointer(NTypeParser.parseFrom(ss)); - } - } - } - - public static class NStructParser extends NTypeParser{ - protected char getOpen(){ return '{'; }; - protected char getClose(){ return '}'; }; - - @Override protected boolean parsePossible(StringStream ss) { - return ss.left() >= 2 && ss.peek() == getOpen(); - } - - @Override protected NType parse(StringStream ss) { - assert parsePossible(ss); - // {_NSRect= - // "origin"{_NSPoint="x"f"y"f} - // "size"{_NSSize="width"f"height"f}} - ss.eat(getOpen()); - String cname = ss.readUntilEither("=" + getClose()); - List fields = new ArrayList(); - if(ss.peek() == '='){ - ss.eat('='); - while(ss.peek() != getClose()){ - String fname = ""; - if(ss.peek() == '"'){ - ss.eat('"'); - fname = ss.readUntil('"'); - ss.eat('"'); - } - NType type = NTypeParser.parseFrom(ss); - fields.add(new NStruct.NField(fname, type)); - } - } - ss.eat(getClose()); - return getNew(cname, fields); - } - - protected NType getNew(String cname, List fields){ - return new NStruct(cname, fields); - } - } - - // A Union is very much like a Struct. - public static class NUnionParser extends NStructParser{ - @Override protected char getOpen(){ return '('; }; - - @Override protected char getClose(){ return ')'; }; - - @Override protected NType getNew(String cname, List fields){ - return new NUnion(cname, Fp.map(NUnion.zeroOffsets, fields)); - } - } - - public static class NArrayParser extends NTypeParser{ - @Override protected boolean parsePossible(StringStream ss) { - return ss.peek() == '['; - } - - @Override protected NType parse(StringStream ss) { - ss.eat('['); - int size = Integer.parseInt(ss.readWhileDigits()); - NType type = NTypeParser.parseFrom(ss); - ss.eat(']'); - return new NArray(size, type); - } - } - - public static class NObjectParser extends NTypeParser{ - @Override protected boolean parsePossible(StringStream ss) { - return ss.peek() == '@'; - } - - @Override protected NType parse(StringStream ss) { - ss.eat('@'); - return NObject.inst(); - } - } - - public static class NClassParser extends NTypeParser{ - @Override protected boolean parsePossible(StringStream ss) { - return ss.peek() == '#'; - } - - @Override protected NType parse(StringStream ss) { - ss.eat('#'); - return NClass.inst(); - } - } - - public static class NSelectorParser extends NTypeParser{ - @Override protected boolean parsePossible(StringStream ss) { - return ss.peek() == ':'; - } - - @Override protected NType parse(StringStream ss) { - ss.eat(':'); - return NSelector.inst(); - } - } - - public static class NUnknownParser extends NTypeParser{ - @Override protected boolean parsePossible(StringStream ss) { - return ss.peek() == '?'; - } - - @Override protected NType parse(StringStream ss) { - ss.eat('?'); - return NUnknown.inst(); - } - } - - /** - * Specifier Encoding - * const r - * in n - * inout N - * out o - * bycopy O - * oneway V - */ - public static class NSpecifierParser extends NTypeParser{ - private static Collection SPECS = Arrays.asList('r', 'n', 'N', 'o', 'O', 'V'); - @Override protected boolean parsePossible(StringStream ss) { - return SPECS.contains(ss.peek()); - } - - @Override protected NType parse(StringStream ss) { - assert parsePossible(ss); - ss.seek(); // XXX Just ignore specs for now and return the affected type. - return NTypeParser.parseFrom(ss); - } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/NTypePrinter.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/NTypePrinter.java deleted file mode 100644 index 07ba7259e37..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/NTypePrinter.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.utils; - -import java.io.StringWriter; - -import com.apple.internal.jobjc.generator.model.types.NType; -import com.apple.internal.jobjc.generator.model.types.NType.NArray; -import com.apple.internal.jobjc.generator.model.types.NType.NBitfield; -import com.apple.internal.jobjc.generator.model.types.NType.NClass; -import com.apple.internal.jobjc.generator.model.types.NType.NField; -import com.apple.internal.jobjc.generator.model.types.NType.NObject; -import com.apple.internal.jobjc.generator.model.types.NType.NPointer; -import com.apple.internal.jobjc.generator.model.types.NType.NPrimitive; -import com.apple.internal.jobjc.generator.model.types.NType.NSelector; -import com.apple.internal.jobjc.generator.model.types.NType.NStruct; -import com.apple.internal.jobjc.generator.model.types.NType.NUnion; -import com.apple.internal.jobjc.generator.model.types.NType.NUnknown; -import com.apple.internal.jobjc.generator.model.types.NType.NVoid; -import com.apple.internal.jobjc.generator.utils.Fp.Dispatcher; - -/** - * Print an NType to the BridgeSupport encoding. - */ -public class NTypePrinter{ - private static NTypePrinter INST = new NTypePrinter(); - public static NTypePrinter inst(){ return INST; } - - public String print(NType nt){ - try { - return Dispatcher.dispatch(getClass(), this, "accept", nt); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - } - - protected String accept(NBitfield nt) { - return "b" + nt.length; - } - - protected String accept(NPrimitive nt) { - return Character.toString(nt.type); - } - - protected String accept(NPointer nt) { - if(nt.subject instanceof NPrimitive && ((NPrimitive) nt.subject).type == 'C') - return "*"; - else - return "^" + print(nt.subject); - } - - protected String printStruct(NStruct nt, char open, char close){ - StringWriter sw = new StringWriter(); - sw.append(open); - sw.append(nt.name); - if(nt.fields.size() > 0){ - sw.append('='); - for(NField f : nt.fields){ - if(f.name != null && f.name.length() > 0) - sw.append("\"" + f.name + "\""); - sw.append(print(f.type)); - } - } - sw.append(close); - return sw.toString(); - } - - protected String accept(NStruct nt) { - return printStruct(nt, '{', '}'); - } - - protected String accept(NUnion nt) { - return printStruct(nt, '(', ')'); - } - - protected String accept(NArray nt) { - return "[" + nt.length + print(nt.type) + "]"; - } - - protected String accept(NObject nt) { return "@"; } - protected String accept(NVoid nt) { return "v"; } - protected String accept(NClass nt) { return "#"; } - protected String accept(NSelector nt) { return ":"; } - protected String accept(NUnknown nt) { return "?"; } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/ObjectInspector.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/ObjectInspector.java deleted file mode 100644 index e54ba340987..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/ObjectInspector.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.utils; - -import java.io.StringWriter; -import java.lang.reflect.Field; - -public abstract class ObjectInspector { - /** - * @return a string representation of object internals. - */ - public static String inspect(Object obj) { - StringWriter sw = new StringWriter(); - inspectForClass(obj, obj.getClass(), sw); - return sw.toString(); - } - - private static void inspectForClass(Object instance, Class clazz, StringWriter sw){ - boolean willGoSuper = clazz.getSuperclass() != null && !clazz.getSuperclass().getName().equals("java.lang.Object"); - - sw.append(clazz.getSimpleName()); - sw.append("{"); - Field[] fs = clazz.getDeclaredFields(); - for(int i = 0; i < fs.length; i++){ - Field f = fs[i]; - f.setAccessible(true); - sw.append(f.getName()); - sw.append(": "); - try { - Object o = f.get(instance); - sw.append(o == null ? "null" : o.toString()); - } catch (IllegalArgumentException ex) { - throw new RuntimeException(ex); - } catch (IllegalAccessException ex) { - throw new RuntimeException(ex); - } - if(i < fs.length - 1 || willGoSuper) - sw.append(", "); - } - - if(willGoSuper){ - sw.append("super: "); - inspectForClass(instance, clazz.getSuperclass(), sw); - } - - sw.append("}"); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/StringStream.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/StringStream.java deleted file mode 100644 index 448d4be12e6..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/StringStream.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.utils; - -import java.io.StringWriter; - -/** - * Stream-like class backed by a string. Useful for parsers. - */ -public class StringStream{ - private String data; - private int pos; - - public StringStream(String s){ - QA.nonNull(s); - this.data = s; - this.pos = 0; - } - - /** - * Number of characters left. - */ - public int left(){ return data.length() - pos; } - - /** - * Are there any characters left? - */ - public boolean atEOF(){ return left() <= 0; } - - /** - * Read next character. - */ - public char read(){ return data.charAt(pos++); } - - /** - * Read n characters and return string. - */ - public String readN(int n){ - String s = data.substring(pos, pos + n); - pos += n; - return s; - } - - /** - * Read until the next char is c, and return the string. - */ - public String readUntil(char c){ - int ix = data.indexOf(c, pos); - if(ix == -1) throw new RuntimeException("readUntil did not find character '" + c + "'"); - return readN(data.indexOf(c, pos) - pos); - } - - /** - * Read until the next char is one in s, and return the string. - */ - public String readUntilEither(String s) { - int ix = Integer.MAX_VALUE; - - for(char c : s.toCharArray()){ - int ixx = data.indexOf(c, pos); - if(ixx >= 0 && ixx < ix) - ix = ixx; - } - - if(ix == -1) throw new RuntimeException("readUntilEither did not find any character in '" + s + "'"); - return readN(ix - pos); - } - - public String readWhile(String s) { - StringWriter sw = new StringWriter(); - while(s.indexOf(peek()) != -1) - sw.append(read()); - return sw.toString(); - } - - public String readWhileDigits() { - return readWhile("0123456789"); - } - - /** - * @return the nth char from the current position. - */ - public char peekAt(int n){ return data.charAt(pos + n); } - - /** - * @return the next n chars. - */ - public String peekN(int n){ return data.substring(pos, pos + n); } - - /** - * @return the next char. - */ - public char peek(){ return peekAt(0); } - - /** - * Skip n chars ahead. - */ - public void seekN(int n){ pos += n; } - - /** - * Skip 1 char ahead. - */ - public void seek(){ seekN(1); } - - /** - * If the next character is c, seek over it. Otherwise throw RuntimeException. - */ - public void eat(char c) { - if(peek() != c) throw new RuntimeException("Parser expected '" + c + "' but got '" + peek() + "'."); - seek(); - } - - /** - * If the next characters are the same as those in s, seek over them. Otherwise throw RuntimeException. - */ - public void eat(String s) { - String pn = peekN(s.length()); - if(!pn.equals(s)) throw new RuntimeException("Parser expected '" + s + "' but got '" + pn + "'."); - seekN(s.length()); - } - - @Override - public String toString(){ - return data; - } - - /** - * @return the remaining characters as a String. - */ - public String remainingToString() { - return data.substring(pos); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/StructOffsetResolver.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/StructOffsetResolver.java deleted file mode 100644 index c207aae323a..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/StructOffsetResolver.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.utils; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileWriter; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.util.Arrays; -import java.util.Collection; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.apple.internal.jobjc.generator.Utils; -import com.apple.internal.jobjc.generator.model.Framework; -import com.apple.internal.jobjc.generator.model.Struct; -import com.apple.internal.jobjc.generator.model.types.NType; -import com.apple.internal.jobjc.generator.model.types.TypeCache; -import com.apple.internal.jobjc.generator.model.types.NType.NField; -import com.apple.internal.jobjc.generator.model.types.NType.NStruct; -import com.apple.internal.jobjc.generator.utils.Fp.Map1; -import com.apple.jobjc.JObjCRuntime.Width; -import java.util.Date; - -/** - * Takes a framework, compiles a native source file with all its structs, - * and figures out their sizes and field offsets. - */ -public class StructOffsetResolver { - public void resolve(Collection fws){ - try { - _resolve(fws); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - protected void _resolve(final Collection fws) throws Exception{ - for(final Framework fw : fws){ - for(final Width width : Width.values()){ - System.out.println("SOR -- Getting Struct offsets @" + width + " for " + fw.name); - String nativeSrc = generateFileForFramework(fw, width); - String executable = compileObjC(nativeSrc, width); - execute(executable, new Map1(){ - public Object apply(String ln) { - try { - processLine(ln, fws, width); - return null; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }); - } - } - } - - static Set alwaysHeaders_shared = new TreeSet(Arrays.asList( - "", - "\"/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/HIToolbox.h\"")); - static Map> alwaysHeaders = Fp.litMap( - Width.W32, alwaysHeaders_shared, - Width.W64, alwaysHeaders_shared); - - static Set bannedHeaders_shared = new TreeSet(Arrays.asList( - "NSJavaSetup.h", "IMKInputController.h", "NSSimpleHorizontalTypesetter.h", "NSSpellServer.h", "IMKServer.h", "IKImageBrowserCell.h")); - static Map> bannedHeaders = Fp.litMap( - Width.W32, bannedHeaders_shared, - Width.W64, Fp.appendSet(bannedHeaders_shared, - Arrays.asList("npapi.h", "npruntime.h", "npfunctions.h"))); - - // We can cache the last accessed framework because, 99% of the time, - // the caller will ask for the same one, over and over again. - protected Framework cachedFw; - protected Framework findFrameworkByName(Collection fws, String name){ - if(cachedFw != null && cachedFw.name.equals(name)) - return cachedFw; - cachedFw = null; - for(Framework fw : fws) - if(fw.name.equals(name)){ - cachedFw = fw; - break; - } - return cachedFw; - } - - protected void processLine(String ln, Collection fws, Width arch) throws Exception{ - System.out.println("\tSOR '" + ln + "'"); - if(ln.trim().length() == 0) return; - Pattern stinfo = Pattern.compile("^(.*) (.*):(\\d+).*$"); - Matcher m = stinfo.matcher(ln); - if(!m.matches()) throw new RuntimeException("Failed to parse line from exec: " + ln); - String fwname = m.group(1); - String stname = m.group(2); - int stsize = Integer.parseInt(m.group(3)); - - Framework fw = findFrameworkByName(fws, fwname); - - Struct st = fw.getStructByName(stname); - NStruct nst = wget(arch, st.type.type32, st.type.type64); - nst.sizeof.put(arch, stsize); - -// System.out.println(st.name + " : " + stsize); - - Pattern finfo = Pattern.compile(" (-?\\d+)"); - Matcher fm = finfo.matcher(ln); - int fi = 0; - while(fm.find()){ - NField sf = nst.fields.get(fi++); - sf.offset.put(arch, Integer.parseInt(fm.group(1))); -// System.out.println("\t" + sf.name + " : " + off); - } - - TypeCache.inst().pingType(st.type); - } - - /** - * Generates Objective-C file and returns absolute path name. - */ - private String generateFileForFramework(Framework fw, Width arch) throws Exception{ - File tempfile = File.createTempFile("JObjC-SOR-" + fw.name + "-" + arch + "-", ".mm"); - PrintWriter out = new PrintWriter(new FileWriter(tempfile)); - out.println("#include"); - printHeaderLines(fw, arch, out); - out.println(""); - out.println("int main(int argc, char** argv){"); - printStructInfos(fw, arch, out); - out.println("\treturn 0;"); - out.println("}"); - out.close(); - return tempfile.getAbsolutePath(); - } - - protected void execute(String executable, Fp.Map1 lineProcessor) throws Exception { -// System.out.println(">>>> Executing " + new Date().toString()); - Process p = Runtime.getRuntime().exec(new String[]{executable}); - - if(lineProcessor != null){ - BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream())); - String line; - while ((line = stdout.readLine()) != null) - lineProcessor.apply(line); - stdout.close(); - } - p.waitFor(); - if(p.exitValue() != 0) - throw new RuntimeException(executable + " did not execute successfully: " + p.exitValue()); - } - - private static Map gccFlag = Fp.litMap(Width.W32, "-m32", Width.W64, "-m64"); - - static boolean isDone(Process p){ - try{ - p.exitValue(); - return true; - } - catch(Exception x){ - return false; - } - } - - protected static String compileObjC(String nativeSrc, Width arch) throws Exception { - String execPath = nativeSrc.replace(".mm", ""); - Process p = Runtime.getRuntime().exec(new String[]{ - "llvm-g++", "-Wall", gccFlag.get(arch), "-ObjC++", "-framework", "Foundation", "-o", execPath, nativeSrc - }); - BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream())); - BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream())); - while(!isDone(p)){ - while(stdout.ready()) System.out.println(stdout.readLine()); - while(stderr.ready()) System.out.println(stderr.readLine()); - } - p.waitFor(); - while(stdout.ready() || stderr.ready()){ - if(stdout.ready()) System.out.println(stdout.readLine()); - if(stderr.ready()) System.out.println(stderr.readLine()); - } - if(p.exitValue() != 0) - throw new RuntimeException("gcc did not compile '" + nativeSrc + "' successfully: " + p.exitValue()); - return execPath; - } - - static void printStructInfos(Framework fw, Width arch, PrintWriter out){ - for(Struct st : fw.structs){ - NStruct nst = wget(arch, st.type.type32, st.type.type64); - out.println("std::cout << \"" + fw.name + " " + st.name + "\" << ':' << sizeof("+st.name+")"); - for(NField sf : nst.fields){ - out.print("\t<< ' ' << "); - out.println(sf.type instanceof NType.NBitfield - ? "-1" - : "offsetof("+st.name+","+sf.name+")"); - } - out.println("\t<< std::endl;"); - } - } - - static void printHeaderLines(Framework fw, Width arch, PrintWriter out) throws Exception { - Collection always = alwaysHeaders.get(arch); - Collection banned = bannedHeaders.get(arch); - out.println("#define COREFOUNDATION_CFPLUGINCOM_SEPARATE 0"); - for(String header : always) - out.println("#import " + header); - - out.println("#undef COREFOUNDATION_CFPLUGINCOM_SEPARATE"); - String umbrella = fw.path + "/Headers/" + fw.name; - if(new File(umbrella).exists()) - out.println("#import \"" + umbrella + "\""); - - for(File header : getHeaders(fw)) - if(!banned.contains(header.getName())) - out.println("#import \"" + header.getAbsolutePath() + "\""); - } - - static A wget(Width arch, B x32, B x64){ - switch(arch){ - case W32: return (A) x32; - case W64: return (A) x64; - default: throw new RuntimeException(); - } - } - - /** - * Gets the absolute path to every header in FOO.framework/Headers - */ - static Collection getHeaders(Framework fw) throws Exception { - String hpath = fw.path + "/Headers"; - return Utils.find(new File(hpath), "^.*\\.h$", ""); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/StructOffsetResolverBigBang.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/StructOffsetResolverBigBang.java deleted file mode 100644 index 212df7734b5..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/internal/jobjc/generator/utils/StructOffsetResolverBigBang.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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 - * 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 com.apple.internal.jobjc.generator.utils; - -import java.io.File; -import java.io.FileWriter; -import java.io.PrintWriter; -import java.util.Collection; - -import com.apple.internal.jobjc.generator.model.Framework; -import com.apple.internal.jobjc.generator.utils.Fp.Map1; -import com.apple.jobjc.JObjCRuntime.Width; - -/** - * Takes a framework, compiles a native source file with all its structs, - * and figures out their sizes and field offsets. - * - * BigBang significantly speeds up the process by - * compiling all frameworks as one big Objective-C file. - */ -public class StructOffsetResolverBigBang extends StructOffsetResolver{ - - @Override protected void _resolve(final Collection fws) throws Exception{ - for(final Width arch : Width.values()){ - System.out.println("SORBB -- Getting Struct offsets @" + arch.toString()); - String nativeSrc = generateFileForFrameworks(fws, arch); - String executable = compileObjC(nativeSrc, arch); - execute(executable, new Map1(){ - public Object apply(String ln) { - try { - processLine(ln, fws, arch); - return null; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - }); - } - } - - /** - * Generates Objective-C file and returns absolute path name. - */ - protected String generateFileForFrameworks(final Collection fws, final Width arch) throws Exception{ - File tempfile = File.createTempFile("JObjC-SORBB-" + arch + "-", ".mm"); - PrintWriter out = new PrintWriter(new FileWriter(tempfile)); - - out.println("#include"); - for(Framework fw : fws) printHeaderLines(fw, arch, out); - out.println("int main(int argc, char** argv){"); - for(Framework fw : fws) printStructInfos(fw, arch, out); - out.println("\treturn 0;"); - out.println("}"); - - out.close(); - return tempfile.getAbsolutePath(); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/jobjc/SuperClassExtractor.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/jobjc/SuperClassExtractor.java deleted file mode 100644 index cc0b3f9047c..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/jobjc/SuperClassExtractor.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import java.util.Map; - -import com.apple.internal.jobjc.generator.model.Clazz; - -/* - * Isolating all the reflection trickery to hijack the runtime into giving up its secrets - * without actually having a full working version of JObjC. Below is a bunch of evil reflection, - * but it allows the generated output to have a cleaner design. - */ -public class SuperClassExtractor { - public static Clazz getSuperClassFor(final String className, final MacOSXFramework nativeFramework, final Map allClasses) throws Throwable { - final NSClass nativeClass = new NSClass(className, nativeFramework.getRuntime()); - final NSClass nativeSuperClass = UnsafeRuntimeAccess.getSuperClass(nativeClass); - final String superClassName = UnsafeRuntimeAccess.getClassNameFor(nativeSuperClass); - if ("nil".equals(superClassName)) return null; - - final Clazz superClazz = allClasses.get(superClassName); - if (superClazz != null) return superClazz; - - final Clazz superClazzX = getSuperClassFor(superClassName, nativeFramework, allClasses); - System.out.print("[Warning] class \"" + superClassName + "\" not found in bridge support files, "); - System.out.println("using \"" + superClazzX.name + "\" as superclass for \"" + className + "\""); - return superClazzX; - } -} diff --git a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/jobjc/UnsafeRuntimeAccess.java b/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/jobjc/UnsafeRuntimeAccess.java deleted file mode 100644 index 556ba97021a..00000000000 --- a/jdk/src/macosx/native/jobjc/src/generator/java/com/apple/jobjc/UnsafeRuntimeAccess.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.jobjc.Invoke.FunCall; -import com.apple.jobjc.Invoke.MsgSend; - -public class UnsafeRuntimeAccess { - public static NativeArgumentBuffer getNativeBuffer() { - return NativeArgumentBuffer.getThreadLocalBuffer(JObjCRuntime.getInstance()); - } - - public static String getClassNameFor(final long obj) { - return NSClass.getClassNameOfClass(obj); - } - - public static String getClassNameFor(final NSClass cls) { - return NSClass.getClassNameOfClass(cls.ptr); - } - - public static NSClass getSuperClass(final NSClass clazz) { - return clazz.getSuperClass(); - } - - public static String getDescriptionForPtr(final long objPtr) { - return ID.getNativeDescription(objPtr); - } - - public static MacOSXFramework getFramework(final String[] frameworkLibs) { - return new MacOSXFramework(JObjCRuntime.getInstance(), frameworkLibs); - } - - public static FunCall createFunCall(final MacOSXFramework framework, final String fxnName, final Coder returnCoder, final Coder ... argCoders) { - return new FunCall(framework, fxnName, returnCoder, argCoders); - } - - public static MsgSend createMsgSend(final NSClass clazz, final String selName, final Coder returnCoder, final Coder ... argCoders) { - return new MsgSend(clazz.getRuntime(), selName, returnCoder, argCoders); - } - - public static NSClass getNSClass(final MacOSXFramework framework, final String name) { - return new NSClass(name, framework.getRuntime()); - } - - public static long getObjPtr(final ID obj) { - return obj.ptr; - } -} diff --git a/jdk/src/macosx/native/jobjc/src/runtime-additions/java/com/apple/jobjc/Utils.java b/jdk/src/macosx/native/jobjc/src/runtime-additions/java/com/apple/jobjc/Utils.java deleted file mode 100644 index a22851de4cb..00000000000 --- a/jdk/src/macosx/native/jobjc/src/runtime-additions/java/com/apple/jobjc/Utils.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import java.util.concurrent.Callable; - -import com.apple.jobjc.foundation.NSNumber; -import com.apple.jobjc.foundation.NSString; - -public class Utils { - JObjCRuntime runtime; - Utils(JObjCRuntime runtime){ this.runtime = runtime; } - - private static Utils utils; - public static Utils get() { - JObjCRuntime runtime = JObjCRuntime.getInstance(); // enforce security check - return utils != null ? utils : (utils = new Utils(runtime)); - } - - private Strings strings_; - public Strings strings() { - return strings_ != null ? strings_ : (strings_ = new Strings(runtime)); - } - - private Numbers numbers_; - public Numbers numbers() { - return numbers_ != null ? numbers_ : (numbers_ = new Numbers(runtime)); - } - - private Threads threads_; - public Threads threads() { - return threads_ != null ? threads_ : (threads_ = new Threads(runtime)); - } - - public static class Strings { - private static native long getNativeNSStringForJavaString(final String javaString); - private static native String getNativeJavaStringForNSString(final long nsString); - - JObjCRuntime runtime; - Strings(JObjCRuntime runtime) { this.runtime = runtime; } - - public NSString nsString(final String str) { - if (str == null) return null; - final long nsString = getNativeNSStringForJavaString(str); - return ID.createNewObjCObjectForClass(NSString.class, nsString, runtime); - } - - public String javaString(final NSString str) { - if (str == null) return null; - return getNativeJavaStringForNSString(((ID)str).ptr); - } - -// static public CString cStringForJavaString(final String str) { -// return null; -// } - } - - public static class Numbers { - private static native long getNativeNSNumberForJavaNumber(final Number num); - private static native Number getNativeJavaNumberForNSNumber(final long num); - - JObjCRuntime runtime; - Numbers(JObjCRuntime runtime) { this.runtime = runtime; } - - public NSNumber nsNumber(final Number num) { - if (num == null) return null; - final long nsNumber = getNativeNSNumberForJavaNumber(num); - return ID.createNewObjCObjectForClass(NSNumber.class, nsNumber, runtime); - } - - public Number javaNumber(final NSNumber num) { - if (num == null) return null; - return getNativeJavaNumberForNSNumber(((ID)num).ptr); - } - } - - public static class Threads { - private static native void performRunnableOnMainThread(final Runnable runnable, final boolean wait); - private static native V performCallableOnMainThread(final Callable callable) throws Exception; - - JObjCRuntime runtime; - Threads(JObjCRuntime runtime) { this.runtime = runtime; } - - /** - * Perform callable on main thread. Exceptions that are thrown on the main thread are ignored. - */ - public void performOnMainThread(final Runnable runnable, final boolean wait) { - performRunnableOnMainThread(runnable, wait); - } - - /** - * Perform callable on main thread, block until done, and return the result. - * This also catches any exceptions on the main thread, brings them back and throws them to the caller. - */ - public V performOnMainThread(final Callable callable) throws Exception{ - return performCallableOnMainThread(callable); - } - } -} diff --git a/jdk/src/macosx/native/jobjc/src/runtime-additions/native/NativeNumber.m b/jdk/src/macosx/native/jobjc/src/runtime-additions/native/NativeNumber.m deleted file mode 100644 index 395f46fb211..00000000000 --- a/jdk/src/macosx/native/jobjc/src/runtime-additions/native/NativeNumber.m +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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 - * 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. - */ - -#include "com_apple_jobjc_Utils_Numbers.h" - -#include - -/* - * Class: com_apple_jobjc_Utils_Numbers - * Method: getNativeNSNumberForJavaNumber - * Signature: (Ljava/lang/Number;)J - */ -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_Utils_00024Numbers_getNativeNSNumberForJavaNumber -(JNIEnv *env, jclass clazz, jobject javaNumber) -{ - return ptr_to_jlong(JNFJavaToNSNumber(env, javaNumber)); -} - -/* - * Class: com_apple_jobjc_Utils_Numbers - * Method: getNativeJavaNumberForNSNumber - * Signature: (J)Ljava/lang/Number; - */ -JNIEXPORT jobject JNICALL Java_com_apple_jobjc_Utils_00024Numbers_getNativeJavaNumberForNSNumber -(JNIEnv *env, jclass clazz, jlong nativeNumber) -{ - return JNFNSToJavaNumber(env, (NSNumber *)jlong_to_ptr(nativeNumber)); -} diff --git a/jdk/src/macosx/native/jobjc/src/runtime-additions/native/NativeString.m b/jdk/src/macosx/native/jobjc/src/runtime-additions/native/NativeString.m deleted file mode 100644 index 1e01545555d..00000000000 --- a/jdk/src/macosx/native/jobjc/src/runtime-additions/native/NativeString.m +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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 - * 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. - */ - -#include "com_apple_jobjc_Utils_Strings.h" - -#include - -/* - * Class: com_apple_jobjc_Utils_Strings - * Method: getNativeNSStringForJavaString - * Signature: (Ljava/lang/String;)J - */ -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_Utils_00024Strings_getNativeNSStringForJavaString -(JNIEnv *env, jclass clazz, jstring javaString) -{ - return ptr_to_jlong(JNFJavaToNSString(env, javaString)); -} - -/* - * Class: com_apple_jobjc_Utils_Strings - * Method: getNativeJavaStringForNSString - * Signature: (J)Ljava/lang/String; - */ -JNIEXPORT jstring JNICALL Java_com_apple_jobjc_Utils_00024Strings_getNativeJavaStringForNSString -(JNIEnv *env, jclass clazz, jlong nativeString) -{ - return JNFNSToJavaString(env, (NSString *)jlong_to_ptr(nativeString)); -} diff --git a/jdk/src/macosx/native/jobjc/src/runtime-additions/native/NativeThread.m b/jdk/src/macosx/native/jobjc/src/runtime-additions/native/NativeThread.m deleted file mode 100644 index 75062e44e0c..00000000000 --- a/jdk/src/macosx/native/jobjc/src/runtime-additions/native/NativeThread.m +++ /dev/null @@ -1,111 +0,0 @@ -/* - * 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 - * 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. - */ - -#include "com_apple_jobjc_Utils_Threads.h" - -#import -#import - - -@interface JObjCCallable : NSObject { - @public jobject returnValue; - @public jthrowable exception; -} -@property jobject returnValue; -@property jthrowable exception; -- (void) performCallable:(JNFJObjectWrapper *)callableWrapper; -@end - -/* - * Class: com_apple_jobjc_Utils_Threads - * Method: performRunnableOnMainThreadNative - * Signature: (Ljava/lang/Runnable;Z)V - */ -JNIEXPORT void JNICALL Java_com_apple_jobjc_Utils_00024Threads_performRunnableOnMainThread -(JNIEnv *env, jclass clazz, jobject runnable, jboolean jWaitUntilDone) -{ -JNF_COCOA_ENTER(env); - [JNFRunLoop performOnMainThreadWaiting:jWaitUntilDone - withBlock:[JNFRunnable blockWithRunnable:runnable - withEnv:env]]; -JNF_COCOA_EXIT(env); -} - -/* - * Class: com_apple_jobjc_Utils_Threads - * Method: performCallableOnMainThreadNative - * Signature: (Ljava/util/concurrent/Callable;)Ljava/lang/Object; - */ -JNIEXPORT jobject JNICALL Java_com_apple_jobjc_Utils_00024Threads_performCallableOnMainThread -(JNIEnv *env, jclass clazz, jobject callable) -{ - jobject returnValue = NULL; - -JNF_COCOA_ENTER(env); - JNFJObjectWrapper *callableWrapper = [[JNFJObjectWrapper alloc] initWithJObject:callable withEnv:env]; - JObjCCallable *ncallable = [JObjCCallable alloc]; - - [ncallable performSelectorOnMainThread:@selector(performCallable:) - withObject:callableWrapper - waitUntilDone:true]; - - returnValue = ncallable.returnValue; - jthrowable exception = ncallable.exception; - - [ncallable release]; - if(exception) (*env)->Throw(env, exception); - -JNF_COCOA_EXIT(env); - - return returnValue; -} - - -@implementation JObjCCallable -@synthesize returnValue; -@synthesize exception; - -- (void) performCallable:(JNFJObjectWrapper *)callableWrapper { - static JNF_CLASS_CACHE(jc_Callable, "java/util/concurrent/Callable"); - static JNF_MEMBER_CACHE(jm_Callable_call, jc_Callable, "call", "()Ljava/lang/Object;"); - - JNFThreadContext threadWasAttached = JNFThreadDetachOnThreadDeath; - JNIEnv *env = JNFObtainEnv(&threadWasAttached); - jobject callable = [callableWrapper jObject]; - - @try{ - self.returnValue = JNFCallObjectMethod(env, callable, jm_Callable_call); - } @catch (JNFException *x) { - [x raiseToJava:env]; - } - - self.exception = (*env)->ExceptionOccurred(env); - (*env)->ExceptionClear(env); - - [callableWrapper release]; - JNFReleaseEnv(env, &threadWasAttached); -} - -@end diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BaseBench.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BaseBench.java deleted file mode 100644 index dbbb80cd31f..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BaseBench.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import sun.misc.Unsafe; - -public class BaseBench extends PooledTestCase { - protected final static JObjCRuntime RUNTIME = JObjCRuntime.getInstance(); - protected final static JObjC JOBJC = JObjC.getInstance(); - protected final static Unsafe UNSAFE = JObjCRuntime.getInstance().unsafe; - protected final static NativeArgumentBuffer ARGS = JObjCRuntime.getInstance().getThreadLocalState(); - - public abstract static class Task{ - final String name; - public Task(String name){ this.name = name; } - public abstract void run(); - } - - public void bench(final String title, final long warmup, final long runs, final long iterations, final Task... tasks){ - final long[] runtimes = new long[tasks.length]; - - for(int t = 0; t < tasks.length; ++t){ - long runtime = 0; - for(int i = 0; i < warmup; ++i) - singleBench(iterations, tasks[t]); - for(int i = 0; i < runs; ++i) - runtime = runtime + singleBench(iterations, tasks[t]); - runtimes[t] = runtime; - } - - final float[] relatives = new float[tasks.length]; - - for(int t = 0; t < tasks.length; ++t) - relatives[t] = ((float) runtimes[t] / (float) runs); - - float min = relatives[0]; - for(float t : relatives) - if(t < min) - min = t; - - for(int t = 0; t < tasks.length; ++t) - relatives[t] = relatives[t] / min; - - System.out.format("\n* %1$s\n", title); - for(int t = 0; t < tasks.length; ++t) - System.out.format("%1$60s : %2$.1f\n", tasks[t].name, relatives[t]); - } - - public long singleBench(final long iterations, final Task task){ - long start = System.currentTimeMillis(); - for(long i = 0; i < iterations; ++i) - task.run(); - long end = System.currentTimeMillis(); - return end - start; - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BenchFunCall.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BenchFunCall.java deleted file mode 100644 index 417ad6d1187..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BenchFunCall.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.jobjc.Invoke.FunCall; -import com.apple.jobjc.PrimitiveCoder.DoubleCoder; - -public final class BenchFunCall extends BaseBench{ - final static int ITERS = 1000; - final static FunCall fc = new FunCall(JObjCRuntime.getInstance(), "sin", DoubleCoder.INST, DoubleCoder.INST); - final static double ARG = 3.14159265 / 2.0; - final static double RET = 1.0; - - private static native double jniSin(double arg); - - public void testBench(){ - this.bench("Calling functions", 5, 3, 10000L, - - new Task("JNI Invoke"){ - @Override public void run() { - for(int i = 0; i < ITERS; ++i) - jniSin(ARG); - }}, - - new Task("JObjC FunCall"){ - @Override public void run() { - for(int i = 0; i < ITERS; ++i){ - fc.init(ARGS); - DoubleCoder.INST.push(ARGS, ARG); - fc.invoke(ARGS); - DoubleCoder.INST.pop(ARGS); - } - }}, - - new Task("JObjC FunCall (inlined)"){ - @Override public void run() { - for(int i = 0; i < ITERS; ++i){ - // init - ARGS.argPtrsPtr = ARGS.buffer.bufferPtr; - ARGS.argValuesPtr = ARGS.buffer.bufferPtr + 256; - // push double - //// push arg ptr - if(JObjCRuntime.IS64) - UNSAFE.putLong(ARGS.argPtrsPtr, ARGS.argValuesPtr); - else - UNSAFE.putInt(ARGS.argPtrsPtr, (int) ARGS.argValuesPtr); - ARGS.argPtrsPtr += JObjCRuntime.PTR_LEN; - //// push arg value - UNSAFE.putDouble(ARGS.argValuesPtr, ARG); - ARGS.argValuesPtr += 8; - // invoke - FunCall.invoke(fc.cif.cif.bufferPtr, fc.fxnPtr, ARGS.retValPtr, ARGS.buffer.bufferPtr); - // pop - UNSAFE.getDouble(ARGS.retValPtr); - } - }} - ); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BenchIDPop.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BenchIDPop.java deleted file mode 100644 index b24059b3644..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BenchIDPop.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.jobjc.foundation.FoundationFramework; -import com.apple.jobjc.foundation.NSString; - -public class BenchIDPop extends BaseBench{ - static native long jniNSStringAlloc(); - static native long jniNSStringAllocAndRetain(); - static native long jniNSStringCached(); - static native void jniCFRetain(long x); - static native void jniCFRelease(long x); - - final static int ITERS = 1000; - final static FoundationFramework FND = JOBJC.Foundation(); - - private static class LongWrap{ - long l; - public LongWrap(long l){ this.l = l; } - } - - public void testIt(){ - bench("Alloc, retain, pop a new NSString", 2, 3, 2000, - new Task("jniNSStringAllocAndRetain()"){ - @Override public void run() { - for(int i = 0; i < ITERS; i++) - jniNSStringAllocAndRetain(); - }}, - - new Task("new LongWrap(jniNSStringAllocAndRetain())"){ - @Override public void run() { - for(int i = 0; i < ITERS; i++) - new LongWrap(jniNSStringAllocAndRetain()); - }}, - - new Task("FND.NSString().alloc()"){ - @Override public void run() { - for(int i = 0; i < ITERS; i++) - FND.NSString().alloc(); - }}, - - new Task("new NSString(jniNSStringAlloc(), RUNTIME)"){ - @Override public void run() { - for(int i = 0; i < ITERS; i++) - new NSString(jniNSStringAlloc(), RUNTIME); - }} - ); - - final long nsstringPtr = jniNSStringAlloc(); - - bench("Get and hold an existing object", 2, 3, 2000, - new Task("jniCFRetain(nsstringPtr)"){ - @Override public void run() { - for(int i = 0; i < ITERS; i++) - jniCFRetain(nsstringPtr); - }}, - - new Task("jniCFRetain(new LongWrap(nsstringPtr).l"){ - @Override public void run() { - for(int i = 0; i < ITERS; i++) - jniCFRetain(new LongWrap(nsstringPtr).l); - }}, - - new Task("ID.getInstance(nsstringPtr, RUNTIME)"){ - @Override public void run() { - for(int i = 0; i < ITERS; i++) - ID.getInstance(nsstringPtr, RUNTIME); - }} - ); - } - -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BenchStructCoding.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BenchStructCoding.java deleted file mode 100644 index 9d0a769805a..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BenchStructCoding.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.jobjc.Coder.StructCoder; -import com.apple.jobjc.Invoke.FunCall; -import com.apple.jobjc.foundation.FoundationFramework; -import com.apple.jobjc.foundation.NSRect; - -public class BenchStructCoding extends BaseBench { - final static FoundationFramework FND = JOBJC.Foundation(); - final static int ITERS = 1000; - final static PrimitiveCoder CODER = com.apple.jobjc.MixedPrimitiveCoder.FloatDoubleCoder; - final static StructCoder RCODER = NSRect.getStructCoder(); - final static FunCall nsMakePoint = - new com.apple.jobjc.Invoke.FunCall(FND, "NSMakeRect", com.apple.jobjc.foundation.NSRect.getStructCoder(), - com.apple.jobjc.MixedPrimitiveCoder.FloatDoubleCoder, - com.apple.jobjc.MixedPrimitiveCoder.FloatDoubleCoder, - com.apple.jobjc.MixedPrimitiveCoder.FloatDoubleCoder, - com.apple.jobjc.MixedPrimitiveCoder.FloatDoubleCoder); - - public void testFoo(){ - bench("NSMakeRect", 3, 3, 10, - new Task("FND.NSMakeRect"){ - @Override public void run() { - for(int i = 0; i < ITERS; ++i){ - NSRect s = FND.NSMakeRect(0, 1, 2, 3); -// assertEquals(1.0D, s.origin().y()); - } - }}, - - new Task("nsMakeRect.invoke(..., s)"){ - @Override public void run() { - for(int i = 0; i < ITERS; ++i){ - nsMakePoint.init(ARGS); - CODER.push(ARGS, 0.0D); - CODER.push(ARGS, 1.0D); - CODER.push(ARGS, 2.0D); - CODER.push(ARGS, 3.0D); - NSRect s = FND.makeNSRect(); - nsMakePoint.invoke(ARGS, s); -// assertEquals(1.0D, s.origin().y()); - } - }}, - - new Task("nsMakeRect.invoke(..); NSRect r = pop(..);"){ - @Override public void run() { - for(int i = 0; i < ITERS; ++i){ - nsMakePoint.init(ARGS); - CODER.push(ARGS, 0.0D); - CODER.push(ARGS, 1.0D); - CODER.push(ARGS, 2.0D); - CODER.push(ARGS, 3.0D); - nsMakePoint.invoke(ARGS); - NSRect s = (NSRect) RCODER.pop(ARGS); -// assertEquals(1.0D, s.origin().y()); - } - }} - ); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BenchUnsafe.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BenchUnsafe.java deleted file mode 100644 index f04c99d3dc8..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/BenchUnsafe.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import java.nio.ByteBuffer; - -public class BenchUnsafe extends BaseBench{ - final static int ITERS = 1000000; - - final static NativeBuffer NBUF = new NativeBuffer(2 * ITERS); - final static ByteBuffer BBUF = NBUF.buffer; - final static long ADDR = NBUF.bufferPtr; - final static long ADDR_MAX = NBUF.bufferPtr + ITERS; - - final static NativeBuffer NBUF2 = new NativeBuffer(2 * ITERS); - final static ByteBuffer BBUF2 = NBUF2.buffer; - final static long ADDR2 = NBUF2.bufferPtr; - final static long ADDR2_MAX = NBUF2.bufferPtr + ITERS; - - final static long ARG = 345; - - final static long BUFSIZE = BBUF.limit(); - - public void testIt(){ - this.bench("Memory writes", 5, 3, 100L, - - new Task("buffer.putLong"){ - @Override public void run() { - for(long i = 0; i < ITERS; i++) - BBUF.putLong((int) i, ARG); - }}, - - new Task("unsafe.putLong"){ - @Override public void run() { - for(long i = ADDR; i < ADDR_MAX; i++) - UNSAFE.putLong(i, ARG); - }}); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/CategoryTest.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/CategoryTest.java deleted file mode 100644 index b762d7e9bb2..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/CategoryTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.jobjc.appkit.AppKitFramework; -import com.apple.jobjc.appkit.NSStringCategory; -import com.apple.jobjc.foundation.NSSize; -import com.apple.jobjc.foundation.NSString; - -public class CategoryTest extends PooledTestCase { - public void testAppKit_NSString(){ - AppKitFramework APPKIT = JObjC.getInstance().AppKit(); - - NSString nstr = Utils.get().strings().nsString("mirzapirza"); - NSStringCategory nstrx = APPKIT.NSStringCategory(nstr); - NSSize sz = nstrx.sizeWithAttributes(null); - - assertEquals(57.0, sz.width()); - assertEquals(15.0, sz.height()); - } - - public static void main(String[] args){ - junit.textui.TestRunner.run(CategoryTest.class); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/FunctionTest.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/FunctionTest.java deleted file mode 100644 index 00e3c4deac1..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/FunctionTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.jobjc.Coder.PointerCoder; -import com.apple.jobjc.Coder.PrimitivePointerCoder; -import com.apple.jobjc.Coder.VoidCoder; -import com.apple.jobjc.Invoke.FunCall; - -public class FunctionTest extends PooledTestCase { - NativeArgumentBuffer nativeBuffer; - JObjCRuntime runtime; - - @Override - public void setUp() throws Exception { - super.setUp(); - nativeBuffer = UnsafeRuntimeAccess.getNativeBuffer(); - runtime = nativeBuffer.runtime; - } - - public void testInvokeNoParamNoReturn() throws Throwable { - final FunCall fxn = UnsafeRuntimeAccess.createFunCall(TestUtils.getAppKit(), "NSBeep", VoidCoder.INST); - - fxn.init(nativeBuffer); - fxn.invoke(nativeBuffer); - } - - public void testInvokeNoParams() throws Throwable { - final FunCall fxn = UnsafeRuntimeAccess.createFunCall(TestUtils.getFoundation(), "NSFullUserName", PointerCoder.INST); - - fxn.init(nativeBuffer); - fxn.invoke(nativeBuffer); - - final long ptr = PrimitivePointerCoder.INST.pop(nativeBuffer); - System.out.println("0x" + Long.toHexString(ptr) + ": " + UnsafeRuntimeAccess.getDescriptionForPtr(ptr)); - } - - public void testInvokeOneParam() throws Throwable { - final FunCall getHomeDirFxn = UnsafeRuntimeAccess.createFunCall(TestUtils.getAppKit(), "NSHomeDirectory", PointerCoder.INST); - - getHomeDirFxn.init(nativeBuffer); - getHomeDirFxn.invoke(nativeBuffer); - - final long homeDirPtr = PrimitivePointerCoder.INST.pop(nativeBuffer); - System.out.println("0x" + Long.toHexString(homeDirPtr) + ": " + UnsafeRuntimeAccess.getDescriptionForPtr(homeDirPtr)); - - final FunCall getTypeOfFxn = UnsafeRuntimeAccess.createFunCall(TestUtils.getFoundation(), "NSLog", PointerCoder.INST, PointerCoder.INST); - getTypeOfFxn.init(nativeBuffer); - PrimitivePointerCoder.INST.push(runtime, nativeBuffer, homeDirPtr); - getTypeOfFxn.invoke(nativeBuffer); - - // long typePtr = PointerCoder.pointer_coder.popPtr(nativeBuffer); - // System.out.println("0x" + Long.toHexString(typePtr) + ": " + TestUtils.getDescriptionForPtr(typePtr)); - } - - public static void main(final String[] args) { - junit.textui.TestRunner.run(FunctionTest.class); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/GUIDemo.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/GUIDemo.java deleted file mode 100644 index c9a3f46b05e..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/GUIDemo.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.jobjc.Utils.Strings; -import com.apple.jobjc.appkit.NSApplication; -import com.apple.jobjc.appkit.NSButton; -import com.apple.jobjc.appkit.NSDrawer; -import com.apple.jobjc.appkit.NSMenu; -import com.apple.jobjc.appkit.NSWindow; -import com.apple.jobjc.foundation.NSAutoreleasePool; -import com.apple.jobjc.foundation.NSObject; -import com.apple.jobjc.foundation.NSObjectClass; -import com.apple.jobjc.foundation.NSRect; -import com.apple.jobjc.foundation.NSSize; - -class MyDelegate extends NSObject{ - static final JObjC objc = JObjC.getInstance(); - static final Strings str = Utils.get().strings(); - - public MyDelegate(long ptr, JObjCRuntime r) { super(ptr, r); } - - private NSWindow myWindow; - private NSDrawer myDrawer; - - public void printHello(ID sender){ - System.out.println("Hello!"); - myDrawer.toggle(this); - } - - public void createMenu(){ - NSMenu menu = objc.AppKit().NSMenu().newID(); - menu.addItemWithTitle_action_keyEquivalent( - str.nsString("Quit"), - new SEL("terminate:"), - str.nsString("q")); - NSApplication app = objc.AppKit().NSApp(); - app.setMainMenu(menu); - } - - public void createWindow(){ - NSRect rect; - int styleMask = objc.AppKit().NSTitledWindowMask() | objc.AppKit().NSMiniaturizableWindowMask(); - NSButton myButton; - NSSize buttonSize; - myButton = objc.AppKit().NSButton().newID(); - myButton.setTitle(str.nsString("Print Hello!")); - myButton.sizeToFit(); - myButton.setTarget(this); - myButton.setAction(new SEL("printHello:")); - buttonSize = myButton.frame().size(); - rect = objc.Foundation().NSMakeRect(100, 100, 2*buttonSize.width(), 2*buttonSize.height()); - myWindow = objc.AppKit().NSWindow().alloc(); - myWindow = myWindow.initWithContentRect_styleMask_backing_defer( - rect, styleMask, objc.AppKit().NSBackingStoreBuffered(), false); - myWindow.setTitle(str.nsString("This is a test window.")); - myWindow.setContentView(myButton); - - myDrawer = objc.AppKit().NSDrawer().alloc(); - myDrawer = myDrawer.initWithContentSize_preferredEdge( - objc.Foundation().NSMakeSize(100, 40), objc.Foundation().NSMinYEdge()); - myDrawer.setParentWindow(myWindow); - } - - public void applicationWillFinishLaunching(ID not){ - createMenu(); - createWindow(); - } - - public void applicationDidFinishLaunching(ID not){ - myWindow.makeKeyAndOrderFront(null); - } -} - -class MyDelegateClass extends NSObjectClass{ - public MyDelegateClass(JObjCRuntime r){ super(r); } -} - -public class GUIDemo{ - static final JObjC objc = JObjC.getInstance(); - - public static void main(String[] args){ - JObjCRuntime.getInstance().registerUserClass(MyDelegate.class, MyDelegateClass.class); - - objc.AppKit().NSApplication().sharedApplication(); - NSApplication app = objc.AppKit().NSApp(); - - NSAutoreleasePool pool = objc.Foundation().NSAutoreleasePool().alloc(); - pool = pool.init(); - app.setDelegate(new MyDelegateClass(JObjCRuntime.getInstance()).newID()); - app.run(); - pool.drain(); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/IBDemo.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/IBDemo.java deleted file mode 100644 index dbfc1eff4a3..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/IBDemo.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * 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 - * 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. - */ -/** - * To locate the nib correctly, this demo must run from - * a .app (created with Jar Bundler...). - * - * TODO Add .app/Jar Bundler as ant task - */ - -package com.apple.jobjc; - -import java.awt.Toolkit; - -import com.apple.jobjc.appkit.AppKitFramework; -import com.apple.jobjc.appkit.NSApplication; -import com.apple.jobjc.appkit.NSView; -import com.apple.jobjc.appkit.NSViewClass; -import com.apple.jobjc.foundation.FoundationFramework; -import com.apple.jobjc.foundation.NSRect; -import com.apple.jobjc.foundation.NSString; - -class MyView extends NSView{ - static final AppKitFramework APPKIT = JObjC.getInstance().AppKit(); - - public MyView(long objPtr, JObjCRuntime runtime) { super(objPtr, runtime); } - - @Override public void drawRect(NSRect r){ - APPKIT.NSColor().redColor().set(); - APPKIT.NSBezierPath().fillRect(r); - } -} - -class MyViewClass extends NSViewClass{ - protected MyViewClass(String name, JObjCRuntime runtime) { super(name, runtime); } - public MyViewClass(JObjCRuntime runtime){ this(MyView.class.getSimpleName(), runtime); } -} - -public class IBDemo{ - final static FoundationFramework FOUNDATION = JObjC.getInstance().Foundation(); - final static AppKitFramework APPKIT = JObjC.getInstance().AppKit(); - - // Works if the JVM is launched on the main thread, - // but JavaApplicationStub does not understand -XstartOnFirstThread - public static void mainWithAppMain(String[] args){ - APPKIT.NSApplicationMain(0, null); - } - - // Work around: let someone else init, and then - // get on the main thread to load the nib. - public static void mainWithoutAppMain(String[] args){ - Toolkit.getDefaultToolkit(); - - Utils.get().threads().performOnMainThread(new Runnable(){ - public void run() { - APPKIT.NSApplication().sharedApplication(); - NSApplication APP = APPKIT.NSApp(); - - NSString nibName = Utils.get().strings().nsString("MainMenu"); - boolean loadedNib = APPKIT.NSBundleCategory().loadNibNamed_owner(nibName, APP); - if(!loadedNib) throw new RuntimeException("Failed to load nib."); - }}, false); - } - - public static void main(String[] args){ - JObjCRuntime.getInstance().registerUserClass(MyView.class, MyViewClass.class); - mainWithoutAppMain(args); - //mainWithAppMain(args); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/IntroTest.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/IntroTest.java deleted file mode 100644 index edd5f072575..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/IntroTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import junit.framework.TestCase; - -import com.apple.jobjc.Invoke.FunCall; -import com.apple.jobjc.PrimitiveCoder.DoubleCoder; -import com.apple.jobjc.appkit.AppKitFramework; -import com.apple.jobjc.appkit.NSApplication; -import com.apple.jobjc.appkit.NSApplicationClass; -import com.apple.jobjc.appkit.NSColorPanel; -import com.apple.jobjc.appkit.NSWorkspace; -import com.apple.jobjc.foundation.FoundationFramework; -import com.apple.jobjc.foundation.NSAutoreleasePool; -import com.apple.jobjc.foundation.NSPoint; -import com.apple.jobjc.foundation.NSString; -import com.apple.jobjc.foundation.NSStringClass; - -public class IntroTest extends TestCase{ - // The low-level core makes function calls, sends messages, marshals data, etc. - public void testCore(){ - // pass security check and get ahold of a runtime (should cache this) - final JObjCRuntime RUNTIME = JObjCRuntime.getInstance(); - final NativeArgumentBuffer ARGS = JObjCRuntime.getInstance().getThreadLocalState(); - - // create a funcall (should cache this) - final FunCall fc = new FunCall(RUNTIME, "sin", DoubleCoder.INST, DoubleCoder.INST); - - // start function call - fc.init(ARGS); - // push an arg - DoubleCoder.INST.push(ARGS, 3.14159265 / 2.0); - // make the call - fc.invoke(ARGS); - // read the return value - double ret = DoubleCoder.INST.pop(ARGS); - - assertEquals(1.0, ret); - } - - // Frameworks bridge the Mac OS X frameworks - public void testFrameworks(){ - // First, get an instance of JObjC: - final JObjC JOBJC = com.apple.jobjc.JObjC.getInstance(); - - // It's your gateway to the frameworks. - final FoundationFramework FND = JOBJC.Foundation(); - final AppKitFramework APP = JOBJC.AppKit(); - - // From which you can then access... - - // enums, defines, constants - int nsmye = FND.NSMaxYEdge(); - boolean debug = FND.NSDebugEnabled(); - - // structs - NSPoint p = FND.makeNSPoint(); - p.setX(3); - assertEquals(3.0, p.x()); - - // C functions - NSPoint p2 = FND.NSMakePoint(12, 34); - assertEquals(12.0, p2.x()); - - // ... Let's create an AutoreleasePool before we go on - NSAutoreleasePool pool = ((NSAutoreleasePool) FND.NSAutoreleasePool().alloc()).init(); - - // Objective-C classes - NSStringClass nsc = FND.NSString(); - - // class-methods - NSString nsStringClassDescr = nsc.description(); - - // instances - NSString nsi = ((NSString) FND.NSString().alloc()).init(); - - // instance methods - NSString d = nsi.description(); - - // The bridge marshals some types for you, but it doesn't - // convert between NSString and Java String automatically. - // For that we use Utils.get().strings().nsString(String) - // and Utils.get().strings().javaString(NSString); - - assertEquals("NSString", Utils.get().strings().javaString(nsStringClassDescr)); - - NSString format = Utils.get().strings().nsString("Foo bar %d baz"); - - NSString formatted = ((NSString) FND.NSString().alloc()).initWithFormat(format, 34); - String jformatted = Utils.get().strings().javaString(formatted); - - assertEquals("Foo bar 34 baz", jformatted); - - // Reveal in Finder -// NSString file = Utils.get().strings().nsString( -// "/Applications/Calculator.app/Contents/Resources/Calculator.icns"); -// APP.NSWorkspace().sharedWorkspace() -// .selectFile_inFileViewerRootedAtPath(file, null); - - pool.drain(); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/NSClassTest.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/NSClassTest.java deleted file mode 100644 index cbd5105737f..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/NSClassTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.jobjc.foundation.FoundationFramework; -import com.apple.jobjc.foundation.NSString; -import com.apple.jobjc.foundation.NSStringClass; - -public class NSClassTest extends PooledTestCase{ - JObjC JOBJC = JObjC.getInstance(); - FoundationFramework FND = JOBJC.Foundation(); - - public void testNSClassName(){ - NSString s = ((NSString) FND.NSString().alloc()).init(); - - NSString cname = s.className(); - String jcname = Utils.get().strings().javaString(cname); - assertEquals("NSCFString", jcname); - } - - public void testNSClassPop(){ - NSString s = ((NSString) FND.NSString().alloc()).init(); - - NSStringClass c = s.classNSClass(); - String jdescr = Utils.get().strings().javaString(c.description()); - assertEquals("NSCFString", jdescr); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/NativeBufferTest.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/NativeBufferTest.java deleted file mode 100644 index a6c93ab382e..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/NativeBufferTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import junit.framework.TestCase; - -public class NativeBufferTest extends TestCase{ - public void testSlicePtrs(){ - JObjC.getInstance(); - - NativeBuffer b = new NativeBuffer(123); - b.position(1); - NativeBuffer c = b.slice(); - assertEquals(b.bufferPtr + 1, c.bufferPtr); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/NativeTypeTest.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/NativeTypeTest.java deleted file mode 100644 index fb352f78046..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/NativeTypeTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.internal.jobjc.generator.model.types.NType; -import com.apple.internal.jobjc.generator.utils.NTypeMerger; -import com.apple.internal.jobjc.generator.utils.NTypeParser; - -public class NativeTypeTest extends PooledTestCase{ - - private NType doParse(String type){ - NType nt = NTypeParser.parseFrom(type); - String printed = nt.toString(); - System.out.println("Original: " + type); - System.out.println("Printed.: " + printed); - assertEquals(type, printed); - return nt; - } - - // {_NSRect= - // "origin"{_NSPoint="x"f"y"f} - // "size"{_NSSize="width"f"height"f}} - public void testStruct(){ - doParse("{_NSRect=\"origin\"{_NSPoint=\"x\"f\"y\"f}\"size\"{_NSSize=\"width\"f\"height\"f}}"); - } - - // {IOBluetoothL2CAPChannelEvent= - // "eventType"i - // "u"(?= - // "data"{IOBluetoothL2CAPChannelDataBlock= - // "dataPtr"^v - // "dataSize"I} - // "writeRefCon"^v - // "padding"[32C]) - // "status"i} - public void testUnion(){ - doParse("{IOBluetoothL2CAPChannelEvent=\"eventType\"i\"u\"(?=\"data\"{IOBluetoothL2CAPChannelDataBlock=\"dataPtr\"^v\"dataSize\"I}\"writeRefCon\"^v\"padding\"[32C])\"status\"i}"); - } - - public void testUnknown(){ - doParse("{_CFSocketContext=\"version\"i\"info\"^v\"retain\"^?\"release\"^?\"copyDescription\"^?}"); - } - - public void testEmptyStruct(){ - doParse("{_CFSocketSignature=\"protocolFamily\"i\"socketType\"i\"protocol\"i\"address\"^{__CFData}}"); - } - - public void testCharPtr(){ - doParse("^*"); - } - - public void doEquals(final String s){ - assertEquals(doParse(s), doParse(s)); - } - - public void testEquals(){ - doEquals("{_NSRect=\"origin\"{_NSPoint=\"x\"f\"y\"f}\"size\"{_NSSize=\"width\"f\"height\"f}}"); - doEquals("{IOBluetoothL2CAPChannelEvent=\"eventType\"i\"u\"(?=\"data\"{IOBluetoothL2CAPChannelDataBlock=\"dataPtr\"^v\"dataSize\"I}\"writeRefCon\"^v\"padding\"[32C])\"status\"i}"); - doEquals("{_CFSocketContext=\"version\"i\"info\"^v\"retain\"^?\"release\"^?\"copyDescription\"^?}"); - doEquals("{_CFSocketSignature=\"protocolFamily\"i\"socketType\"i\"protocol\"i\"address\"^{__CFData}}"); - } - - public void testMerge(){ - NType a = doParse("{_NSRect={_NSPoint=\"x\"f\"y\"f}\"size\"{_NSSize=ff}}"); - NType b = doParse("{_NSRect=\"origin\"{_NSPoint=ff}{_NSSize=\"width\"f\"height\"f}}"); - NType c = NTypeMerger.inst().merge(a, b); - NType expected = doParse("{_NSRect=\"origin\"{_NSPoint=\"x\"f\"y\"f}\"size\"{_NSSize=\"width\"f\"height\"f}}"); - System.out.println("Merge results:"); - System.out.println("\ta: " + a.toString()); - System.out.println("\tb: " + b.toString()); - System.out.println("\tc: " + c.toString()); - System.out.println("\tx: " + expected.toString()); - assertEquals(expected, c); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/PooledTestCase.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/PooledTestCase.java deleted file mode 100644 index f52c3860f47..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/PooledTestCase.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import junit.framework.TestCase; - -import com.apple.jobjc.foundation.FoundationFramework; -import com.apple.jobjc.foundation.NSAutoreleasePool; - -public class PooledTestCase extends TestCase { - static{ - System.loadLibrary("JObjC-tests"); - } - NSAutoreleasePool pool; - - @Override public void setUp() throws Exception { - FoundationFramework foundation = JObjC.getInstance().Foundation(); - pool = foundation.NSAutoreleasePool().alloc(); - pool.init(); - } - - @Override public void tearDown() throws Exception { - pool.drain(); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/SELTest.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/SELTest.java deleted file mode 100644 index 1fd94e12ec1..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/SELTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.jobjc.Coder.PointerCoder; -import com.apple.jobjc.Coder.PrimitivePointerCoder; -import com.apple.jobjc.Invoke.MsgSend; - -public class SELTest extends PooledTestCase { - - NativeArgumentBuffer nativeBuffer; - JObjCRuntime runtime; - - @Override - public void setUp() throws Exception { - super.setUp(); - nativeBuffer = UnsafeRuntimeAccess.getNativeBuffer(); - runtime = nativeBuffer.runtime; - } - - public void testGetBlackColor() throws Throwable { - final MacOSXFramework appKit = TestUtils.getAppKit(); - final NSClass clazz = UnsafeRuntimeAccess.getNSClass(appKit, "NSColor"); - final MsgSend sel = UnsafeRuntimeAccess.createMsgSend(clazz, "redColor", PointerCoder.INST); - - sel.init(nativeBuffer, clazz); - sel.invoke(nativeBuffer); - - final long blackColorPtr = PrimitivePointerCoder.INST.pop(nativeBuffer); - String dscr = UnsafeRuntimeAccess.getDescriptionForPtr(blackColorPtr); - - System.out.println("0x" + Long.toHexString(blackColorPtr) + ": " + dscr); - assertEquals("NSCalibratedRGBColorSpace 1 0 0 1", dscr); - } - - public static void main(final String[] args) { - junit.textui.TestRunner.run(SELTest.class); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/StructTest.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/StructTest.java deleted file mode 100644 index b55e731fa58..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/StructTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import java.io.StringWriter; - -import com.apple.jobjc.coreaudio.AudioBuffer; -import com.apple.jobjc.foundation.NSPoint; -import com.apple.jobjc.foundation.NSRect; - -public class StructTest extends PooledTestCase { - public void testSimpleStruct(){ - AudioBuffer b = JObjC.getInstance().CoreAudio().makeAudioBuffer(); - assertEquals(0, b.mNumberChannels()); - assertEquals(0, b.mDataByteSize()); - b.setMNumberChannels(1); - b.setMDataByteSize(3); - assertEquals(1, b.mNumberChannels()); - assertEquals(3, b.mDataByteSize()); - } - - public void testNestedStruct(){ - NSRect r = JObjC.getInstance().Foundation().makeNSRect(); - assertTrue(0f == r.size().width()); - r.size().setWidth(3f); - assertTrue(3f == r.size().width()); - assertTrue(r.size() == r.size()); - } - - public void testSTRET(){ - NSPoint point = JObjC.getInstance().Foundation().NSMakePoint(3, 4); - assertTrue(point.x() == 3); - assertTrue(point.y() == 4); - - NSRect rect = JObjC.getInstance().Foundation().NSMakeRect(0, 1, 2, 3); - assertTrue(rect.origin().x() == 0); - assertTrue(rect.origin().y() == 1); - assertTrue(rect.size().width() == 2); - assertTrue(rect.size().height() == 3); - } - - // - - private char halfByteToHex(int b){ - return (b >= 0x0 && b < 0xA) ? (char) ('0' + b) : (char) ('A' + (b-0xA)); - } - - private String byteToHexString(Byte b){ - StringWriter sw = new StringWriter(); - sw.append(halfByteToHex(b & 0xF)); - sw.append(halfByteToHex((b & 0xF0) >> 4)); - return sw.toString(); - } - - String print(Struct st){ - StringWriter sw = new StringWriter(); - st.raw.position(0); - sw.append(st.getClass().getSimpleName() + ":" + st.raw.limit() + " @ " + Long.toHexString(st.raw.bufferPtr) + " : "); - for(int i = 0; i < st.raw.limit(); i++){ - sw.append(byteToHexString(st.raw.get()) + " "); - if((i+1) % 4 == 0) - sw.append(" "); - } - System.out.println(sw.toString().trim()); - return sw.toString().trim(); - } - - public static void main(String[] args){ - junit.textui.TestRunner.run(StructTest.class); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/SubclassingTest.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/SubclassingTest.java deleted file mode 100644 index bfe91440d2b..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/SubclassingTest.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.jobjc.Coder.IDCoder; -import com.apple.jobjc.Coder.VoidCoder; -import com.apple.jobjc.Invoke.MsgSend; -import com.apple.jobjc.Invoke.MsgSendSuper; -import com.apple.jobjc.PrimitiveCoder.DoubleCoder; -import com.apple.jobjc.PrimitiveCoder.FloatCoder; -import com.apple.jobjc.PrimitiveCoder.SIntCoder; -import com.apple.jobjc.PrimitiveCoder.SLongLongCoder; -import com.apple.jobjc.foundation.NSObject; -import com.apple.jobjc.foundation.NSObjectClass; -import com.apple.jobjc.foundation.NSPoint; -import com.apple.jobjc.foundation.NSString; - -public class SubclassingTest extends PooledTestCase{ - JObjCRuntime runtime; - NativeArgumentBuffer ctx; - - @Override public void setUp() throws Exception{ - super.setUp(); - this.runtime = JObjCRuntime.getInstance(); - this.ctx = runtime.getThreadLocalState(); - - runtime.registerUserClass(MyObject.class, MyObjectClass.class); - } - - public void testClass(){ - final MyObjectClass cls = new MyObjectClass(runtime); - assertEquals(MyObject.class.getSimpleName(), UnsafeRuntimeAccess.getClassNameFor(cls)); - } - - public void testInst(){ - final MyObjectClass cls = new MyObjectClass(runtime); - final MyObject instObj = cls.alloc(); - final MyObject retrievedObj = Subclassing.getJObjectFromIVar(UnsafeRuntimeAccess.getObjPtr(instObj)); - assertTrue(instObj == retrievedObj); - } - - public void testVoidVoidMethod(){ - final MyObject instObj = new MyObjectClass(runtime).alloc(); - - assertEquals(0, instObj.myMethodHits); - MsgSend sel = new MsgSend(runtime, "myMethod", VoidCoder.INST); - sel.init(ctx, instObj); - sel.invoke(ctx); - assertEquals(1, instObj.myMethodHits); - } - - public void testMsgSendSuper(){ - final MyObjectClass cls = new MyObjectClass(runtime); - final MyObject obj = ((MyObject) cls.alloc()).init(); - - // direct descr - - assertEquals("foo", Utils.get().strings().javaString(obj.description())); - - // indirect (from native) descr - { - MsgSend msgSend = new MsgSend(runtime, "description", IDCoder.INST); - msgSend.init(ctx, obj); - msgSend.invoke(ctx); - assertEquals("foo", Utils.get().strings().javaString((NSString) IDCoder.INST.pop(ctx))); - } - - // indirect (from native) descr - { - MsgSendSuper msgSendSuper = new MsgSendSuper(runtime, "description", IDCoder.INST); - msgSendSuper.init(ctx, obj, cls); - msgSendSuper.invoke(ctx); - assertEquals("foo", Utils.get().strings().javaString((NSString) IDCoder.INST.pop(ctx))); - } - - // nso descr - { - MsgSendSuper msgSendSuper = new MsgSendSuper(runtime, "description", IDCoder.INST); - msgSendSuper.init(ctx, obj, JObjC.getInstance().Foundation().NSObject()); - msgSendSuper.invoke(ctx); - - final NSString nsod = (NSString) IDCoder.INST.pop(ctx); - String jde = Utils.get().strings().javaString(nsod); - assertEquals(jde.substring(0, 9), " 0) - js2 += jss; - return Utils.get().strings().nsString(js2); - } - - public double add_and_and(int a, long b, float c){ - return a + b + c; - } - - public NSPoint doubleIt(NSPoint p){ - System.out.println("Doubling NSPoint(" + p.x() + ", " + p.y() + ")."); - p.setX(p.x() * 2); - p.setY(p.y() * 2); - return p; - } - - @Override public NSString description(){ - return Utils.get().strings().nsString("foo"); - } -} - -class MyObjectClass extends NSObjectClass{ - protected MyObjectClass(String name, JObjCRuntime runtime) { - super(name, runtime); - } - - public MyObjectClass(JObjCRuntime runtime){ - this("MyObject", runtime); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/UtilsTest.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/UtilsTest.java deleted file mode 100644 index b77a82f92af..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/UtilsTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import java.util.concurrent.Callable; - -import com.apple.jobjc.foundation.NSString; - -public class UtilsTest extends PooledTestCase{ - public void testStrings(){ - String s = "fooBarBazDazzle"; - NSString ns = Utils.get().strings().nsString(s); - String t = Utils.get().strings().javaString(ns); - assertEquals(s, t); - } - - public void testThreadsPerformRunnableOnMainThread(){ - final long testThreadId = Thread.currentThread().getId(); - class Wrap{ public long x = testThreadId; } - final Wrap wrap = new Wrap(); - assertTrue(testThreadId == wrap.x); - - Utils.get().threads().performOnMainThread(new Runnable(){ - public void run() { - wrap.x = Thread.currentThread().getId(); - } - }, true); - - assertTrue(testThreadId != wrap.x); - } - - public void testThreadsPerformCallableOnMainThread() throws Exception{ - final long testThreadId = Thread.currentThread().getId(); - final long mainThreadId = Utils.get().threads().performOnMainThread(new Callable(){ - public Long call() { return Thread.currentThread().getId(); } - }); - assertTrue(testThreadId != mainThreadId); - } - - public void testThreadsPerformCallableOnMainThreadException() throws Exception{ - class FooException extends RuntimeException{} - try { - Utils.get().threads().performOnMainThread(new Callable(){ - public Object call() { throw new FooException(); } - }); - } catch (FooException e) { - return; - } - fail("Failed to catch exception."); - } - - public static void main(String[] args){ - junit.textui.TestRunner.run(UtilsTest.class); - } -} - diff --git a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/VarArgsTest.java b/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/VarArgsTest.java deleted file mode 100644 index 6d8774ece87..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/java/com/apple/jobjc/VarArgsTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 - * 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 com.apple.jobjc; - -import com.apple.jobjc.foundation.FoundationFramework; -import com.apple.jobjc.foundation.NSDictionary; -import com.apple.jobjc.foundation.NSString; - -public class VarArgsTest extends PooledTestCase { - FoundationFramework FND = JObjC.getInstance().Foundation(); - - public void testNSString_initWithFormat(){ - String expected = "1 + 0.2 = 1.2 abracadabra"; - NSString format = Utils.get().strings().nsString("%d + %.1f = %.1f %@"); - - NSString abra = Utils.get().strings().nsString("abracadabra"); - - NSString nstr = ((NSString)FND.NSString().alloc()).initWithFormat(format, 1, 0.2, 1.2, abra); - String actual = Utils.get().strings().javaString(nstr); - - assertEquals(expected, actual); - } - - public void testNSDictionary(){ - NSString v1 = Utils.get().strings().nsString("value1"); - NSString v2 = Utils.get().strings().nsString("value2"); - NSString k1 = Utils.get().strings().nsString("key1"); - NSString k2 = Utils.get().strings().nsString("key2"); - - NSDictionary dict = ((NSDictionary)FND.NSDictionary().alloc()).initWithObjectsAndKeys(v1, k1, v2, k2, null); - - NSString nsdescr = dict.description(); - String jdescr = Utils.get().strings().javaString(nsdescr); - - assertEquals("{\n key1 = value1;\n key2 = value2;\n}", jdescr); - } - - public static void main(String[] args){ - junit.textui.TestRunner.run(VarArgsTest.class); - } -} diff --git a/jdk/src/macosx/native/jobjc/src/tests/native/FunCallBench.m b/jdk/src/macosx/native/jobjc/src/tests/native/FunCallBench.m deleted file mode 100644 index 3c5f9adcc8f..00000000000 --- a/jdk/src/macosx/native/jobjc/src/tests/native/FunCallBench.m +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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 - * 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. - */ -#include -#include - -#include "com_apple_jobjc_BenchFunCall.h" -#include - -JNIEXPORT jdouble JNICALL Java_com_apple_jobjc_BenchFunCall_jniSin -(JNIEnv *env, jclass clazz, jdouble x) -{ - return (jdouble) sin((double) x); -} - - -#include "com_apple_jobjc_BenchIDPop.h" - -JNIEXPORT void JNICALL Java_com_apple_jobjc_BenchIDPop_jniCFRetain -(JNIEnv *env, jclass clazz, jlong x) -{ - CFRetain(jlong_to_ptr(x)); -} - -JNIEXPORT void JNICALL Java_com_apple_jobjc_BenchIDPop_jniCFRelease -(JNIEnv *env, jclass clazz, jlong x) -{ - CFRelease(jlong_to_ptr(x)); -} - -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_BenchIDPop_jniNSStringAlloc -(JNIEnv *env, jclass clazz) -{ - return ptr_to_jlong([NSString alloc]); -} - -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_BenchIDPop_jniNSStringAllocAndRetain -(JNIEnv *env, jclass clazz) -{ - return ptr_to_jlong(CFRetain([NSString alloc])); -} - -JNIEXPORT jlong JNICALL Java_com_apple_jobjc_BenchIDPop_jniNSStringCached -(JNIEnv *env, jclass clazz) -{ - static jlong str = 0; - if(!str) str = ptr_to_jlong([NSString alloc]); - return str; -} diff --git a/jdk/src/macosx/native/sun/awt/AWTView.m b/jdk/src/macosx/native/sun/awt/AWTView.m index 830fb77e82b..a59ff1a51ae 100644 --- a/jdk/src/macosx/native/sun/awt/AWTView.m +++ b/jdk/src/macosx/native/sun/awt/AWTView.m @@ -440,17 +440,20 @@ AWT_ASSERT_APPKIT_THREAD; JNIEnv *env = [ThreadUtilities getJNIEnv]; jstring characters = NULL; + jstring charactersIgnoringModifiers = NULL; if ([event type] != NSFlagsChanged) { characters = JNFNSToJavaString(env, [event characters]); + charactersIgnoringModifiers = JNFNSToJavaString(env, [event charactersIgnoringModifiers]); } static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent"); - static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IISLjava/lang/String;)V"); + static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IISLjava/lang/String;Ljava/lang/String;)V"); jobject jEvent = JNFNewObject(env, jctor_NSEvent, [event type], [event modifierFlags], [event keyCode], - characters); + characters, + charactersIgnoringModifiers); CHECK_NULL(jEvent); static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView"); diff --git a/jdk/src/macosx/native/sun/awt/AWTWindow.m b/jdk/src/macosx/native/sun/awt/AWTWindow.m index 6a9c1166e84..5cb5621a159 100644 --- a/jdk/src/macosx/native/sun/awt/AWTWindow.m +++ b/jdk/src/macosx/native/sun/awt/AWTWindow.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -252,6 +252,10 @@ AWT_ASSERT_APPKIT_THREAD; self.ownerWindow = owner; [self setPropertiesForStyleBits:styleBits mask:MASK(_METHOD_PROP_BITMASK)]; + if (IS(self.styleBits, IS_POPUP)) { + [self.nsWindow setCollectionBehavior:(1 << 8) /*NSWindowCollectionBehaviorFullScreenAuxiliary*/]; + } + return self; } diff --git a/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m b/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m index a1813b6154d..36df94b1236 100644 --- a/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m +++ b/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m @@ -57,7 +57,7 @@ static CFMutableArrayRef getAllValidDisplayModes(jint displayID){ CFArrayRef allModes = CGDisplayCopyAllDisplayModes(displayID, NULL); CFIndex numModes = CFArrayGetCount(allModes); - CFMutableArrayRef validModes = CFArrayCreateMutable(kCFAllocatorDefault, numModes + 1, NULL); + CFMutableArrayRef validModes = CFArrayCreateMutable(kCFAllocatorDefault, numModes + 1, &kCFTypeArrayCallBacks); CFIndex n; for (n=0; n < numModes; n++) { diff --git a/jdk/src/macosx/native/sun/awt/CWrapper.m b/jdk/src/macosx/native/sun/awt/CWrapper.m index 247358f0df9..bf0d6b2fccd 100644 --- a/jdk/src/macosx/native/sun/awt/CWrapper.m +++ b/jdk/src/macosx/native/sun/awt/CWrapper.m @@ -337,12 +337,17 @@ JNF_COCOA_EXIT(env); */ JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CWrapper_00024NSWindow_setBackgroundColor -(JNIEnv *env, jclass cls, jlong windowPtr, jlong colorPtr) +(JNIEnv *env, jclass cls, jlong windowPtr, jint rgb) { JNF_COCOA_ENTER(env); NSWindow *window = (NSWindow *)jlong_to_ptr(windowPtr); - NSColor *color = (NSColor *)jlong_to_ptr(colorPtr); + CGFloat alpha = (((rgb >> 24) & 0xff) / 255.0); + CGFloat red = (((rgb >> 16) & 0xff) / 255.0); + CGFloat green = (((rgb >> 8) & 0xff) / 255.0); + CGFloat blue = (((rgb >> 0) & 0xff) / 255.0); + NSColor *color = [NSColor colorWithCalibratedRed:red green:green blue:blue + alpha:alpha]; [ThreadUtilities performOnMainThreadWaiting:NO block:^(){ [window setBackgroundColor:color]; }]; @@ -575,26 +580,3 @@ JNF_COCOA_ENTER(env); JNF_COCOA_EXIT(env); } - -/* - * Class: sun_lwawt_macosx_CWrapper$NSColor - * Method: clearColor - * Signature: ()J - */ -JNIEXPORT jlong JNICALL -Java_sun_lwawt_macosx_CWrapper_00024NSColor_clearColor -(JNIEnv *env, jclass cls) -{ - __block jlong clearColorPtr = 0L; - -JNF_COCOA_ENTER(env); - - [ThreadUtilities performOnMainThreadWaiting:YES block:^(){ - clearColorPtr = ptr_to_jlong([NSColor clearColor]); - }]; - -JNF_COCOA_EXIT(env); - - return clearColorPtr; -} - diff --git a/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m b/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m index c7dd0b78726..7deb34d0baa 100644 --- a/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m +++ b/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m @@ -36,7 +36,7 @@ static JNIEnv *appKitEnv = NULL; static jobject appkitThreadGroup = NULL; static BOOL awtEmbedded = NO; -inline void attachCurrentThread(void** env) { +static inline void attachCurrentThread(void** env) { if ([NSThread isMainThread]) { JavaVMAttachArgs args; args.version = JNI_VERSION_1_4; diff --git a/jdk/src/share/classes/com/sun/crypto/provider/CipherCore.java b/jdk/src/share/classes/com/sun/crypto/provider/CipherCore.java index 8d54633adb1..6b5eea85d6d 100644 --- a/jdk/src/share/classes/com/sun/crypto/provider/CipherCore.java +++ b/jdk/src/share/classes/com/sun/crypto/provider/CipherCore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -720,6 +720,15 @@ final class CipherCore { int outLen = 0; if (len != 0) { // there is some work to do + if ((input == output) + && (outputOffset < (inputOffset + inputLen)) + && (inputOffset < (outputOffset + buffer.length))) { + // copy 'input' out to avoid its content being + // overwritten prematurely. + input = Arrays.copyOfRange(input, inputOffset, + inputOffset + inputLen); + inputOffset = 0; + } if (len <= buffered) { // all to-be-processed data are from 'buffer' if (decrypting) { @@ -732,37 +741,37 @@ final class CipherCore { System.arraycopy(buffer, len, buffer, 0, buffered); } } else { // len > buffered - if ((input != output) && (buffered == 0)) { - // all to-be-processed data are from 'input' - // however, note that if 'input' and 'output' are the same, - // then they can't be passed directly to the underlying cipher - // engine operations as data may be overwritten before they - // are read. + int inputConsumed = len - buffered; + int temp; + if (buffered > 0) { + int bufferCapacity = buffer.length - buffered; + if (bufferCapacity != 0) { + temp = Math.min(bufferCapacity, inputConsumed); + System.arraycopy(input, inputOffset, buffer, buffered, temp); + inputOffset += temp; + inputConsumed -= temp; + inputLen -= temp; + buffered += temp; + } + // process 'buffer' if (decrypting) { - outLen = cipher.decrypt(input, inputOffset, len, output, outputOffset); + outLen = cipher.decrypt(buffer, 0, buffered, output, outputOffset); } else { - outLen = cipher.encrypt(input, inputOffset, len, output, outputOffset); - } - inputOffset += len; - inputLen -= len; - } else { - // assemble the data using both 'buffer' and 'input' - byte[] in = new byte[len]; - int inConsumed = len - buffered; - if (buffered != 0) { - System.arraycopy(buffer, 0, in, 0, buffered); - buffered = 0; - } - if (inConsumed != 0) { - System.arraycopy(input, inputOffset, in, len - inConsumed, inConsumed); - inputOffset += inConsumed; - inputLen -= inConsumed; + outLen = cipher.encrypt(buffer, 0, buffered, output, outputOffset); } + outputOffset += outLen; + buffered = 0; + } + if (inputConsumed > 0) { // still has input to process if (decrypting) { - outLen = cipher.decrypt(in, 0, len, output, outputOffset); + outLen += cipher.decrypt(input, inputOffset, inputConsumed, + output, outputOffset); } else { - outLen = cipher.encrypt(in, 0, len, output, outputOffset); + outLen += cipher.encrypt(input, inputOffset, inputConsumed, + output, outputOffset); } + inputOffset += inputConsumed; + inputLen -= inputConsumed; } } // Let's keep track of how many bytes are needed to make @@ -925,8 +934,10 @@ final class CipherCore { byte[] finalBuf = input; int finalOffset = inputOffset; int finalBufLen = inputLen; - if ((input == output) || (buffered != 0) || - (!decrypting && padding != null)) { + if ((buffered != 0) || (!decrypting && padding != null) || + ((input == output) + && (outputOffset < (inputOffset + inputLen)) + && (inputOffset < (outputOffset + buffer.length)))) { if (decrypting || padding == null) { paddingLen = 0; } diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java index 961f7a0682e..82814627077 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java @@ -616,7 +616,7 @@ public class GIFImageReader extends ImageReader { return index; } - Long l1 = new Long(stream.getStreamPosition()); + Long l1 = stream.getStreamPosition(); imageStartPosition.add(l1); ++index; } diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java index 961255ce8c9..5743cedc904 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java @@ -89,7 +89,7 @@ public class JPEGImageReader extends ImageReader { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Void run() { - System.loadLibrary("jpeg"); + System.loadLibrary("javajpeg"); return null; } }); @@ -367,10 +367,10 @@ public class JPEGImageReader extends ImageReader { // Now we are at the first image if there are any, so add it // to the list if (hasNextImage()) { - imagePositions.add(new Long(iis.getStreamPosition())); + imagePositions.add(iis.getStreamPosition()); } } else { // Not tables only, so add original pos to the list - imagePositions.add(new Long(savePos)); + imagePositions.add(savePos); // And set current image since we've read it now currentImage = 0; } @@ -498,7 +498,7 @@ public class JPEGImageReader extends ImageReader { if (!hasNextImage()) { throw new IndexOutOfBoundsException(); } - pos = new Long(iis.getStreamPosition()); + pos = iis.getStreamPosition(); imagePositions.add(pos); if (seekForwardOnly) { iis.flushBefore(pos.longValue()); diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java index 1913ef4641f..477e6738b5f 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageWriter.java @@ -179,7 +179,7 @@ public class JPEGImageWriter extends ImageWriter { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Void run() { - System.loadLibrary("jpeg"); + System.loadLibrary("javajpeg"); return null; } }); diff --git a/jdk/src/share/classes/com/sun/java/browser/dom/DOMAccessException.java b/jdk/src/share/classes/com/sun/java/browser/dom/DOMAccessException.java deleted file mode 100644 index 77307d834f5..00000000000 --- a/jdk/src/share/classes/com/sun/java/browser/dom/DOMAccessException.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.java.browser.dom; - -@SuppressWarnings("serial") // JDK implementation class -public class DOMAccessException extends Exception -{ - /** - * Constructs a new DOMAccessException with no detail message. - */ - public DOMAccessException() - { - this(null, null); - } - - - /** - * Constructs a new DOMAccessException with the given detail message. - * - * @param msg Detail message. - */ - public DOMAccessException(String msg) - { - this(null, msg); - } - - /** - * Constructs a new DOMAccessException with the given exception as a root clause. - * - * @param e Exception. - */ - public DOMAccessException(Exception e) - { - this(e, null); - } - - /** - * Constructs a new DOMAccessException with the given exception as a root clause and the given detail message. - * - * @param e Exception. - * @param msg Detail message. - */ - public DOMAccessException(Exception e, String msg) - { - this.ex = e; - this.msg = msg; - } - - /** - * Returns the detail message of the error or null if there is no detail message. - */ - public String getMessage() - { - return msg; - } - - /** - * Returns the root cause of the error or null if there is none. - */ - public Throwable getCause() - { - return ex; - } - - private Throwable ex; - private String msg; -} diff --git a/jdk/src/share/classes/com/sun/java/browser/dom/DOMService.java b/jdk/src/share/classes/com/sun/java/browser/dom/DOMService.java deleted file mode 100644 index 9a418cf5edc..00000000000 --- a/jdk/src/share/classes/com/sun/java/browser/dom/DOMService.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.java.browser.dom; - -import java.security.AccessController; -import java.security.PrivilegedAction; - -public abstract class DOMService -{ - /** - * Returns new instance of a DOMService. The implementation - * of the DOMService returns depends on the setting of the - * com.sun.java.browser.dom.DOMServiceProvider property or, - * if the property is not set, a platform specific default. - * - * Throws DOMUnsupportedException if the DOMService is not - * available to the obj. - * - * @param obj Object to leverage the DOMService - */ - public static DOMService getService(Object obj) - throws DOMUnsupportedException - { - try - { - String provider = AccessController.doPrivileged( - (PrivilegedAction) () -> - System.getProperty("com.sun.java.browser.dom.DOMServiceProvider")); - - Class clazz = Class.forName("sun.plugin.dom.DOMService"); - - return (DOMService) clazz.newInstance(); - } - catch (Throwable e) - { - throw new DOMUnsupportedException(e.toString()); - } - } - - /** - * An empty constructor is provided. Implementations of this - * abstract class must provide a public no-argument constructor - * in order for the static getService() method to work correctly. - * Application programmers should not be able to directly - * construct implementation subclasses of this abstract subclass. - */ - public DOMService() - { - } - - /** - * Causes action.run() to be executed synchronously on the - * DOM action dispatching thread. This call will block until all - * pending DOM actions have been processed and (then) - * action.run() returns. This method should be used when an - * application thread needs to access the browser's DOM. - * It should not be called from the DOMActionDispatchThread. - * - * Note that if the DOMAction.run() method throws an uncaught - * exception (on the DOM action dispatching thread), it's caught - * and re-thrown, as an DOMAccessException, on the caller's thread. - * - * If the DOMAction.run() method throws any DOM security related - * exception (on the DOM action dispatching thread), it's caught - * and re-thrown, as an DOMSecurityException, on the caller's thread. - * - * @param action DOMAction. - */ - public abstract Object invokeAndWait(DOMAction action) throws DOMAccessException; - - /** - * Causes action.run() to be executed asynchronously on the - * DOM action dispatching thread. This method should be used - * when an application thread needs to access the browser's - * DOM. It should not be called from the DOMActionDispatchThread. - * - * Note that if the DOMAction.run() method throws an uncaught - * exception (on the DOM action dispatching thread), it will not be - * caught and re-thrown on the caller's thread. - * - * @param action DOMAction. - */ - public abstract void invokeLater(DOMAction action); -} diff --git a/jdk/src/share/classes/com/sun/java/browser/dom/DOMServiceProvider.java b/jdk/src/share/classes/com/sun/java/browser/dom/DOMServiceProvider.java deleted file mode 100644 index 8cd7aa1e3a8..00000000000 --- a/jdk/src/share/classes/com/sun/java/browser/dom/DOMServiceProvider.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2000, 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 com.sun.java.browser.dom; - -public abstract class DOMServiceProvider -{ - /** - * An empty constructor is provided. Implementations should - * provide a public constructor so that the DOMService - * can instantiate instances of the implementation class. - * Application programmers should not be able to directly - * construct implementation subclasses of this abstract subclass. - * The only way an application should be able to obtain a - * reference to a DOMServiceProvider implementation - * instance is by using the appropriate methods of the - * DOMService. - */ - public DOMServiceProvider() - { - } - - /** - * Returns true if the DOMService can determine the association - * between the obj and the underlying DOM in the browser. - */ - public abstract boolean canHandle(Object obj); - - /** - * Returns the Document object of the DOM. - */ - public abstract org.w3c.dom.Document getDocument(Object obj) throws DOMUnsupportedException; - - /** - * Returns the DOMImplemenation object of the DOM. - */ - public abstract org.w3c.dom.DOMImplementation getDOMImplementation(); -} diff --git a/jdk/src/share/classes/com/sun/java/browser/dom/DOMUnsupportedException.java b/jdk/src/share/classes/com/sun/java/browser/dom/DOMUnsupportedException.java deleted file mode 100644 index 2796339f39a..00000000000 --- a/jdk/src/share/classes/com/sun/java/browser/dom/DOMUnsupportedException.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package com.sun.java.browser.dom; - -@SuppressWarnings("serial") // JDK implementation class -public class DOMUnsupportedException extends Exception -{ - /** - * Constructs a new DOMUnsupportedException with no detail message. - */ - public DOMUnsupportedException() - { - this(null, null); - } - - /** - * Constructs a new DOMUnsupportedException with the given detail message. - * - * @param msg Detail message. - */ - public DOMUnsupportedException(String msg) - { - this(null, msg); - } - - /** - * Constructs a new DOMUnsupportedException with the given exception as a root clause. - * - * @param e Exception. - */ - public DOMUnsupportedException(Exception e) - { - this(e, null); - } - - /** - * Constructs a new DOMUnsupportedException with the given exception as a root clause and the given detail message. - * - * @param e Exception. - * @param msg Detail message. - */ - public DOMUnsupportedException(Exception e, String msg) - { - this.ex = e; - this.msg = msg; - } - - /** - * Returns the detail message of the error or null if there is no detail message. - */ - public String getMessage() - { - return msg; - } - - /** - * Returns the root cause of the error or null if there is none. - */ - public Throwable getCause() - { - return ex; - } - - private Throwable ex; - private String msg; -} diff --git a/jdk/src/share/classes/com/sun/java/browser/net/ProxyService.java b/jdk/src/share/classes/com/sun/java/browser/net/ProxyService.java deleted file mode 100644 index b4960905fda..00000000000 --- a/jdk/src/share/classes/com/sun/java/browser/net/ProxyService.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2001, 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 com.sun.java.browser.net; - -import java.net.URL; -import java.io.IOException; - -/** - * - * @author Zhengyu Gu - */ -public class ProxyService extends Object { - private static ProxyServiceProvider provider = null; - - - public static void setProvider(ProxyServiceProvider p) - throws IOException { - if(null == provider) - provider = p; - else - throw new IOException("Proxy service provider has already been set."); - } - - - /** - *

The function returns proxy information of the specified URL.

- * @param url URL - * @return returns proxy information. If there is not proxy, returns null - * @since 1.4 - */ - public static ProxyInfo[] getProxyInfo(URL url) - throws IOException { - if(null == provider) - throw new IOException("Proxy service provider is not yet set"); - - return provider.getProxyInfo(url); - } -} diff --git a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java index 1ca240dd743..6b2891aa517 100644 --- a/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java +++ b/jdk/src/share/classes/com/sun/java/swing/SwingUtilities3.java @@ -25,15 +25,13 @@ package com.sun.java.swing; -import sun.awt.EventQueueDelegate; import sun.awt.AppContext; +import sun.awt.SunToolkit; + import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; -import java.util.concurrent.Callable; import java.applet.Applet; -import java.awt.AWTEvent; -import java.awt.EventQueue; import java.awt.Component; import java.awt.Container; import java.awt.Window; @@ -117,8 +115,8 @@ public class SwingUtilities3 { public static RepaintManager getDelegateRepaintManager(Component component) { RepaintManager delegate = null; - if (Boolean.TRUE == AppContext.getAppContext().get( - DELEGATE_REPAINT_MANAGER_KEY)) { + if (Boolean.TRUE == SunToolkit.targetToAppContext(component) + .get(DELEGATE_REPAINT_MANAGER_KEY)) { while (delegate == null && component != null) { while (component != null && ! (component instanceof JComponent)) { @@ -135,86 +133,4 @@ public class SwingUtilities3 { } return delegate; } - - /* - * We use maps to avoid reflection. Hopefully it should perform better - * this way. - */ - public static void setEventQueueDelegate( - Map> map) { - EventQueueDelegate.setDelegate(new EventQueueDelegateFromMap(map)); - } - - private static class EventQueueDelegateFromMap - implements EventQueueDelegate.Delegate { - private final AWTEvent[] afterDispatchEventArgument; - private final Object[] afterDispatchHandleArgument; - private final Callable afterDispatchCallable; - - private final AWTEvent[] beforeDispatchEventArgument; - private final Callable beforeDispatchCallable; - - private final EventQueue[] getNextEventEventQueueArgument; - private final Callable getNextEventCallable; - - @SuppressWarnings("unchecked") - public EventQueueDelegateFromMap(Map> objectMap) { - Map methodMap = objectMap.get("afterDispatch"); - afterDispatchEventArgument = (AWTEvent[]) methodMap.get("event"); - afterDispatchHandleArgument = (Object[]) methodMap.get("handle"); - afterDispatchCallable = (Callable) methodMap.get("method"); - - methodMap = objectMap.get("beforeDispatch"); - beforeDispatchEventArgument = (AWTEvent[]) methodMap.get("event"); - beforeDispatchCallable = (Callable) methodMap.get("method"); - - methodMap = objectMap.get("getNextEvent"); - getNextEventEventQueueArgument = - (EventQueue[]) methodMap.get("eventQueue"); - getNextEventCallable = (Callable) methodMap.get("method"); - } - - @Override - public void afterDispatch(AWTEvent event, Object handle) throws InterruptedException { - afterDispatchEventArgument[0] = event; - afterDispatchHandleArgument[0] = handle; - try { - afterDispatchCallable.call(); - } catch (InterruptedException e) { - throw e; - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public Object beforeDispatch(AWTEvent event) throws InterruptedException { - beforeDispatchEventArgument[0] = event; - try { - return beforeDispatchCallable.call(); - } catch (InterruptedException e) { - throw e; - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public AWTEvent getNextEvent(EventQueue eventQueue) throws InterruptedException { - getNextEventEventQueueArgument[0] = eventQueue; - try { - return getNextEventCallable.call(); - } catch (InterruptedException e) { - throw e; - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } } diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java index b0a811c3bbf..85527e44a4c 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java @@ -547,7 +547,7 @@ class Metacity implements SynthConstants { i = strLowerCase.indexOf("", i); if (i > 0) { i += "".length(); - int i2 = str.indexOf("<", i); + int i2 = str.indexOf('<', i); return str.substring(i, i2); } } diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java index a6c1c895757..5998f85483c 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java @@ -1102,8 +1102,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel "PasswordField.selectionBackground", SelectionBackgroundColor, "PasswordField.selectionForeground", SelectionTextColor, "PasswordField.caretForeground",WindowTextColor, - "PasswordField.echoChar", new XPValue(new Character((char)0x25CF), - new Character('*')), + "PasswordField.echoChar", new XPValue((char)0x25CF, '*'), // *** ProgressBar "ProgressBar.font", ControlFont, diff --git a/jdk/src/share/classes/com/sun/jmx/snmp/SnmpCounter64.java b/jdk/src/share/classes/com/sun/jmx/snmp/SnmpCounter64.java index 7d29b251127..f65d887050b 100644 --- a/jdk/src/share/classes/com/sun/jmx/snmp/SnmpCounter64.java +++ b/jdk/src/share/classes/com/sun/jmx/snmp/SnmpCounter64.java @@ -84,7 +84,7 @@ public class SnmpCounter64 extends SnmpValue { * @return The Long representation of the value. */ public Long toLong() { - return new Long(value) ; + return value; } /** diff --git a/jdk/src/share/classes/com/sun/jmx/snmp/SnmpInt.java b/jdk/src/share/classes/com/sun/jmx/snmp/SnmpInt.java index a6114d7dbc5..eb536581bb8 100644 --- a/jdk/src/share/classes/com/sun/jmx/snmp/SnmpInt.java +++ b/jdk/src/share/classes/com/sun/jmx/snmp/SnmpInt.java @@ -130,7 +130,7 @@ public class SnmpInt extends SnmpValue { * @return The Long representation of the value. */ public Long toLong() { - return new Long(value) ; + return value; } /** diff --git a/jdk/src/share/classes/com/sun/jmx/snmp/SnmpString.java b/jdk/src/share/classes/com/sun/jmx/snmp/SnmpString.java index 169b67bcad3..675386ab1be 100644 --- a/jdk/src/share/classes/com/sun/jmx/snmp/SnmpString.java +++ b/jdk/src/share/classes/com/sun/jmx/snmp/SnmpString.java @@ -140,7 +140,7 @@ public class SnmpString extends SnmpValue { public Byte[] toByte() { Byte[] result = new Byte[value.length] ; for (int i = 0 ; i < value.length ; i++) { - result[i] = new Byte(value[i]) ; + result[i] = value[i]; } return result ; } diff --git a/jdk/src/share/classes/com/sun/jmx/snmp/agent/SnmpMibGroup.java b/jdk/src/share/classes/com/sun/jmx/snmp/agent/SnmpMibGroup.java index b689ef287e7..99223ea0cb8 100644 --- a/jdk/src/share/classes/com/sun/jmx/snmp/agent/SnmpMibGroup.java +++ b/jdk/src/share/classes/com/sun/jmx/snmp/agent/SnmpMibGroup.java @@ -136,7 +136,7 @@ public abstract class SnmpMibGroup extends SnmpMibOid */ public boolean isNestedArc(long arc) { if (subgroups == null) return false; - Object obj = subgroups.get(new Long(arc)); + Object obj = subgroups.get(arc); // if the arc is registered in the hashtable, // it leads to a subgroup. return (obj != null); @@ -260,7 +260,7 @@ public abstract class SnmpMibGroup extends SnmpMibOid * */ void registerNestedArc(long arc) { - Long obj = new Long(arc); + Long obj = arc; if (subgroups == null) subgroups = new Hashtable<>(); // registers the arc in the hashtable. subgroups.put(obj,obj); diff --git a/jdk/src/share/classes/com/sun/jmx/snmp/daemon/SnmpAdaptorServer.java b/jdk/src/share/classes/com/sun/jmx/snmp/daemon/SnmpAdaptorServer.java index 612d4c57437..b55c32ab1ea 100644 --- a/jdk/src/share/classes/com/sun/jmx/snmp/daemon/SnmpAdaptorServer.java +++ b/jdk/src/share/classes/com/sun/jmx/snmp/daemon/SnmpAdaptorServer.java @@ -858,7 +858,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpOutTraps() { - return new Long(snmpOutTraps); + return (long)snmpOutTraps; } /** @@ -868,7 +868,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpOutGetResponses() { - return new Long(snmpOutGetResponses); + return (long)snmpOutGetResponses; } /** @@ -878,7 +878,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpOutGenErrs() { - return new Long(snmpOutGenErrs); + return (long)snmpOutGenErrs; } /** @@ -888,7 +888,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpOutBadValues() { - return new Long(snmpOutBadValues); + return (long)snmpOutBadValues; } /** @@ -898,7 +898,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpOutNoSuchNames() { - return new Long(snmpOutNoSuchNames); + return (long)snmpOutNoSuchNames; } /** @@ -908,7 +908,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpOutTooBigs() { - return new Long(snmpOutTooBigs); + return (long)snmpOutTooBigs; } /** @@ -918,7 +918,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpInASNParseErrs() { - return new Long(snmpInASNParseErrs); + return (long)snmpInASNParseErrs; } /** @@ -928,7 +928,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpInBadCommunityUses() { - return new Long(snmpInBadCommunityUses); + return (long)snmpInBadCommunityUses; } /** @@ -939,7 +939,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpInBadCommunityNames() { - return new Long(snmpInBadCommunityNames); + return (long)snmpInBadCommunityNames; } /** @@ -949,7 +949,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpInBadVersions() { - return new Long(snmpInBadVersions); + return (long)snmpInBadVersions; } /** @@ -959,7 +959,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpOutPkts() { - return new Long(snmpOutPkts); + return (long)snmpOutPkts; } /** @@ -969,7 +969,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpInPkts() { - return new Long(snmpInPkts); + return (long)snmpInPkts; } /** @@ -979,7 +979,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpInGetRequests() { - return new Long(snmpInGetRequests); + return (long)snmpInGetRequests; } /** @@ -989,7 +989,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpInGetNexts() { - return new Long(snmpInGetNexts); + return (long)snmpInGetNexts; } /** @@ -999,7 +999,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpInSetRequests() { - return new Long(snmpInSetRequests); + return (long)snmpInSetRequests; } /** @@ -1009,7 +1009,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpInTotalSetVars() { - return new Long(snmpInTotalSetVars); + return (long)snmpInTotalSetVars; } /** @@ -1019,7 +1019,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpInTotalReqVars() { - return new Long(snmpInTotalReqVars); + return (long)snmpInTotalReqVars; } /** @@ -1032,7 +1032,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpSilentDrops() { - return new Long(snmpSilentDrops); + return (long)snmpSilentDrops; } /** @@ -1045,7 +1045,7 @@ public class SnmpAdaptorServer extends CommunicatorServer */ @Override public Long getSnmpProxyDrops() { - return new Long(0); + return 0L; } diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/LdapPoolManager.java b/jdk/src/share/classes/com/sun/jndi/ldap/LdapPoolManager.java index 88b36cba315..a40b964c592 100644 --- a/jdk/src/share/classes/com/sun/jndi/ldap/LdapPoolManager.java +++ b/jdk/src/share/classes/com/sun/jndi/ldap/LdapPoolManager.java @@ -421,7 +421,7 @@ public final class LdapPoolManager { try { return Long.getLong(propName, defVal); } catch (SecurityException e) { - return new Long(defVal); + return defVal; } } }); diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/NamingEventNotifier.java b/jdk/src/share/classes/com/sun/jndi/ldap/NamingEventNotifier.java index d614aa943da..20794f8e502 100644 --- a/jdk/src/share/classes/com/sun/jndi/ldap/NamingEventNotifier.java +++ b/jdk/src/share/classes/com/sun/jndi/ldap/NamingEventNotifier.java @@ -221,7 +221,7 @@ final class NamingEventNotifier implements Runnable { return; NamingEvent e = new NamingEvent(eventSrc, NamingEvent.OBJECT_ADDED, - newBd, null, new Long(changeID)); + newBd, null, changeID); support.queueEvent(e, namingListeners); } @@ -233,7 +233,7 @@ final class NamingEventNotifier implements Runnable { return; NamingEvent e = new NamingEvent(eventSrc, NamingEvent.OBJECT_REMOVED, - null, oldBd, new Long(changeID)); + null, oldBd, changeID); support.queueEvent(e, namingListeners); } @@ -248,7 +248,7 @@ final class NamingEventNotifier implements Runnable { Binding oldBd = new Binding(newBd.getName(), null, newBd.isRelative()); NamingEvent e = new NamingEvent( - eventSrc, NamingEvent.OBJECT_CHANGED, newBd, oldBd, new Long(changeID)); + eventSrc, NamingEvent.OBJECT_CHANGED, newBd, oldBd, changeID); support.queueEvent(e, namingListeners); } @@ -273,7 +273,7 @@ final class NamingEventNotifier implements Runnable { } NamingEvent e = new NamingEvent( - eventSrc, NamingEvent.OBJECT_RENAMED, newBd, oldBd, new Long(changeID)); + eventSrc, NamingEvent.OBJECT_RENAMED, newBd, oldBd, changeID); support.queueEvent(e, namingListeners); } diff --git a/jdk/src/share/classes/com/sun/jndi/toolkit/dir/SearchFilter.java b/jdk/src/share/classes/com/sun/jndi/toolkit/dir/SearchFilter.java index bdbf578cc24..cf23c3dd2e4 100644 --- a/jdk/src/share/classes/com/sun/jndi/toolkit/dir/SearchFilter.java +++ b/jdk/src/share/classes/com/sun/jndi/toolkit/dir/SearchFilter.java @@ -379,7 +379,7 @@ public class SearchFilter implements AttrFilter { // used for substring comparisons (where proto has "*" wildcards private boolean substringMatch(String proto, String value) { // simple case 1: "*" means attribute presence is being tested - if(proto.equals(new Character(WILDCARD_TOKEN).toString())) { + if(proto.equals(Character.toString(WILDCARD_TOKEN))) { if(debug) {System.out.println("simple presence assertion");} return true; } diff --git a/jdk/src/share/classes/com/sun/media/sound/services/linux-i586/javax.sound.sampled.spi.MixerProvider b/jdk/src/share/classes/com/sun/media/sound/services/linux-i586/javax.sound.sampled.spi.MixerProvider deleted file mode 100644 index 56b8f12b0fb..00000000000 --- a/jdk/src/share/classes/com/sun/media/sound/services/linux-i586/javax.sound.sampled.spi.MixerProvider +++ /dev/null @@ -1,6 +0,0 @@ -# service provider file for Linux: with DirectAudioDeviceProvider -# last mixer is default mixer -com.sun.media.sound.PortMixerProvider -com.sun.media.sound.SimpleInputDeviceProvider -com.sun.media.sound.DirectAudioDeviceProvider -com.sun.media.sound.HeadspaceMixerProvider diff --git a/jdk/src/share/classes/com/sun/media/sound/services/windows-i586/javax.sound.sampled.spi.MixerProvider b/jdk/src/share/classes/com/sun/media/sound/services/windows-i586/javax.sound.sampled.spi.MixerProvider deleted file mode 100644 index 7e39afe741a..00000000000 --- a/jdk/src/share/classes/com/sun/media/sound/services/windows-i586/javax.sound.sampled.spi.MixerProvider +++ /dev/null @@ -1,6 +0,0 @@ -# service provider file for Windows: with DirectAudioDeviceProvider -# last mixer is default mixer -com.sun.media.sound.PortMixerProvider -com.sun.media.sound.SimpleInputDeviceProvider -com.sun.media.sound.DirectAudioDeviceProvider -com.sun.media.sound.HeadspaceMixerProvider diff --git a/jdk/src/share/classes/com/sun/media/sound/services/windows-ia64/javax.sound.sampled.spi.MixerProvider b/jdk/src/share/classes/com/sun/media/sound/services/windows-ia64/javax.sound.sampled.spi.MixerProvider deleted file mode 100644 index cf3bc8acaa6..00000000000 --- a/jdk/src/share/classes/com/sun/media/sound/services/windows-ia64/javax.sound.sampled.spi.MixerProvider +++ /dev/null @@ -1,6 +0,0 @@ -# service provider file for Windows IA64: with DirectAudioDeviceProvider -# last mixer is default mixer -com.sun.media.sound.PortMixerProvider -com.sun.media.sound.SimpleInputDeviceProvider -com.sun.media.sound.DirectAudioDeviceProvider -com.sun.media.sound.HeadspaceMixerProvider diff --git a/jdk/src/share/classes/com/sun/security/auth/SolarisNumericGroupPrincipal.java b/jdk/src/share/classes/com/sun/security/auth/SolarisNumericGroupPrincipal.java index 7924362f28b..04229eaab9c 100644 --- a/jdk/src/share/classes/com/sun/security/auth/SolarisNumericGroupPrincipal.java +++ b/jdk/src/share/classes/com/sun/security/auth/SolarisNumericGroupPrincipal.java @@ -110,7 +110,7 @@ public class SolarisNumericGroupPrincipal implements * */ public SolarisNumericGroupPrincipal(long name, boolean primaryGroup) { - this.name = (new Long(name)).toString(); + this.name = Long.toString(name); this.primaryGroup = primaryGroup; } @@ -137,7 +137,7 @@ public class SolarisNumericGroupPrincipal implements * SolarisNumericGroupPrincipal as a long. */ public long longValue() { - return ((new Long(name)).longValue()); + return Long.parseLong(name); } /** diff --git a/jdk/src/share/classes/com/sun/security/auth/SolarisNumericUserPrincipal.java b/jdk/src/share/classes/com/sun/security/auth/SolarisNumericUserPrincipal.java index 86f7ed67768..d7ba9c038d7 100644 --- a/jdk/src/share/classes/com/sun/security/auth/SolarisNumericUserPrincipal.java +++ b/jdk/src/share/classes/com/sun/security/auth/SolarisNumericUserPrincipal.java @@ -96,7 +96,7 @@ public class SolarisNumericUserPrincipal implements * represented as a long. */ public SolarisNumericUserPrincipal(long name) { - this.name = (new Long(name)).toString(); + this.name = Long.toString(name); } /** @@ -122,7 +122,7 @@ public class SolarisNumericUserPrincipal implements * SolarisNumericUserPrincipal as a long. */ public long longValue() { - return ((new Long(name)).longValue()); + return Long.parseLong(name); } /** diff --git a/jdk/src/share/classes/com/sun/security/auth/UnixNumericGroupPrincipal.java b/jdk/src/share/classes/com/sun/security/auth/UnixNumericGroupPrincipal.java index db5775ab329..63c9d28c34d 100644 --- a/jdk/src/share/classes/com/sun/security/auth/UnixNumericGroupPrincipal.java +++ b/jdk/src/share/classes/com/sun/security/auth/UnixNumericGroupPrincipal.java @@ -102,7 +102,7 @@ public class UnixNumericGroupPrincipal implements * */ public UnixNumericGroupPrincipal(long name, boolean primaryGroup) { - this.name = (new Long(name)).toString(); + this.name = Long.toString(name); this.primaryGroup = primaryGroup; } @@ -129,7 +129,7 @@ public class UnixNumericGroupPrincipal implements * UnixNumericGroupPrincipal as a long. */ public long longValue() { - return ((new Long(name)).longValue()); + return Long.parseLong(name); } /** diff --git a/jdk/src/share/classes/com/sun/security/auth/UnixNumericUserPrincipal.java b/jdk/src/share/classes/com/sun/security/auth/UnixNumericUserPrincipal.java index c6dfd7eaf1b..e2016efe77d 100644 --- a/jdk/src/share/classes/com/sun/security/auth/UnixNumericUserPrincipal.java +++ b/jdk/src/share/classes/com/sun/security/auth/UnixNumericUserPrincipal.java @@ -87,7 +87,7 @@ public class UnixNumericUserPrincipal implements * represented as a long. */ public UnixNumericUserPrincipal(long name) { - this.name = (new Long(name)).toString(); + this.name = Long.toString(name); } /** @@ -113,7 +113,7 @@ public class UnixNumericUserPrincipal implements * UnixNumericUserPrincipal as a long. */ public long longValue() { - return ((new Long(name)).longValue()); + return Long.parseLong(name); } /** diff --git a/jdk/src/share/classes/com/sun/security/sasl/digest/DigestMD5Base.java b/jdk/src/share/classes/com/sun/security/sasl/digest/DigestMD5Base.java index 37a261a6a2f..3469e708233 100644 --- a/jdk/src/share/classes/com/sun/security/sasl/digest/DigestMD5Base.java +++ b/jdk/src/share/classes/com/sun/security/sasl/digest/DigestMD5Base.java @@ -1460,7 +1460,7 @@ abstract class DigestMD5Base extends AbstractSaslImpl { if (logger.isLoggable(Level.INFO)) { logger.log(Level.INFO, "DIGEST39:Incorrect padding: {0}", - new Byte(msgWithPadding[msgWithPadding.length - 1])); + msgWithPadding[msgWithPadding.length - 1]); } return EMPTY_BYTE_ARRAY; } diff --git a/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Client.java b/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Client.java index e8d9a4cc866..aca462929f7 100644 --- a/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Client.java +++ b/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Client.java @@ -241,7 +241,7 @@ final class GssKrb5Client extends GssKrb5Base implements SaslClient { "KRB5CLNT05:Challenge [unwrapped]:", gssOutToken); } logger.log(Level.FINE, "KRB5CLNT06:Server protections: {0}", - new Byte(gssOutToken[0])); + gssOutToken[0]); } // Client selects preferred protection @@ -293,7 +293,7 @@ final class GssKrb5Client extends GssKrb5Base implements SaslClient { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "KRB5CLNT08:Selected protection: {0}; privacy: {1}; integrity: {2}", - new Object[]{new Byte(selectedQop), + new Object[]{selectedQop, Boolean.valueOf(privacy), Boolean.valueOf(integrity)}); } diff --git a/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Server.java b/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Server.java index 94ce39c0ad1..c15dfc9aae7 100644 --- a/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Server.java +++ b/jdk/src/share/classes/com/sun/security/sasl/gsskerb/GssKrb5Server.java @@ -221,7 +221,7 @@ final class GssKrb5Server extends GssKrb5Base implements SaslServer { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "KRB5SRV06:Supported protections: {0}; recv max buf size: {1}", - new Object[]{new Byte(allQop), + new Object[]{allQop, new Integer(recvMaxBufSize)}); } @@ -288,7 +288,7 @@ final class GssKrb5Server extends GssKrb5Base implements SaslServer { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "KRB5SRV10:Selected protection: {0}; privacy: {1}; integrity: {2}", - new Object[]{new Byte(selectedQop), + new Object[]{selectedQop, Boolean.valueOf(privacy), Boolean.valueOf(integrity)}); logger.log(Level.FINE, diff --git a/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java b/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java index eb122e3bbb4..1136d8db723 100644 --- a/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java +++ b/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java @@ -77,7 +77,7 @@ public abstract class AbstractSaslImpl { if (logger.isLoggable(Level.FINE)) { logger.logp(Level.FINE, myClassName, "constructor", - "SASLIMPL02:Preferred qop mask: {0}", new Byte(allQop)); + "SASLIMPL02:Preferred qop mask: {0}", allQop); if (qop.length > 0) { StringBuilder str = new StringBuilder(); diff --git a/jdk/src/share/classes/com/sun/tools/example/debug/tty/BreakpointSpec.java b/jdk/src/share/classes/com/sun/tools/example/debug/tty/BreakpointSpec.java index db0f25c1cb8..2bd04857e00 100644 --- a/jdk/src/share/classes/com/sun/tools/example/debug/tty/BreakpointSpec.java +++ b/jdk/src/share/classes/com/sun/tools/example/debug/tty/BreakpointSpec.java @@ -142,8 +142,8 @@ class BreakpointSpec extends EventRequestSpec { refSpec.toString())); } else if (e instanceof LineNotFoundException) { return (MessageOutput.format("No code at line", - new Object [] {new Long (lineNumber()), - refSpec.toString()})); + new Object [] {Long.valueOf(lineNumber()), + refSpec.toString()})); } else if (e instanceof InvalidTypeException) { return (MessageOutput.format("Breakpoints can be located only in classes.", refSpec.toString())); diff --git a/jdk/src/share/classes/com/sun/tools/example/debug/tty/Commands.java b/jdk/src/share/classes/com/sun/tools/example/debug/tty/Commands.java index 65a0a800e09..2ea7d487a02 100644 --- a/jdk/src/share/classes/com/sun/tools/example/debug/tty/Commands.java +++ b/jdk/src/share/classes/com/sun/tools/example/debug/tty/Commands.java @@ -935,7 +935,7 @@ class Commands { try { methodInfo = loc.sourceName() + MessageOutput.format("line number", - new Object [] {new Long(lineNumber)}); + new Object [] {Long.valueOf(lineNumber)}); } catch (AbsentInformationException e) { methodInfo = MessageOutput.format("unknown"); } @@ -946,7 +946,7 @@ class Commands { meth.declaringType().name(), meth.name(), methodInfo, - new Long(pc)}); + Long.valueOf(pc)}); } else { MessageOutput.println("stack frame dump", new Object [] {new Integer(frameNumber + 1), @@ -1015,7 +1015,7 @@ class Commands { new Object [] {loc.declaringType().name(), loc.method().name(), new Integer (loc.lineNumber()), - new Long (loc.codeIndex())}); + Long.valueOf(loc.codeIndex())}); } void listBreakpoints() { diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/model/JavaLazyReadObject.java b/jdk/src/share/classes/com/sun/tools/hat/internal/model/JavaLazyReadObject.java index 0727d519ca6..7b80466f488 100644 --- a/jdk/src/share/classes/com/sun/tools/hat/internal/model/JavaLazyReadObject.java +++ b/jdk/src/share/classes/com/sun/tools/hat/internal/model/JavaLazyReadObject.java @@ -102,7 +102,7 @@ public abstract class JavaLazyReadObject extends JavaHeapObject { if ((id & ~Snapshot.SMALL_ID_MASK) == 0) { return new Integer((int)id); } else { - return new Long(id); + return id; } } diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/model/Snapshot.java b/jdk/src/share/classes/com/sun/tools/hat/internal/model/Snapshot.java index 4d881fd0d72..51f922c8044 100644 --- a/jdk/src/share/classes/com/sun/tools/hat/internal/model/Snapshot.java +++ b/jdk/src/share/classes/com/sun/tools/hat/internal/model/Snapshot.java @@ -583,7 +583,7 @@ public class Snapshot { if (identifierSize == 4) { return new Integer((int)id); } else { - return new Long(id); + return id; } } diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/parser/HprofReader.java b/jdk/src/share/classes/com/sun/tools/hat/internal/parser/HprofReader.java index 33cdb3aa3e1..8a5afa88854 100644 --- a/jdk/src/share/classes/com/sun/tools/hat/internal/parser/HprofReader.java +++ b/jdk/src/share/classes/com/sun/tools/hat/internal/parser/HprofReader.java @@ -215,7 +215,7 @@ public class HprofReader extends Reader /* imports */ implements ArrayTypeCodes long id = readID(); byte[] chars = new byte[(int)length - identifierSize]; in.readFully(chars); - names.put(new Long(id), new String(chars)); + names.put(id, new String(chars)); break; } case HPROF_LOAD_CLASS: { @@ -223,7 +223,7 @@ public class HprofReader extends Reader /* imports */ implements ArrayTypeCodes long classID = readID(); int stackTraceSerialNo = in.readInt(); long classNameID = readID(); - Long classIdI = new Long(classID); + Long classIdI = classID; String nm = getNameFromID(classNameID).replace('/', '.'); classNameFromObjectID.put(classIdI, nm); if (classNameFromSerialNo != null) { @@ -303,7 +303,7 @@ public class HprofReader extends Reader /* imports */ implements ArrayTypeCodes warn("Weird stack frame line number: " + lineNumber); lineNumber = StackFrame.LINE_NUMBER_UNKNOWN; } - stackFrames.put(new Long(id), + stackFrames.put(id, new StackFrame(methodName, methodSig, className, sourceFile, lineNumber)); @@ -319,7 +319,7 @@ public class HprofReader extends Reader /* imports */ implements ArrayTypeCodes StackFrame[] frames = new StackFrame[in.readInt()]; for (int i = 0; i < frames.length; i++) { long fid = readID(); - frames[i] = stackFrames.get(new Long(fid)); + frames[i] = stackFrames.get(fid); if (frames[i] == null) { throw new IOException("Stack frame " + toHex(fid) + " not found"); } @@ -619,7 +619,7 @@ public class HprofReader extends Reader /* imports */ implements ArrayTypeCodes } private String getNameFromID(long id) throws IOException { - return getNameFromID(new Long(id)); + return getNameFromID(Long.valueOf(id)); } private String getNameFromID(Long id) throws IOException { @@ -703,7 +703,7 @@ public class HprofReader extends Reader /* imports */ implements ArrayTypeCodes String signature = "" + ((char) type); fields[i] = new JavaField(fieldName, signature); } - String name = classNameFromObjectID.get(new Long(id)); + String name = classNameFromObjectID.get(id); if (name == null) { warn("Class name not found for " + toHex(id)); name = "unknown-name@" + toHex(id); diff --git a/jdk/src/share/classes/com/sun/tools/hat/internal/server/RefsByTypeQuery.java b/jdk/src/share/classes/com/sun/tools/hat/internal/server/RefsByTypeQuery.java index ccffc6d5602..73755c2e523 100644 --- a/jdk/src/share/classes/com/sun/tools/hat/internal/server/RefsByTypeQuery.java +++ b/jdk/src/share/classes/com/sun/tools/hat/internal/server/RefsByTypeQuery.java @@ -63,9 +63,9 @@ public class RefsByTypeQuery extends QueryHandler { } Long count = referrersStat.get(cl); if (count == null) { - count = new Long(1); + count = 1L; } else { - count = new Long(count.longValue() + 1); + count = count + 1L; } referrersStat.put(cl, count); } @@ -75,9 +75,9 @@ public class RefsByTypeQuery extends QueryHandler { JavaClass cl = obj.getClazz(); Long count = refereesStat.get(cl); if (count == null) { - count = new Long(1); + count = 1L; } else { - count = new Long(count.longValue() + 1); + count = count + 1L; } refereesStat.put(cl, count); } diff --git a/jdk/src/share/classes/com/sun/tools/jdi/VirtualMachineImpl.java b/jdk/src/share/classes/com/sun/tools/jdi/VirtualMachineImpl.java index ca1c6e21408..c03ed4de31b 100644 --- a/jdk/src/share/classes/com/sun/tools/jdi/VirtualMachineImpl.java +++ b/jdk/src/share/classes/com/sun/tools/jdi/VirtualMachineImpl.java @@ -781,7 +781,7 @@ class VirtualMachineImpl extends MirrorImpl type.setSignature(signature); } - typesByID.put(new Long(id), type); + typesByID.put(id, type); typesBySignature.add(type); if ((vm.traceFlags & VirtualMachine.TRACE_REFTYPES) != 0) { @@ -809,7 +809,7 @@ class VirtualMachineImpl extends MirrorImpl if (comp == 0) { matches++; iter.remove(); - typesByID.remove(new Long(type.ref())); + typesByID.remove(type.ref()); if ((vm.traceFlags & VirtualMachine.TRACE_REFTYPES) != 0) { vm.printTrace("Uncaching ReferenceType, sig=" + signature + ", id=" + type.ref()); @@ -895,7 +895,7 @@ class VirtualMachineImpl extends MirrorImpl ReferenceTypeImpl retType = null; synchronized (this) { if (typesByID != null) { - retType = (ReferenceTypeImpl)typesByID.get(new Long(id)); + retType = (ReferenceTypeImpl)typesByID.get(id); } if (retType == null) { retType = addReferenceType(id, tag, signature); @@ -1247,7 +1247,7 @@ class VirtualMachineImpl extends MirrorImpl return null; } ObjectReferenceImpl object = null; - Long key = new Long(id); + Long key = id; /* * Attempt to retrieve an existing object object reference @@ -1313,7 +1313,7 @@ class VirtualMachineImpl extends MirrorImpl // Handle any queue elements that are not strongly reachable processQueue(); - SoftObjectReference ref = objectsByID.remove(new Long(object.ref())); + SoftObjectReference ref = objectsByID.remove(object.ref()); if (ref != null) { batchForDispose(ref); } else { diff --git a/jdk/src/share/classes/java/awt/AWTEvent.java b/jdk/src/share/classes/java/awt/AWTEvent.java index db51f2c1088..4a935f39848 100644 --- a/jdk/src/share/classes/java/awt/AWTEvent.java +++ b/jdk/src/share/classes/java/awt/AWTEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -388,6 +388,8 @@ public abstract class AWTEvent extends EventObject { /** * Returns the event type. + * + * @return the event's type id */ public int getID() { return id; @@ -446,6 +448,9 @@ public abstract class AWTEvent extends EventObject { /** * Returns whether this event has been consumed. + * + * @return {@code true} if this event has been consumed; + * otherwise {@code false} */ protected boolean isConsumed() { return consumed; diff --git a/jdk/src/share/classes/java/awt/AWTEventMulticaster.java b/jdk/src/share/classes/java/awt/AWTEventMulticaster.java index de51ab1c0b4..112dbb62ace 100644 --- a/jdk/src/share/classes/java/awt/AWTEventMulticaster.java +++ b/jdk/src/share/classes/java/awt/AWTEventMulticaster.java @@ -110,7 +110,15 @@ public class AWTEventMulticaster implements TextListener, InputMethodListener, HierarchyListener, HierarchyBoundsListener, MouseWheelListener { - protected final EventListener a, b; + /** + * A variable in the event chain (listener-a) + */ + protected final EventListener a; + + /** + * A variable in the event chain (listener-b) + */ + protected final EventListener b; /** * Creates an event multicaster instance which chains listener-a @@ -537,6 +545,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a component-listener-a * @param b component-listener-b + * @return the resulting listener */ public static ComponentListener add(ComponentListener a, ComponentListener b) { return (ComponentListener)addInternal(a, b); @@ -547,6 +556,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a container-listener-a * @param b container-listener-b + * @return the resulting listener */ public static ContainerListener add(ContainerListener a, ContainerListener b) { return (ContainerListener)addInternal(a, b); @@ -557,6 +567,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a focus-listener-a * @param b focus-listener-b + * @return the resulting listener */ public static FocusListener add(FocusListener a, FocusListener b) { return (FocusListener)addInternal(a, b); @@ -567,6 +578,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a key-listener-a * @param b key-listener-b + * @return the resulting listener */ public static KeyListener add(KeyListener a, KeyListener b) { return (KeyListener)addInternal(a, b); @@ -577,6 +589,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a mouse-listener-a * @param b mouse-listener-b + * @return the resulting listener */ public static MouseListener add(MouseListener a, MouseListener b) { return (MouseListener)addInternal(a, b); @@ -587,6 +600,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a mouse-motion-listener-a * @param b mouse-motion-listener-b + * @return the resulting listener */ public static MouseMotionListener add(MouseMotionListener a, MouseMotionListener b) { return (MouseMotionListener)addInternal(a, b); @@ -597,6 +611,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a window-listener-a * @param b window-listener-b + * @return the resulting listener */ public static WindowListener add(WindowListener a, WindowListener b) { return (WindowListener)addInternal(a, b); @@ -607,6 +622,7 @@ public class AWTEventMulticaster implements * and returns the resulting multicast listener. * @param a window-state-listener-a * @param b window-state-listener-b + * @return the resulting listener * @since 1.4 */ @SuppressWarnings("overloads") @@ -620,6 +636,7 @@ public class AWTEventMulticaster implements * and returns the resulting multicast listener. * @param a window-focus-listener-a * @param b window-focus-listener-b + * @return the resulting listener * @since 1.4 */ public static WindowFocusListener add(WindowFocusListener a, @@ -632,6 +649,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a action-listener-a * @param b action-listener-b + * @return the resulting listener */ @SuppressWarnings("overloads") public static ActionListener add(ActionListener a, ActionListener b) { @@ -643,6 +661,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a item-listener-a * @param b item-listener-b + * @return the resulting listener */ @SuppressWarnings("overloads") public static ItemListener add(ItemListener a, ItemListener b) { @@ -654,11 +673,21 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a adjustment-listener-a * @param b adjustment-listener-b + * @return the resulting listener */ @SuppressWarnings("overloads") public static AdjustmentListener add(AdjustmentListener a, AdjustmentListener b) { return (AdjustmentListener)addInternal(a, b); } + + /** + * Adds text-listener-a with text-listener-b and + * returns the resulting multicast listener. + * + * @param a text-listener-a + * @param b text-listener-b + * @return the resulting listener + */ @SuppressWarnings("overloads") public static TextListener add(TextListener a, TextListener b) { return (TextListener)addInternal(a, b); @@ -669,6 +698,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a input-method-listener-a * @param b input-method-listener-b + * @return the resulting listener */ public static InputMethodListener add(InputMethodListener a, InputMethodListener b) { return (InputMethodListener)addInternal(a, b); @@ -679,6 +709,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a hierarchy-listener-a * @param b hierarchy-listener-b + * @return the resulting listener * @since 1.3 */ @SuppressWarnings("overloads") @@ -691,6 +722,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a hierarchy-bounds-listener-a * @param b hierarchy-bounds-listener-b + * @return the resulting listener * @since 1.3 */ public static HierarchyBoundsListener add(HierarchyBoundsListener a, HierarchyBoundsListener b) { @@ -702,6 +734,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param a mouse-wheel-listener-a * @param b mouse-wheel-listener-b + * @return the resulting listener * @since 1.4 */ @SuppressWarnings("overloads") @@ -715,6 +748,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param l component-listener-l * @param oldl the component-listener being removed + * @return the resulting listener */ public static ComponentListener remove(ComponentListener l, ComponentListener oldl) { return (ComponentListener) removeInternal(l, oldl); @@ -725,6 +759,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param l container-listener-l * @param oldl the container-listener being removed + * @return the resulting listener */ public static ContainerListener remove(ContainerListener l, ContainerListener oldl) { return (ContainerListener) removeInternal(l, oldl); @@ -735,6 +770,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param l focus-listener-l * @param oldl the focus-listener being removed + * @return the resulting listener */ public static FocusListener remove(FocusListener l, FocusListener oldl) { return (FocusListener) removeInternal(l, oldl); @@ -745,6 +781,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param l key-listener-l * @param oldl the key-listener being removed + * @return the resulting listener */ public static KeyListener remove(KeyListener l, KeyListener oldl) { return (KeyListener) removeInternal(l, oldl); @@ -755,6 +792,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param l mouse-listener-l * @param oldl the mouse-listener being removed + * @return the resulting listener */ public static MouseListener remove(MouseListener l, MouseListener oldl) { return (MouseListener) removeInternal(l, oldl); @@ -765,6 +803,7 @@ public class AWTEventMulticaster implements * and returns the resulting multicast listener. * @param l mouse-motion-listener-l * @param oldl the mouse-motion-listener being removed + * @return the resulting listener */ public static MouseMotionListener remove(MouseMotionListener l, MouseMotionListener oldl) { return (MouseMotionListener) removeInternal(l, oldl); @@ -775,6 +814,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param l window-listener-l * @param oldl the window-listener being removed + * @return the resulting listener */ public static WindowListener remove(WindowListener l, WindowListener oldl) { return (WindowListener) removeInternal(l, oldl); @@ -785,6 +825,7 @@ public class AWTEventMulticaster implements * and returns the resulting multicast listener. * @param l window-state-listener-l * @param oldl the window-state-listener being removed + * @return the resulting listener * @since 1.4 */ @SuppressWarnings("overloads") @@ -798,6 +839,7 @@ public class AWTEventMulticaster implements * and returns the resulting multicast listener. * @param l window-focus-listener-l * @param oldl the window-focus-listener being removed + * @return the resulting listener * @since 1.4 */ public static WindowFocusListener remove(WindowFocusListener l, @@ -810,6 +852,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param l action-listener-l * @param oldl the action-listener being removed + * @return the resulting listener */ @SuppressWarnings("overloads") public static ActionListener remove(ActionListener l, ActionListener oldl) { @@ -821,6 +864,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param l item-listener-l * @param oldl the item-listener being removed + * @return the resulting listener */ @SuppressWarnings("overloads") public static ItemListener remove(ItemListener l, ItemListener oldl) { @@ -832,11 +876,21 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param l adjustment-listener-l * @param oldl the adjustment-listener being removed + * @return the resulting listener */ @SuppressWarnings("overloads") public static AdjustmentListener remove(AdjustmentListener l, AdjustmentListener oldl) { return (AdjustmentListener) removeInternal(l, oldl); } + + /** + * Removes the old text-listener from text-listener-l and + * returns the resulting multicast listener. + * + * @param l text-listener-l + * @param oldl the text-listener being removed + * @return the resulting listener + */ @SuppressWarnings("overloads") public static TextListener remove(TextListener l, TextListener oldl) { return (TextListener) removeInternal(l, oldl); @@ -847,6 +901,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param l input-method-listener-l * @param oldl the input-method-listener being removed + * @return the resulting listener */ public static InputMethodListener remove(InputMethodListener l, InputMethodListener oldl) { return (InputMethodListener) removeInternal(l, oldl); @@ -857,6 +912,7 @@ public class AWTEventMulticaster implements * returns the resulting multicast listener. * @param l hierarchy-listener-l * @param oldl the hierarchy-listener being removed + * @return the resulting listener * @since 1.3 */ @SuppressWarnings("overloads") @@ -870,6 +926,7 @@ public class AWTEventMulticaster implements * listener. * @param l hierarchy-bounds-listener-l * @param oldl the hierarchy-bounds-listener being removed + * @return the resulting listener * @since 1.3 */ public static HierarchyBoundsListener remove(HierarchyBoundsListener l, HierarchyBoundsListener oldl) { @@ -881,6 +938,7 @@ public class AWTEventMulticaster implements * and returns the resulting multicast listener. * @param l mouse-wheel-listener-l * @param oldl the mouse-wheel-listener being removed + * @return the resulting listener * @since 1.4 */ @SuppressWarnings("overloads") @@ -898,6 +956,7 @@ public class AWTEventMulticaster implements * a new AWTEventMulticaster instance which chains a with b. * @param a event listener-a * @param b event listener-b + * @return the resulting listener */ protected static EventListener addInternal(EventListener a, EventListener b) { if (a == null) return b; @@ -915,6 +974,7 @@ public class AWTEventMulticaster implements * Else, returns listener l. * @param l the listener being removed from * @param oldl the listener being removed + * @return the resulting listener */ protected static EventListener removeInternal(EventListener l, EventListener oldl) { if (l == oldl || l == null) { @@ -927,9 +987,14 @@ public class AWTEventMulticaster implements } - /* Serialization support. - */ - + /** + * Serialization support. Saves all Serializable listeners + * to a serialization stream. + * + * @param s the stream to save to + * @param k a prefix stream to put before each serializable listener + * @throws IOException if serialization fails + */ protected void saveInternal(ObjectOutputStream s, String k) throws IOException { if (a instanceof AWTEventMulticaster) { ((AWTEventMulticaster)a).saveInternal(s, k); @@ -948,6 +1013,14 @@ public class AWTEventMulticaster implements } } + /** + * Saves a Serializable listener chain to a serialization stream. + * + * @param s the stream to save to + * @param k a prefix stream to put before each serializable listener + * @param l the listener chain to save + * @throws IOException if serialization fails + */ protected static void save(ObjectOutputStream s, String k, EventListener l) throws IOException { if (l == null) { return; diff --git a/jdk/src/share/classes/java/awt/AWTKeyStroke.java b/jdk/src/share/classes/java/awt/AWTKeyStroke.java index 4be729b8c89..681113a07db 100644 --- a/jdk/src/share/classes/java/awt/AWTKeyStroke.java +++ b/jdk/src/share/classes/java/awt/AWTKeyStroke.java @@ -802,6 +802,7 @@ public class AWTKeyStroke implements Serializable { * AWTKeyStroke) which is equal to this instance. * * @return a cached instance which is equal to this instance + * @throws java.io.ObjectStreamException if a serialization problem occurs */ protected Object readResolve() throws java.io.ObjectStreamException { synchronized (AWTKeyStroke.class) { diff --git a/jdk/src/share/classes/java/awt/AlphaComposite.java b/jdk/src/share/classes/java/awt/AlphaComposite.java index f08ea2b47bf..542d2884a01 100644 --- a/jdk/src/share/classes/java/awt/AlphaComposite.java +++ b/jdk/src/share/classes/java/awt/AlphaComposite.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -621,7 +621,9 @@ public final class AlphaComposite implements Composite { /** * Creates an AlphaComposite object with the specified rule. + * * @param rule the compositing rule + * @return the {@code AlphaComposite} object created * @throws IllegalArgumentException if rule is not one of * the following: {@link #CLEAR}, {@link #SRC}, {@link #DST}, * {@link #SRC_OVER}, {@link #DST_OVER}, {@link #SRC_IN}, @@ -664,10 +666,12 @@ public final class AlphaComposite implements Composite { * the constant alpha to multiply with the alpha of the source. * The source is multiplied with the specified alpha before being composited * with the destination. + * * @param rule the compositing rule * @param alpha the constant alpha to be multiplied with the alpha of * the source. alpha must be a floating point number in the * inclusive range [0.0, 1.0]. + * @return the {@code AlphaComposite} object created * @throws IllegalArgumentException if * alpha is less than 0.0 or greater than 1.0, or if * rule is not one of diff --git a/jdk/src/share/classes/java/awt/BorderLayout.java b/jdk/src/share/classes/java/awt/BorderLayout.java index b2f7e25fe19..fd891bc371b 100644 --- a/jdk/src/share/classes/java/awt/BorderLayout.java +++ b/jdk/src/share/classes/java/awt/BorderLayout.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -367,6 +367,8 @@ public class BorderLayout implements LayoutManager2, /** * Returns the horizontal gap between components. + * + * @return the horizontal gap between components * @since 1.1 */ public int getHgap() { @@ -375,6 +377,7 @@ public class BorderLayout implements LayoutManager2, /** * Sets the horizontal gap between components. + * * @param hgap the horizontal gap between components * @since 1.1 */ @@ -384,6 +387,8 @@ public class BorderLayout implements LayoutManager2, /** * Returns the vertical gap between components. + * + * @return the vertical gap between components * @since 1.1 */ public int getVgap() { @@ -392,6 +397,7 @@ public class BorderLayout implements LayoutManager2, /** * Sets the vertical gap between components. + * * @param vgap the vertical gap between components * @since 1.1 */ diff --git a/jdk/src/share/classes/java/awt/Button.java b/jdk/src/share/classes/java/awt/Button.java index 08e569d446a..cc01947a9f1 100644 --- a/jdk/src/share/classes/java/awt/Button.java +++ b/jdk/src/share/classes/java/awt/Button.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -238,6 +238,8 @@ public class Button extends Component implements Accessible { * Returns the command name of the action event fired by this button. * If the command name is null (default) then this method * returns the label of the button. + * + * @return the action command name (or label) for this button */ public String getActionCommand() { return (actionCommand == null? label : actionCommand); diff --git a/jdk/src/share/classes/java/awt/Checkbox.java b/jdk/src/share/classes/java/awt/Checkbox.java index 8e8b5dd226a..021b2fcebaa 100644 --- a/jdk/src/share/classes/java/awt/Checkbox.java +++ b/jdk/src/share/classes/java/awt/Checkbox.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -713,6 +713,9 @@ public class Checkbox extends Component implements ItemSelectable, Accessible { */ private static final long serialVersionUID = 7881579233144754107L; + /** + * Constructor for {@code AccessibleAWTCheckbox} + */ public AccessibleAWTCheckbox() { super(); Checkbox.this.addItemListener(this); diff --git a/jdk/src/share/classes/java/awt/CheckboxGroup.java b/jdk/src/share/classes/java/awt/CheckboxGroup.java index a34c337b712..15e91c4d2a0 100644 --- a/jdk/src/share/classes/java/awt/CheckboxGroup.java +++ b/jdk/src/share/classes/java/awt/CheckboxGroup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -91,6 +91,10 @@ public class CheckboxGroup implements java.io.Serializable { } /** + * Returns the current choice from this check box group + * or {@code null} if none of checkboxes are selected. + * + * @return the selected checkbox * @deprecated As of JDK version 1.1, * replaced by getSelectedCheckbox(). */ @@ -120,6 +124,11 @@ public class CheckboxGroup implements java.io.Serializable { } /** + * Sets the currently selected check box in this group + * to be the specified check box and unsets all others. + * + * @param box the {@code Checkbox} to set as the + * current selection. * @deprecated As of JDK version 1.1, * replaced by setSelectedCheckbox(Checkbox). */ diff --git a/jdk/src/share/classes/java/awt/Choice.java b/jdk/src/share/classes/java/awt/Choice.java index 1d79dc71831..a6f20718321 100644 --- a/jdk/src/share/classes/java/awt/Choice.java +++ b/jdk/src/share/classes/java/awt/Choice.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -156,6 +156,7 @@ public class Choice extends Component implements ItemSelectable, Accessible { /** * Returns the number of items in this Choice menu. + * * @return the number of items in this Choice menu * @see #getItem * @since 1.1 @@ -165,6 +166,9 @@ public class Choice extends Component implements ItemSelectable, Accessible { } /** + * Returns the number of items in this {@code Choice} menu. + * + * @return the number of items in this {@code Choice} menu * @deprecated As of JDK version 1.1, * replaced by getItemCount(). */ @@ -176,8 +180,10 @@ public class Choice extends Component implements ItemSelectable, Accessible { /** * Gets the string at the specified index in this * Choice menu. - * @param index the index at which to begin - * @see #getItemCount + * + * @param index the index at which to begin + * @return the item at the specified index + * @see #getItemCount */ public String getItem(int index) { return getItemImpl(index); @@ -759,6 +765,9 @@ public class Choice extends Component implements ItemSelectable, Accessible { */ private static final long serialVersionUID = 7175603582428509322L; + /** + * Constructor for {@code AccessibleAWTChoice} + */ public AccessibleAWTChoice() { super(); } diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java index e5659d7cce3..24cc58733e7 100644 --- a/jdk/src/share/classes/java/awt/Component.java +++ b/jdk/src/share/classes/java/awt/Component.java @@ -1075,6 +1075,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * @deprecated As of JDK version 1.1, * programs should not directly manipulate peers; * replaced by boolean isDisplayable(). + * @return the peer for this component */ @Deprecated public ComponentPeer getPeer() { @@ -1132,6 +1133,8 @@ public abstract class Component implements ImageObserver, MenuContainer, /** * Gets the DropTarget associated with this * Component. + * + * @return the drop target */ public synchronized DropTarget getDropTarget() { return dropTarget; } @@ -1498,6 +1501,11 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * Enables or disables this component. + * + * @param b {@code true} to enable this component; + * otherwise {@code false} + * * @deprecated As of JDK version 1.1, * replaced by setEnabled(boolean). */ @@ -1656,6 +1664,11 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * Makes this component visible or invisible. + * + * @param b {@code true} to make this component visible; + * otherwise {@code false} + * * @deprecated As of JDK version 1.1, * replaced by setVisible(boolean). */ @@ -2068,6 +2081,9 @@ public abstract class Component implements ImageObserver, MenuContainer, /** + * Returns the location of this component's top left corner. + * + * @return the location of this component's top left corner * @deprecated As of JDK version 1.1, * replaced by getLocation(). */ @@ -2102,6 +2118,13 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * Moves this component to a new location. + * + * @param x the x-coordinate of the new location's + * top-left corner in the parent's coordinate space + * @param y the y-coordinate of the new location's + * top-left corner in the parent's coordinate space + * * @deprecated As of JDK version 1.1, * replaced by setLocation(int, int). */ @@ -2150,6 +2173,11 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * Returns the size of this component in the form of a + * {@code Dimension} object. + * + * @return the {@code Dimension} object that indicates the + * size of this component * @deprecated As of JDK version 1.1, * replaced by getSize(). */ @@ -2177,6 +2205,10 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * Resizes this component. + * + * @param width the new width of the component + * @param height the new height of the component * @deprecated As of JDK version 1.1, * replaced by setSize(int, int). */ @@ -2208,6 +2240,10 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * Resizes this component so that it has width {@code d.width} + * and height {@code d.height}. + * + * @param d the new size of this component * @deprecated As of JDK version 1.1, * replaced by setSize(Dimension). */ @@ -2231,6 +2267,9 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * Returns the bounding rectangle of this component. + * + * @return the bounding rectangle for this component * @deprecated As of JDK version 1.1, * replaced by getBounds(). */ @@ -2265,6 +2304,13 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * Reshapes the bounding rectangle for this component. + * + * @param x the x coordinate of the upper left corner of the rectangle + * @param y the y coordinate of the upper left corner of the rectangle + * @param width the width of the rectangle + * @param height the height of the rectangle + * * @deprecated As of JDK version 1.1, * replaced by setBounds(int, int, int, int). */ @@ -2631,6 +2677,9 @@ public abstract class Component implements ImageObserver, MenuContainer, /** + * Returns the component's preferred size. + * + * @return the component's preferred size * @deprecated As of JDK version 1.1, * replaced by getPreferredSize(). */ @@ -2701,6 +2750,9 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * Returns the minimum size of this component. + * + * @return the minimum size of this component * @deprecated As of JDK version 1.1, * replaced by getMinimumSize(). */ @@ -2781,6 +2833,8 @@ public abstract class Component implements ImageObserver, MenuContainer, * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. + * + * @return the horizontal alignment of this component */ public float getAlignmentX() { return CENTER_ALIGNMENT; @@ -2792,6 +2846,8 @@ public abstract class Component implements ImageObserver, MenuContainer, * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. + * + * @return the vertical alignment of this component */ public float getAlignmentY() { return CENTER_ALIGNMENT; @@ -3157,8 +3213,10 @@ public abstract class Component implements ImageObserver, MenuContainer, * not have a cursor set, the cursor of its parent is returned. * If no cursor is set in the entire hierarchy, * Cursor.DEFAULT_CURSOR is returned. + * + * @return the cursor for this component * @see #setCursor - * @since 1.1 + * @since 1.1 */ public Cursor getCursor() { return getCursor_NoClientCode(); @@ -3411,7 +3469,7 @@ public abstract class Component implements ImageObserver, MenuContainer, (width > 0) && (height > 0)) { PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE, new Rectangle(x, y, width, height)); - Toolkit.getEventQueue().postEvent(e); + SunToolkit.postEvent(SunToolkit.targetToAppContext(this), e); } } } @@ -3942,6 +4000,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * a lost state. */ protected boolean validatedContents; // = false + /** * Size of the back buffers. (Note: these fields were added in 6.0 * but kept package-private to avoid exposing them in the spec. @@ -3949,7 +4008,15 @@ public abstract class Component implements ImageObserver, MenuContainer, * protected when they were introduced in 1.4, but now we just have * to live with that decision.) */ + + /** + * The width of the back buffers + */ int width; + + /** + * The height of the back buffers + */ int height; /** @@ -4304,6 +4371,8 @@ public abstract class Component implements ImageObserver, MenuContainer, /** * Creates the back buffers + * + * @param numBuffers the number of buffers to create */ protected void createBackBuffers(int numBuffers) { if (numBuffers == 0) { @@ -4593,6 +4662,9 @@ public abstract class Component implements ImageObserver, MenuContainer, * better performance is desired, or if page-flipping is used as the * buffer strategy. * + * @param ignoreRepaint {@code true} if the paint messages from the OS + * should be ignored; otherwise {@code false} + * * @since 1.4 * @see #getIgnoreRepaint * @see Canvas#createBufferStrategy @@ -4619,8 +4691,11 @@ public abstract class Component implements ImageObserver, MenuContainer, * Checks whether this component "contains" the specified point, * where x and y are defined to be * relative to the coordinate system of this component. + * * @param x the x coordinate of the point * @param y the y coordinate of the point + * @return {@code true} if the point is within the component; + * otherwise {@code false} * @see #getComponentAt(int, int) * @since 1.1 */ @@ -4629,6 +4704,12 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * Checks whether the point is inside of this component. + * + * @param x the x coordinate of the point + * @param y the y coordinate of the point + * @return {@code true} if the point is within the component; + * otherwise {@code false} * @deprecated As of JDK version 1.1, * replaced by contains(int, int). */ @@ -4641,7 +4722,10 @@ public abstract class Component implements ImageObserver, MenuContainer, * Checks whether this component "contains" the specified point, * where the point's x and y coordinates are defined * to be relative to the coordinate system of this component. + * * @param p the point + * @return {@code true} if the point is within the component; + * otherwise {@code false} * @throws NullPointerException if {@code p} is {@code null} * @see #getComponentAt(Point) * @since 1.1 @@ -4676,6 +4760,13 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * Returns the component occupying the position specified (this component, + * or immediate child component, or null if neither + * of the first two occupies the location). + * + * @param x the x coordinate to search for components at + * @param y the y coordinate to search for components at + * @return the component at the specified location or {@code null} * @deprecated As of JDK version 1.1, * replaced by getComponentAt(int, int). */ @@ -4687,15 +4778,17 @@ public abstract class Component implements ImageObserver, MenuContainer, /** * Returns the component or subcomponent that contains the * specified point. - * @param p the point - * @see java.awt.Component#contains - * @since 1.1 + * @param p the point + * @return the component at the specified location or {@code null} + * @see java.awt.Component#contains + * @since 1.1 */ public Component getComponentAt(Point p) { return getComponentAt(p.x, p.y); } /** + * @param e the event to deliver * @deprecated As of JDK version 1.1, * replaced by dispatchEvent(AWTEvent e). */ @@ -6746,6 +6839,8 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * @param evt the event to handle + * @return {@code true} if the event was handled, {@code false} otherwise * @deprecated As of JDK version 1.1 * replaced by processEvent(AWTEvent). */ @@ -6789,6 +6884,10 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * @param evt the event to handle + * @param x the x coordinate + * @param y the y coordinate + * @return {@code false} * @deprecated As of JDK version 1.1, * replaced by processMouseEvent(MouseEvent). */ @@ -6798,6 +6897,10 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * @param evt the event to handle + * @param x the x coordinate + * @param y the y coordinate + * @return {@code false} * @deprecated As of JDK version 1.1, * replaced by processMouseMotionEvent(MouseEvent). */ @@ -6807,6 +6910,10 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * @param evt the event to handle + * @param x the x coordinate + * @param y the y coordinate + * @return {@code false} * @deprecated As of JDK version 1.1, * replaced by processMouseEvent(MouseEvent). */ @@ -6816,6 +6923,10 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * @param evt the event to handle + * @param x the x coordinate + * @param y the y coordinate + * @return {@code false} * @deprecated As of JDK version 1.1, * replaced by processMouseMotionEvent(MouseEvent). */ @@ -6825,6 +6936,10 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * @param evt the event to handle + * @param x the x coordinate + * @param y the y coordinate + * @return {@code false} * @deprecated As of JDK version 1.1, * replaced by processMouseEvent(MouseEvent). */ @@ -6834,6 +6949,10 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * @param evt the event to handle + * @param x the x coordinate + * @param y the y coordinate + * @return {@code false} * @deprecated As of JDK version 1.1, * replaced by processMouseEvent(MouseEvent). */ @@ -6843,6 +6962,9 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * @param evt the event to handle + * @param key the key pressed + * @return {@code false} * @deprecated As of JDK version 1.1, * replaced by processKeyEvent(KeyEvent). */ @@ -6852,6 +6974,9 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * @param evt the event to handle + * @param key the key pressed + * @return {@code false} * @deprecated As of JDK version 1.1, * replaced by processKeyEvent(KeyEvent). */ @@ -6861,6 +6986,9 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * @param evt the event to handle + * @param what the object acted on + * @return {@code false} * @deprecated As of JDK version 1.1, * should register this component as ActionListener on component * which fires action events. @@ -7070,6 +7198,9 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * @param evt the event to handle + * @param what the object focused + * @return {@code false} * @deprecated As of JDK version 1.1, * replaced by processFocusEvent(FocusEvent). */ @@ -7079,6 +7210,9 @@ public abstract class Component implements ImageObserver, MenuContainer, } /** + * @param evt the event to handle + * @param what the object focused + * @return {@code false} * @deprecated As of JDK version 1.1, * replaced by processFocusEvent(FocusEvent). */ @@ -8390,6 +8524,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * Returns an array of all the listeners which have been associated * with the named property. * + * @param propertyName the property name * @return all of the PropertyChangeListeners associated with * the named property; if no such listeners have been added or * if propertyName is null, an empty @@ -8400,8 +8535,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * @see #getPropertyChangeListeners * @since 1.4 */ - public PropertyChangeListener[] getPropertyChangeListeners( - String propertyName) { + public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) { synchronized (getObjectLock()) { if (changeSupport == null) { return new PropertyChangeListener[0]; @@ -8506,7 +8640,7 @@ public abstract class Component implements ImageObserver, MenuContainer, if (changeSupport == null || oldValue == newValue) { return; } - firePropertyChange(propertyName, new Character(oldValue), new Character(newValue)); + firePropertyChange(propertyName, Character.valueOf(oldValue), Character.valueOf(newValue)); } /** @@ -8879,6 +9013,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * This method changes layout-related information, and therefore, * invalidates the component hierarchy. * + * @param o the orientation to be set * * @see ComponentOrientation * @see #invalidate @@ -8906,6 +9041,7 @@ public abstract class Component implements ImageObserver, MenuContainer, * subclasses that wish to respect orientation should call this method to * get the component's orientation before performing layout or drawing. * + * @return the orientation to order the elements or text * @see ComponentOrientation * * @author Laura Werner, IBM @@ -9063,7 +9199,16 @@ public abstract class Component implements ImageObserver, MenuContainer, */ private volatile transient int propertyListenersCount = 0; + /** + * A component listener to track show/hide/resize events + * and convert them to PropertyChange events. + */ protected ComponentListener accessibleAWTComponentHandler = null; + + /** + * A listener to track focus events + * and convert them to PropertyChange events. + */ protected FocusListener accessibleAWTFocusHandler = null; /** diff --git a/jdk/src/share/classes/java/awt/ComponentOrientation.java b/jdk/src/share/classes/java/awt/ComponentOrientation.java index 8655aafa322..226b004a273 100644 --- a/jdk/src/share/classes/java/awt/ComponentOrientation.java +++ b/jdk/src/share/classes/java/awt/ComponentOrientation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -126,6 +126,8 @@ public final class ComponentOrientation implements java.io.Serializable * Are lines horizontal? * This will return true for horizontal, left-to-right writing * systems such as Roman. + * + * @return {@code true} if this orientation has horizontal lines */ public boolean isHorizontal() { return (orientation & HORIZ_BIT) != 0; @@ -136,6 +138,8 @@ public final class ComponentOrientation implements java.io.Serializable * Vertical Lines: Do lines run left-to-right?
* This will return true for horizontal, left-to-right writing * systems such as Roman. + * + * @return {@code true} if this orientation is left-to-right */ public boolean isLeftToRight() { return (orientation & LTR_BIT) != 0; @@ -143,7 +147,9 @@ public final class ComponentOrientation implements java.io.Serializable /** * Returns the orientation that is appropriate for the given locale. + * * @param locale the specified locale + * @return the orientation for the locale */ public static ComponentOrientation getOrientation(Locale locale) { // A more flexible implementation would consult a ResourceBundle @@ -171,6 +177,8 @@ public final class ComponentOrientation implements java.io.Serializable *
  • Return the default locale's orientation. * * + * @param bdl the bundle to use + * @return the orientation * @deprecated As of J2SE 1.4, use {@link #getOrientation(java.util.Locale)}. */ @Deprecated diff --git a/jdk/src/share/classes/java/awt/Container.java b/jdk/src/share/classes/java/awt/Container.java index a352bab43ef..95997f4f900 100644 --- a/jdk/src/share/classes/java/awt/Container.java +++ b/jdk/src/share/classes/java/awt/Container.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -310,6 +310,9 @@ public class Container extends Component { } /** + * Returns the number of components in this container. + * + * @return the number of components in this container * @deprecated As of JDK version 1.1, * replaced by getComponentCount(). */ @@ -391,8 +394,11 @@ public class Container extends Component { } /** + * Returns the insets for this container. + * * @deprecated As of JDK version 1.1, * replaced by getInsets(). + * @return the insets for this container */ @Deprecated public Insets insets() { @@ -438,6 +444,9 @@ public class Container extends Component { * displayed, the hierarchy must be validated thereafter in order to * display the added component. * + * @param name the name of the component to be added + * @param comp the component to be added + * @return the component added * @exception NullPointerException if {@code comp} is {@code null} * @see #add(Component, Object) * @see #invalidate @@ -1471,8 +1480,10 @@ public class Container extends Component { /** * Gets the layout manager for this container. + * * @see #doLayout * @see #setLayout + * @return the current layout manager for this container */ public LayoutManager getLayout() { return layoutMgr; @@ -3854,6 +3865,10 @@ public class Container extends Component { */ private volatile transient int propertyListenersCount = 0; + /** + * The handler to fire {@code PropertyChange} + * when children are added or removed + */ protected ContainerListener accessibleContainerHandler = null; /** diff --git a/jdk/src/share/classes/java/awt/Cursor.java b/jdk/src/share/classes/java/awt/Cursor.java index 794c7c9b242..1468e162134 100644 --- a/jdk/src/share/classes/java/awt/Cursor.java +++ b/jdk/src/share/classes/java/awt/Cursor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -294,6 +294,7 @@ public class Cursor implements java.io.Serializable { * @return the system specific custom cursor named * @exception HeadlessException if * GraphicsEnvironment.isHeadless returns true + * @exception AWTException in case of erroneous retrieving of the cursor */ static public Cursor getSystemCustomCursor(final String name) throws AWTException, HeadlessException { @@ -378,6 +379,8 @@ public class Cursor implements java.io.Serializable { /** * Return the system default cursor. + * + * @return the default cursor */ static public Cursor getDefaultCursor() { return getPredefinedCursor(Cursor.DEFAULT_CURSOR); @@ -416,6 +419,8 @@ public class Cursor implements java.io.Serializable { /** * Returns the type for this cursor. + * + * @return the cursor type */ public int getType() { return type; diff --git a/jdk/src/share/classes/java/awt/DisplayMode.java b/jdk/src/share/classes/java/awt/DisplayMode.java index 71a5d7e8122..41564300615 100644 --- a/jdk/src/share/classes/java/awt/DisplayMode.java +++ b/jdk/src/share/classes/java/awt/DisplayMode.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -125,6 +125,8 @@ public final class DisplayMode { /** * Returns whether the two display modes are equal. + * + * @param dm the display mode to compare to * @return whether the two display modes are equal */ public boolean equals(DisplayMode dm) { diff --git a/jdk/src/share/classes/java/awt/EventDispatchThread.java b/jdk/src/share/classes/java/awt/EventDispatchThread.java index 51344658c7e..962039c8374 100644 --- a/jdk/src/share/classes/java/awt/EventDispatchThread.java +++ b/jdk/src/share/classes/java/awt/EventDispatchThread.java @@ -33,7 +33,6 @@ import java.util.ArrayList; import sun.util.logging.PlatformLogger; import sun.awt.dnd.SunDragSourceContextPeer; -import sun.awt.EventQueueDelegate; /** * EventDispatchThread is a package-private AWT class which takes @@ -158,17 +157,11 @@ class EventDispatchThread extends Thread { boolean eventOK = false; try { EventQueue eq = null; - EventQueueDelegate.Delegate delegate = null; do { // EventQueue may change during the dispatching eq = getEventQueue(); - delegate = EventQueueDelegate.getDelegate(); - if (delegate != null && id == ANY_EVENT) { - event = delegate.getNextEvent(eq); - } else { - event = (id == ANY_EVENT) ? eq.getNextEvent() : eq.getNextEvent(id); - } + event = (id == ANY_EVENT) ? eq.getNextEvent() : eq.getNextEvent(id); eventOK = true; synchronized (eventFilters) { @@ -194,14 +187,7 @@ class EventDispatchThread extends Thread { eventLog.finest("Dispatching: " + event); } - Object handle = null; - if (delegate != null) { - handle = delegate.beforeDispatch(event); - } eq.dispatchEvent(event); - if (delegate != null) { - delegate.afterDispatch(event, handle); - } } catch (ThreadDeath death) { doDispatch = false; diff --git a/jdk/src/share/classes/java/awt/EventQueue.java b/jdk/src/share/classes/java/awt/EventQueue.java index 4164641392e..a89311352ab 100644 --- a/jdk/src/share/classes/java/awt/EventQueue.java +++ b/jdk/src/share/classes/java/awt/EventQueue.java @@ -214,9 +214,17 @@ public class EventQueue { FwDispatcher dispatcher) { eventQueue.setFwDispatcher(dispatcher); } + + @Override + public long getMostRecentEventTime(EventQueue eventQueue) { + return eventQueue.getMostRecentEventTimeImpl(); + } }); } + /** + * Initializes a new instance of {@code EventQueue}. + */ public EventQueue() { for (int i = 0; i < NUM_PRIORITIES; i++) { queues[i] = new Queue(); diff --git a/jdk/src/share/classes/java/awt/Frame.java b/jdk/src/share/classes/java/awt/Frame.java index df3fcda4773..c6ce4814078 100644 --- a/jdk/src/share/classes/java/awt/Frame.java +++ b/jdk/src/share/classes/java/awt/Frame.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1089,6 +1089,9 @@ public class Frame extends Window implements MenuContainer { } /** + * Sets the cursor for this frame to the specified type. + * + * @param cursorType the cursor type * @deprecated As of JDK version 1.1, * replaced by Component.setCursor(Cursor). */ @@ -1103,6 +1106,7 @@ public class Frame extends Window implements MenuContainer { /** * @deprecated As of JDK version 1.1, * replaced by Component.getCursor(). + * @return the cursor type for this frame */ @Deprecated public int getCursorType() { @@ -1124,6 +1128,8 @@ public class Frame extends Window implements MenuContainer { * ownerless {@code Dialog}s (introduced in release 1.6), use {@link * Window#getOwnerlessWindows Window.getOwnerlessWindows}. * + * @return the array of all {@code Frame}s created by this application + * * @see Window#getWindows() * @see Window#getOwnerlessWindows * diff --git a/jdk/src/share/classes/java/awt/GraphicsEnvironment.java b/jdk/src/share/classes/java/awt/GraphicsEnvironment.java index e9e9080dba6..2d6436cc00d 100644 --- a/jdk/src/share/classes/java/awt/GraphicsEnvironment.java +++ b/jdk/src/share/classes/java/awt/GraphicsEnvironment.java @@ -357,6 +357,8 @@ public abstract class GraphicsEnvironment { *

    Notice that an application can supersede the registration * of an earlier created font with a new one. * + * + * @param font the font to be registered * @return true if the font is successfully * registered in this GraphicsEnvironment. * @throws NullPointerException if font is null diff --git a/jdk/src/share/classes/java/awt/GridBagLayout.java b/jdk/src/share/classes/java/awt/GridBagLayout.java index 0b2c32ba2b5..981c993751a 100644 --- a/jdk/src/share/classes/java/awt/GridBagLayout.java +++ b/jdk/src/share/classes/java/awt/GridBagLayout.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -981,9 +981,15 @@ java.io.Serializable { * This method is obsolete and supplied for backwards * compatibility only; new code should call {@link * #getLayoutInfo(java.awt.Container, int) getLayoutInfo} instead. - * This method is the same as getLayoutInfo; - * refer to getLayoutInfo for details on parameters - * and return value. + * + * Fills in an instance of {@code GridBagLayoutInfo} for the + * current set of managed children. This method is the same + * as {@code getLayoutInfo}; refer to {@code getLayoutInfo} + * description for details. + * + * @param parent the layout container + * @param sizeflag either {@code PREFERREDSIZE} or {@code MINSIZE} + * @return the {@code GridBagLayoutInfo} for the set of children */ protected GridBagLayoutInfo GetLayoutInfo(Container parent, int sizeflag) { synchronized (parent.getTreeLock()) { @@ -1611,13 +1617,17 @@ java.io.Serializable { } /** + * Adjusts the x, y, width, and height fields to the correct + * values depending on the constraint geometry and pads. + *

    * This method is obsolete and supplied for backwards * compatibility only; new code should call {@link * #adjustForGravity(java.awt.GridBagConstraints, java.awt.Rectangle) * adjustForGravity} instead. - * This method is the same as adjustForGravity; - * refer to adjustForGravity for details - * on parameters. + * This method is the same as adjustForGravity + * + * @param constraints the constraints to be applied + * @param r the {@code Rectangle} to be adjusted */ protected void AdjustForGravity(GridBagConstraints constraints, Rectangle r) { @@ -1995,9 +2005,12 @@ java.io.Serializable { * This method is obsolete and supplied for backwards * compatibility only; new code should call {@link * #getMinSize(java.awt.Container, GridBagLayoutInfo) getMinSize} instead. - * This method is the same as getMinSize; - * refer to getMinSize for details on parameters - * and return value. + * This method is the same as getMinSize + * + * @param parent the layout container + * @param info the layout info for this parent + * @return a Dimension object containing the + * minimum size */ protected Dimension GetMinSize(Container parent, GridBagLayoutInfo info) { Dimension d = new Dimension(); @@ -2035,9 +2048,9 @@ java.io.Serializable { * This method is obsolete and supplied for backwards * compatibility only; new code should call {@link * #arrangeGrid(Container) arrangeGrid} instead. - * This method is the same as arrangeGrid; - * refer to arrangeGrid for details on the - * parameter. + * This method is the same as arrangeGrid + * + * @param parent the layout container */ protected void ArrangeGrid(Container parent) { Component comp; diff --git a/jdk/src/share/classes/java/awt/HeadlessException.java b/jdk/src/share/classes/java/awt/HeadlessException.java index db53a351c6d..5809ffd9faf 100644 --- a/jdk/src/share/classes/java/awt/HeadlessException.java +++ b/jdk/src/share/classes/java/awt/HeadlessException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,10 +38,24 @@ public class HeadlessException extends UnsupportedOperationException { * JDK 1.4 serialVersionUID */ private static final long serialVersionUID = 167183644944358563L; + + /** + * Constructs new {@code HeadlessException} + */ public HeadlessException() {} + + /** + * Create a new instance with the specified detailed error message. + * + * @param msg the error message + */ public HeadlessException(String msg) { super(msg); } + + /** + * {@inheritDoc} + */ public String getMessage() { String superMessage = super.getMessage(); String headlessMessage = GraphicsEnvironment.getHeadlessMessage(); diff --git a/jdk/src/share/classes/java/awt/ItemSelectable.java b/jdk/src/share/classes/java/awt/ItemSelectable.java index d19afb3ab0d..e11b70ef48f 100644 --- a/jdk/src/share/classes/java/awt/ItemSelectable.java +++ b/jdk/src/share/classes/java/awt/ItemSelectable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2000, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,6 +39,8 @@ public interface ItemSelectable { /** * Returns the selected items or null if no * items are selected. + * + * @return the list of selected objects, or {@code null} */ public Object[] getSelectedObjects(); diff --git a/jdk/src/share/classes/java/awt/KeyboardFocusManager.java b/jdk/src/share/classes/java/awt/KeyboardFocusManager.java index 8758a2b50e3..57a8f733ce7 100644 --- a/jdk/src/share/classes/java/awt/KeyboardFocusManager.java +++ b/jdk/src/share/classes/java/awt/KeyboardFocusManager.java @@ -1459,6 +1459,7 @@ public abstract class KeyboardFocusManager * Returns an array of all the PropertyChangeListeners * associated with the named property. * + * @param propertyName the property name * @return all of the PropertyChangeListeners associated with * the named property or an empty array if no such listeners have * been added. @@ -1628,6 +1629,7 @@ public abstract class KeyboardFocusManager * Returns an array of all the VetoableChangeListeners * associated with the named property. * + * @param propertyName the property name * @return all of the VetoableChangeListeners associated with * the named property or an empty array if no such listeners have * been added. diff --git a/jdk/src/share/classes/java/awt/Label.java b/jdk/src/share/classes/java/awt/Label.java index 20ccdcd4c86..c8aab9569ff 100644 --- a/jdk/src/share/classes/java/awt/Label.java +++ b/jdk/src/share/classes/java/awt/Label.java @@ -193,7 +193,8 @@ public class Label extends Component implements Accessible { * Gets the current alignment of this label. Possible values are * Label.LEFT, Label.RIGHT, and * Label.CENTER. - * @see java.awt.Label#setAlignment + * @return the alignment of this label + * @see java.awt.Label#setAlignment */ public int getAlignment() { return alignment; @@ -321,6 +322,9 @@ public class Label extends Component implements Accessible { */ private static final long serialVersionUID = -3568967560160480438L; + /** + * Constructor for the accessible label. + */ public AccessibleAWTLabel() { super(); } diff --git a/jdk/src/share/classes/java/awt/LayoutManager.java b/jdk/src/share/classes/java/awt/LayoutManager.java index 5a00db263e6..d7abfbb1c29 100644 --- a/jdk/src/share/classes/java/awt/LayoutManager.java +++ b/jdk/src/share/classes/java/awt/LayoutManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -61,7 +61,9 @@ public interface LayoutManager { /** * Calculates the preferred size dimensions for the specified * container, given the components it contains. - * @param parent the container to be laid out + * + * @param parent the container to be laid out + * @return the preferred dimension for the container * * @see #minimumLayoutSize */ @@ -70,7 +72,10 @@ public interface LayoutManager { /** * Calculates the minimum size dimensions for the specified * container, given the components it contains. - * @param parent the component to be laid out + * + * @param parent the component to be laid out + * @return the minimum dimension for the container + * * @see #preferredLayoutSize */ Dimension minimumLayoutSize(Container parent); diff --git a/jdk/src/share/classes/java/awt/LayoutManager2.java b/jdk/src/share/classes/java/awt/LayoutManager2.java index ae6516e17b8..347295052e4 100644 --- a/jdk/src/share/classes/java/awt/LayoutManager2.java +++ b/jdk/src/share/classes/java/awt/LayoutManager2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,8 +55,11 @@ public interface LayoutManager2 extends LayoutManager { /** * Calculates the maximum size dimensions for the specified container, * given the components it contains. + * * @see java.awt.Component#getMaximumSize * @see LayoutManager + * @param target the target container + * @return the maximum size of the container */ public Dimension maximumLayoutSize(Container target); @@ -66,6 +69,9 @@ public interface LayoutManager2 extends LayoutManager { * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. + * + * @param target the target container + * @return the x-axis alignment preference */ public float getLayoutAlignmentX(Container target); @@ -75,12 +81,16 @@ public interface LayoutManager2 extends LayoutManager { * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. + * + * @param target the target container + * @return the y-axis alignment preference */ public float getLayoutAlignmentY(Container target); /** * Invalidates the layout, indicating that if the layout manager * has cached information it should be discarded. + * @param target the target container */ public void invalidateLayout(Container target); diff --git a/jdk/src/share/classes/java/awt/List.java b/jdk/src/share/classes/java/awt/List.java index df638c26724..ede6f643157 100644 --- a/jdk/src/share/classes/java/awt/List.java +++ b/jdk/src/share/classes/java/awt/List.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -282,6 +282,9 @@ public class List extends Component implements ItemSelectable, Accessible { } /** + * Returns the number of items in the list. + * + * @return the number of items in the list * @deprecated As of JDK version 1.1, * replaced by getItemCount(). */ @@ -333,7 +336,10 @@ public class List extends Component implements ItemSelectable, Accessible { } /** - * @deprecated replaced by add(String). + * Adds the specified item to the end of the list. + * + * @param item the item to be added + * @deprecated replaced by add(String). */ @Deprecated public void addItem(String item) { @@ -358,7 +364,12 @@ public class List extends Component implements ItemSelectable, Accessible { } /** - * @deprecated replaced by add(String, int). + * Adds the specified item to the the list + * at the position indicated by the index. + * + * @param item the item to be added + * @param index the position at which to add the item + * @deprecated replaced by add(String, int). */ @Deprecated public synchronized void addItem(String item, int index) { @@ -455,8 +466,11 @@ public class List extends Component implements ItemSelectable, Accessible { } /** - * @deprecated replaced by remove(String) - * and remove(int). + * Removes the item at the specified position. + * + * @param position the index of the item to delete + * @deprecated replaced by remove(String) + * and remove(int). */ @Deprecated public void delItem(int position) { @@ -646,6 +660,10 @@ public class List extends Component implements ItemSelectable, Accessible { } /** + * Determines if the specified item in the list is selected. + * + * @param index specifies the item to be checked + * @return {@code true} if the item is selected; otherwise {@code false} * @deprecated As of JDK version 1.1, * replaced by isIndexSelected(int). */ @@ -672,6 +690,7 @@ public class List extends Component implements ItemSelectable, Accessible { /** * Determines whether this list allows multiple selections. + * * @return true if this list allows multiple * selections; otherwise, false * @see #setMultipleMode @@ -682,6 +701,10 @@ public class List extends Component implements ItemSelectable, Accessible { } /** + * Determines whether this list allows multiple selections. + * + * @return {@code true} if this list allows multiple + * selections; otherwise {@code false} * @deprecated As of JDK version 1.1, * replaced by isMultipleMode(). */ @@ -709,6 +732,9 @@ public class List extends Component implements ItemSelectable, Accessible { } /** + * Enables or disables multiple selection mode for this list. + * + * @param b {@code true} to enable multiple mode, {@code false} otherwise * @deprecated As of JDK version 1.1, * replaced by setMultipleMode(boolean). */ @@ -760,6 +786,11 @@ public class List extends Component implements ItemSelectable, Accessible { } /** + * Returns the preferred size of this component + * assuming it has the specified number of rows. + * + * @param rows the number of rows + * @return the preferred dimensions for displaying this list * @deprecated As of JDK version 1.1, * replaced by getPreferredSize(int). */ @@ -810,6 +841,11 @@ public class List extends Component implements ItemSelectable, Accessible { } /** + * Returns the minimum dimensions for the list + * with the specified number of rows. + * + * @param rows the number of rows in the list + * @return the minimum dimensions for displaying this list * @deprecated As of JDK version 1.1, * replaced by getMinimumSize(int). */ @@ -1146,6 +1182,10 @@ public class List extends Component implements ItemSelectable, Accessible { } /** + * Deletes the list items in the specified index range. + * + * @param start the beginning index of the range to delete + * @param end the ending index of the range to delete * @deprecated As of JDK version 1.1, * Not for public use in the future. * This method is expected to be retained only as a package @@ -1290,6 +1330,9 @@ public class List extends Component implements ItemSelectable, Accessible { */ private static final long serialVersionUID = 7924617370136012829L; + /** + * Constructs new {@code AccessibleAWTList} + */ public AccessibleAWTList() { super(); List.this.addActionListener(this); @@ -1491,6 +1534,13 @@ public class List extends Component implements ItemSelectable, Accessible { private List parent; private int indexInParent; + /** + * Constructs new {@code AccessibleAWTListChild} with the given + * parent {@code List} and 0-based index of this object in the parent. + * + * @param parent the parent {@code List} + * @param indexInParent the index in the parent + */ public AccessibleAWTListChild(List parent, int indexInParent) { this.parent = parent; this.setAccessibleParent(parent); diff --git a/jdk/src/share/classes/java/awt/MediaTracker.java b/jdk/src/share/classes/java/awt/MediaTracker.java index e8e8212208b..dd8f9e0825f 100644 --- a/jdk/src/share/classes/java/awt/MediaTracker.java +++ b/jdk/src/share/classes/java/awt/MediaTracker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -226,7 +226,9 @@ public class MediaTracker implements java.io.Serializable { addImageImpl(image, id, w, h); Image rvImage = getResolutionVariant(image); if (rvImage != null) { - addImageImpl(rvImage, id, 2 * w, 2 * h); + addImageImpl(rvImage, id, + w == -1 ? -1 : 2 * w, + h == -1 ? -1 : 2 * h); } } @@ -641,9 +643,11 @@ public class MediaTracker implements java.io.Serializable { * image is considered to have finished loading. Use the * statusID, isErrorID, and * isErrorAny methods to check for errors. - * @param id the identifier of the images to check - * @param ms the length of time, in milliseconds, to wait - * for the loading to complete + * @param id the identifier of the images to check + * @param ms the length of time, in milliseconds, to wait + * for the loading to complete + * @return {@code true} if the loading completed in time; + * otherwise {@code false} * @see java.awt.MediaTracker#waitForAll * @see java.awt.MediaTracker#waitForID(int) * @see java.awt.MediaTracker#statusID @@ -810,8 +814,9 @@ public class MediaTracker implements java.io.Serializable { removeImageImpl(image, id, width, height); Image rvImage = getResolutionVariant(image); if (rvImage != null) { - removeImageImpl(rvImage, id, 2 * width, 2 * height); - + removeImageImpl(rvImage, id, + width == -1 ? -1 : 2 * width, + height == -1 ? -1 : 2 * height); } notifyAll(); // Notify in case remaining images are "done". } diff --git a/jdk/src/share/classes/java/awt/Menu.java b/jdk/src/share/classes/java/awt/Menu.java index 177f208be05..3c8154338ac 100644 --- a/jdk/src/share/classes/java/awt/Menu.java +++ b/jdk/src/share/classes/java/awt/Menu.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -213,7 +213,7 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { /** * Get the number of items in this menu. - * @return the number of items in this menu. + * @return the number of items in this menu * @since 1.1 */ public int getItemCount() { @@ -221,6 +221,9 @@ public class Menu extends MenuItem implements MenuContainer, Accessible { } /** + * Returns the number of items in this menu. + * + * @return the number of items in this menu * @deprecated As of JDK version 1.1, * replaced by getItemCount(). */ diff --git a/jdk/src/share/classes/java/awt/MenuBar.java b/jdk/src/share/classes/java/awt/MenuBar.java index 4e48c7c38ce..4fa4723c417 100644 --- a/jdk/src/share/classes/java/awt/MenuBar.java +++ b/jdk/src/share/classes/java/awt/MenuBar.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -279,6 +279,9 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible } /** + * Gets the number of menus on the menu bar. + * + * @return the number of menus on the menu bar. * @deprecated As of JDK version 1.1, * replaced by getMenuCount(). */ @@ -338,10 +341,11 @@ public class MenuBar extends MenuComponent implements MenuContainer, Accessible * or null if none of the menu items being managed * by this menu bar is associated with the specified menu * shortcut. - * @param s the specified menu shortcut. - * @see java.awt.MenuItem - * @see java.awt.MenuShortcut - * @since 1.1 + * @param s the specified menu shortcut. + * @return the menu item for the specified shortcut. + * @see java.awt.MenuItem + * @see java.awt.MenuShortcut + * @since 1.1 */ public MenuItem getShortcutMenuItem(MenuShortcut s) { int nmenus = getMenuCount(); diff --git a/jdk/src/share/classes/java/awt/MenuComponent.java b/jdk/src/share/classes/java/awt/MenuComponent.java index 28fb9ab209e..4ea95bf5969 100644 --- a/jdk/src/share/classes/java/awt/MenuComponent.java +++ b/jdk/src/share/classes/java/awt/MenuComponent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -220,6 +220,7 @@ public abstract class MenuComponent implements java.io.Serializable { /** * @deprecated As of JDK version 1.1, * programs should not directly manipulate peers. + * @return the peer for this component */ @Deprecated public MenuComponentPeer getPeer() { diff --git a/jdk/src/share/classes/java/awt/MenuContainer.java b/jdk/src/share/classes/java/awt/MenuContainer.java index 8b43f992f4f..8ba5e70245b 100644 --- a/jdk/src/share/classes/java/awt/MenuContainer.java +++ b/jdk/src/share/classes/java/awt/MenuContainer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,10 +31,25 @@ package java.awt; */ public interface MenuContainer { + + /** + * Returns the font in use by this container. + * + * @return the menu font + */ Font getFont(); + + /** + * Removes the specified menu component from the menu. + * + * @param comp the menu component to remove + */ void remove(MenuComponent comp); /** + * Posts an event to the listeners. + * + * @param evt the event to dispatch * @deprecated As of JDK version 1.1 * replaced by dispatchEvent(AWTEvent). */ diff --git a/jdk/src/share/classes/java/awt/MenuItem.java b/jdk/src/share/classes/java/awt/MenuItem.java index a81c1314700..ab797f4dd1a 100644 --- a/jdk/src/share/classes/java/awt/MenuItem.java +++ b/jdk/src/share/classes/java/awt/MenuItem.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -264,6 +264,9 @@ public class MenuItem extends MenuComponent implements Accessible { /** * Checks whether this menu item is enabled. + * + * @return {@code true} if the item is enabled; + * otherwise {@code false} * @see java.awt.MenuItem#setEnabled * @since 1.0 */ @@ -296,6 +299,10 @@ public class MenuItem extends MenuComponent implements Accessible { } /** + * Sets whether or not this menu item can be chosen. + * + * @param b if {@code true}, enables this menu item; + * otherwise disables * @deprecated As of JDK version 1.1, * replaced by setEnabled(boolean). */ @@ -494,8 +501,10 @@ public class MenuItem extends MenuComponent implements Accessible { /** * Gets the command name of the action event that is fired * by this menu item. - * @see java.awt.MenuItem#setActionCommand - * @since 1.1 + * + * @return the action command name + * @see java.awt.MenuItem#setActionCommand + * @since 1.1 */ public String getActionCommand() { return getActionCommandImpl(); diff --git a/jdk/src/share/classes/java/awt/PrintGraphics.java b/jdk/src/share/classes/java/awt/PrintGraphics.java index 91e5173f81f..74c2f84a31e 100644 --- a/jdk/src/share/classes/java/awt/PrintGraphics.java +++ b/jdk/src/share/classes/java/awt/PrintGraphics.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 1997, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,6 +35,8 @@ public interface PrintGraphics { /** * Returns the PrintJob object from which this PrintGraphics * object originated. + * + * @return the print job for this object */ public PrintJob getPrintJob(); diff --git a/jdk/src/share/classes/java/awt/PrintJob.java b/jdk/src/share/classes/java/awt/PrintJob.java index 996d7653526..fcc6afebf2a 100644 --- a/jdk/src/share/classes/java/awt/PrintJob.java +++ b/jdk/src/share/classes/java/awt/PrintJob.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,6 +42,7 @@ public abstract class PrintJob { * object is disposed. This graphics object will also implement * the PrintGraphics interface. * @see PrintGraphics + * @return the graphics context for printing the next page */ public abstract Graphics getGraphics(); @@ -49,6 +50,8 @@ public abstract class PrintJob { * Returns the dimensions of the page in pixels. * The resolution of the page is chosen so that it * is similar to the screen resolution. + * + * @return the page dimension */ public abstract Dimension getPageDimension(); @@ -56,11 +59,16 @@ public abstract class PrintJob { * Returns the resolution of the page in pixels per inch. * Note that this doesn't have to correspond to the physical * resolution of the printer. + * + * @return the page resolution */ public abstract int getPageResolution(); /** * Returns true if the last page will be printed first. + * + * @return {@code true} if the last page will be printed first; + * otherwise {@code false} */ public abstract boolean lastPageFirst(); diff --git a/jdk/src/share/classes/java/awt/Robot.java b/jdk/src/share/classes/java/awt/Robot.java index cc734dd45a2..8de89ee8ed9 100644 --- a/jdk/src/share/classes/java/awt/Robot.java +++ b/jdk/src/share/classes/java/awt/Robot.java @@ -498,6 +498,8 @@ public class Robot { /** * Returns the number of milliseconds this Robot sleeps after generating an event. + * + * @return the delay duration in milliseconds */ public synchronized int getAutoDelay() { return autoDelay; @@ -505,7 +507,10 @@ public class Robot { /** * Sets the number of milliseconds this Robot sleeps after generating an event. - * @throws IllegalArgumentException If ms is not between 0 and 60,000 milliseconds inclusive + * + * @param ms the delay duration in milliseconds + * @throws IllegalArgumentException If {@code ms} + * is not between 0 and 60,000 milliseconds inclusive */ public synchronized void setAutoDelay(int ms) { checkDelayArgument(ms); @@ -523,9 +528,11 @@ public class Robot { * Sleeps for the specified time. * To catch any InterruptedExceptions that occur, * Thread.sleep() may be used instead. - * @param ms time to sleep in milliseconds - * @throws IllegalArgumentException if ms is not between 0 and 60,000 milliseconds inclusive - * @see java.lang.Thread#sleep + * + * @param ms time to sleep in milliseconds + * @throws IllegalArgumentException if {@code ms} + * is not between 0 and 60,000 milliseconds inclusive + * @see java.lang.Thread#sleep */ public synchronized void delay(int ms) { checkDelayArgument(ms); diff --git a/jdk/src/share/classes/java/awt/ScrollPane.java b/jdk/src/share/classes/java/awt/ScrollPane.java index 70ca48f4d74..fb5401d06f6 100644 --- a/jdk/src/share/classes/java/awt/ScrollPane.java +++ b/jdk/src/share/classes/java/awt/ScrollPane.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -323,7 +323,9 @@ public class ScrollPane extends Container implements Accessible { * represents the state of the vertical scrollbar. * The declared return type of this method is * Adjustable to maintain backward compatibility. + * * @see java.awt.ScrollPaneAdjustable + * @return the vertical scrollbar state */ public Adjustable getVAdjustable() { return vAdjustable; @@ -334,7 +336,9 @@ public class ScrollPane extends Container implements Accessible { * represents the state of the horizontal scrollbar. * The declared return type of this method is * Adjustable to maintain backward compatibility. + * * @see java.awt.ScrollPaneAdjustable + * @return the horizontal scrollbar state */ public Adjustable getHAdjustable() { return hAdjustable; @@ -657,6 +661,9 @@ public class ScrollPane extends Container implements Accessible { * Indicates whether or not scrolling will take place in response to * the mouse wheel. Wheel scrolling is enabled by default. * + * @return {@code true} if the wheel scrolling enabled; + * otherwise {@code false} + * * @see #setWheelScrollingEnabled(boolean) * @since 1.4 */ diff --git a/jdk/src/share/classes/java/awt/Scrollbar.java b/jdk/src/share/classes/java/awt/Scrollbar.java index bf119ae2779..28c84efb923 100644 --- a/jdk/src/share/classes/java/awt/Scrollbar.java +++ b/jdk/src/share/classes/java/awt/Scrollbar.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -656,6 +656,9 @@ public class Scrollbar extends Component implements Adjustable, Accessible { } /** + * Returns the visible amount of this scroll bar. + * + * @return the visible amount of this scroll bar * @deprecated As of JDK version 1.1, * replaced by getVisibleAmount(). */ @@ -729,6 +732,10 @@ public class Scrollbar extends Component implements Adjustable, Accessible { } /** + * Sets the unit increment for this scroll bar. + * + * @param v the increment value + * * @deprecated As of JDK version 1.1, * replaced by setUnitIncrement(int). */ @@ -768,6 +775,9 @@ public class Scrollbar extends Component implements Adjustable, Accessible { } /** + * Returns the unit increment for this scrollbar. + * + * @return the unit increment for this scrollbar * @deprecated As of JDK version 1.1, * replaced by getUnitIncrement(). */ @@ -797,6 +807,9 @@ public class Scrollbar extends Component implements Adjustable, Accessible { } /** + * Sets the block increment for this scroll bar. + * + * @param v the block increment * @deprecated As of JDK version 1.1, * replaced by setBlockIncrement(). */ @@ -833,6 +846,10 @@ public class Scrollbar extends Component implements Adjustable, Accessible { } /** + * Returns the block increment of this scroll bar. + * + * @return the block increment of this scroll bar + * * @deprecated As of JDK version 1.1, * replaced by getBlockIncrement(). */ diff --git a/jdk/src/share/classes/java/awt/TextArea.java b/jdk/src/share/classes/java/awt/TextArea.java index dd90aa7414e..f29da08b537 100644 --- a/jdk/src/share/classes/java/awt/TextArea.java +++ b/jdk/src/share/classes/java/awt/TextArea.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -314,6 +314,11 @@ public class TextArea extends TextComponent { } /** + * Inserts the specified text at the specified position + * in this text area. + * + * @param str the non-{@code null} text to insert + * @param pos the position at which to insert * @deprecated As of JDK version 1.1, * replaced by insert(String, int). */ @@ -342,6 +347,9 @@ public class TextArea extends TextComponent { } /** + * Appends the given text to the text area's current text. + * + * @param str the text to append * @deprecated As of JDK version 1.1, * replaced by append(String). */ @@ -378,6 +386,15 @@ public class TextArea extends TextComponent { } /** + * Replaces a range of characters between + * the indicated start and end positions + * with the specified replacement text (the text at the end + * position will not be replaced). + * + * @param str the non-{@code null} text to use as + * the replacement + * @param start the start position + * @param end the end position * @deprecated As of JDK version 1.1, * replaced by replaceRange(String, int, int). */ @@ -492,6 +509,12 @@ public class TextArea extends TextComponent { } /** + * Determines the preferred size of the text area with the specified + * number of rows and columns. + * + * @param rows the number of rows + * @param columns the number of columns + * @return the preferred dimensions needed for the text area * @deprecated As of JDK version 1.1, * replaced by getPreferredSize(int, int). */ @@ -544,6 +567,12 @@ public class TextArea extends TextComponent { } /** + * Determines the minimum size of the text area with the specified + * number of rows and columns. + * + * @param rows the number of rows + * @param columns the number of columns + * @return the minimum size for the text area * @deprecated As of JDK version 1.1, * replaced by getMinimumSize(int, int). */ diff --git a/jdk/src/share/classes/java/awt/TextComponent.java b/jdk/src/share/classes/java/awt/TextComponent.java index 104fe02e53b..639438a2a1d 100644 --- a/jdk/src/share/classes/java/awt/TextComponent.java +++ b/jdk/src/share/classes/java/awt/TextComponent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -107,6 +107,9 @@ public class TextComponent extends Component implements Accessible { // the background color of non-editable TextComponents. boolean backgroundSetByClientCode = false; + /** + * A list of listeners that will receive events from this object. + */ transient protected TextListener textListener; /* diff --git a/jdk/src/share/classes/java/awt/TextField.java b/jdk/src/share/classes/java/awt/TextField.java index 3b4646896e1..ebebc828b96 100644 --- a/jdk/src/share/classes/java/awt/TextField.java +++ b/jdk/src/share/classes/java/awt/TextField.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -272,6 +272,10 @@ public class TextField extends TextComponent { } /** + * Sets the character to be echoed when protected input is displayed. + * + * @param c the echo character for this text field + * * @deprecated As of JDK version 1.1, * replaced by setEchoChar(char). */ @@ -368,6 +372,12 @@ public class TextField extends TextComponent { } /** + * Returns the preferred size for this text field + * with the specified number of columns. + * + * @param columns the number of columns + * @return the preferred size for the text field + * * @deprecated As of JDK version 1.1, * replaced by getPreferredSize(int). */ @@ -407,8 +417,9 @@ public class TextField extends TextComponent { /** * Gets the minimum dimensions for a text field with * the specified number of columns. - * @param columns the number of columns in - * this text field. + * @param columns the number of columns in + * this text field. + * @return the minimum size for this text field * @since 1.1 */ public Dimension getMinimumSize(int columns) { @@ -416,6 +427,11 @@ public class TextField extends TextComponent { } /** + * Returns the minimum dimensions for a text field with + * the specified number of columns. + * + * @param columns the number of columns + * @return the minimum size for this text field * @deprecated As of JDK version 1.1, * replaced by getMinimumSize(int). */ diff --git a/jdk/src/share/classes/java/awt/Toolkit.java b/jdk/src/share/classes/java/awt/Toolkit.java index 7bc8c24f625..65b494ba52d 100644 --- a/jdk/src/share/classes/java/awt/Toolkit.java +++ b/jdk/src/share/classes/java/awt/Toolkit.java @@ -422,7 +422,8 @@ public abstract class Toolkit { * and allows the Component and Container classes to be extended directly * to create windowless components that are defined entirely in java. * - * @param target The Component to be created. + * @param target The Component to be created. + * @return the peer for the specified component */ protected LightweightPeer createComponent(Component target) { if (lightweightMarker == null) { @@ -1370,6 +1371,9 @@ public abstract class Toolkit { * {@link java.awt.event.KeyEvent#VK_SCROLL_LOCK VK_SCROLL_LOCK}, and * {@link java.awt.event.KeyEvent#VK_KANA_LOCK VK_KANA_LOCK}. * + * @param keyCode the key code + * @return {@code true} if the given key is currently in its "on" state; + * otherwise {@code false} * @exception java.lang.IllegalArgumentException if keyCode * is not one of the valid key codes * @exception java.lang.UnsupportedOperationException if the host system doesn't @@ -1404,6 +1408,8 @@ public abstract class Toolkit { * involve event processing and therefore may not be immediately * observable through getLockingKeyState. * + * @param keyCode the key code + * @param on the state of the key * @exception java.lang.IllegalArgumentException if keyCode * is not one of the valid key codes * @exception java.lang.UnsupportedOperationException if the host system doesn't @@ -1429,6 +1435,9 @@ public abstract class Toolkit { /** * Give native peers the ability to query the native container * given a native component (eg the direct parent may be lightweight). + * + * @param c the component to fetch the container for + * @return the native container object for the component */ protected static Container getNativeContainer(Component c) { return c.getNativeContainer(); @@ -1449,6 +1458,7 @@ public abstract class Toolkit { * @param name a localized description of the cursor, for Java Accessibility use * @exception IndexOutOfBoundsException if the hotSpot values are outside * the bounds of the cursor + * @return the cursor created * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true * @see java.awt.GraphicsEnvironment#isHeadless @@ -1675,6 +1685,11 @@ public abstract class Toolkit { /** * Gets a property with the specified key and default. * This method returns defaultValue if the property is not found. + * + * @param key the key + * @param defaultValue the default value + * @return the value of the property or the default value + * if the property was not found */ public static String getProperty(String key, String defaultValue) { // first try platform specific bundle @@ -1738,6 +1753,9 @@ public abstract class Toolkit { * Creates the peer for a DragSourceContext. * Always throws InvalidDndOperationException if * GraphicsEnvironment.isHeadless() returns true. + * + * @param dge the {@code DragGestureEvent} + * @return the peer created * @see java.awt.GraphicsEnvironment#isHeadless */ public abstract DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent dge) throws InvalidDnDOperationException; @@ -1775,6 +1793,9 @@ public abstract class Toolkit { * representation for an underlying platform dependent desktop setting. * For more information on desktop properties supported by the AWT see * AWT Desktop Properties. + * + * @param propertyName the property name + * @return the value for the specified desktop property */ public final synchronized Object getDesktopProperty(String propertyName) { // This is a workaround for headless toolkits. It would be @@ -1818,6 +1839,9 @@ public abstract class Toolkit { /** * Sets the named desktop property to the specified value and fires a * property change event to notify any listeners that the value has changed. + * + * @param name the property name + * @param newValue the new property value */ protected final void setDesktopProperty(String name, Object newValue) { // This is a workaround for headless toolkits. It would be diff --git a/jdk/src/share/classes/java/awt/Window.java b/jdk/src/share/classes/java/awt/Window.java index 47bcdf301ca..629f1df75a4 100644 --- a/jdk/src/share/classes/java/awt/Window.java +++ b/jdk/src/share/classes/java/awt/Window.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1452,6 +1452,8 @@ public class Window extends Container implements Accessible { /** * Returns the owner of this window. + * + * @return the owner of this window * @since 1.2 */ public Window getOwner() { @@ -1464,6 +1466,8 @@ public class Window extends Container implements Accessible { /** * Return an array containing all the windows this * window currently owns. + * + * @return the array of all the owned windows * @since 1.2 */ public Window[] getOwnedWindows() { @@ -1586,6 +1590,7 @@ public class Window extends Container implements Accessible { * dialogs such as component positions, {@code LayoutManager}s * or serialization. * + * @return the array of all the {@code Window}s created by the application * @see Frame#getFrames * @see Window#getOwnerlessWindows * @@ -1608,6 +1613,8 @@ public class Window extends Container implements Accessible { * dialogs such as component positions, {@code LayoutManager}s * or serialization. * + * @return the array of all the ownerless {@code Window}s + * created by this application * @see Frame#getFrames * @see Window#getWindows() * @@ -2849,6 +2856,7 @@ public class Window extends Container implements Accessible { * * This method can only be called while the window is not displayable. * + * @param type the window type * @throws IllegalComponentStateException if the window * is displayable. * @throws IllegalArgumentException if the type is {@code null} @@ -2874,6 +2882,7 @@ public class Window extends Container implements Accessible { /** * Returns the type of the window. * + * @return the type of the window * @see #setType * @since 1.7 */ diff --git a/jdk/src/share/classes/java/awt/event/InputMethodEvent.java b/jdk/src/share/classes/java/awt/event/InputMethodEvent.java index 104f10b8fea..ca214ed6e45 100644 --- a/jdk/src/share/classes/java/awt/event/InputMethodEvent.java +++ b/jdk/src/share/classes/java/awt/event/InputMethodEvent.java @@ -25,6 +25,10 @@ package java.awt.event; +import sun.awt.AWTAccessor; +import sun.awt.AppContext; +import sun.awt.SunToolkit; + import java.awt.AWTEvent; import java.awt.Component; import java.awt.EventQueue; @@ -217,8 +221,10 @@ public class InputMethodEvent extends AWTEvent { public InputMethodEvent(Component source, int id, AttributedCharacterIterator text, int committedCharacterCount, TextHitInfo caret, TextHitInfo visiblePosition) { - this(source, id, EventQueue.getMostRecentEventTime(), text, - committedCharacterCount, caret, visiblePosition); + this(source, id, + getMostRecentEventTimeForSource(source), + text, committedCharacterCount, + caret, visiblePosition); } /** @@ -258,8 +264,9 @@ public class InputMethodEvent extends AWTEvent { */ public InputMethodEvent(Component source, int id, TextHitInfo caret, TextHitInfo visiblePosition) { - this(source, id, EventQueue.getMostRecentEventTime(), null, - 0, caret, visiblePosition); + this(source, id, + getMostRecentEventTimeForSource(source), + null, 0, caret, visiblePosition); } /** @@ -411,7 +418,25 @@ public class InputMethodEvent extends AWTEvent { private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { s.defaultReadObject(); if (when == 0) { - when = EventQueue.getMostRecentEventTime(); + when = getMostRecentEventTimeForSource(this.source); } } + + /** + * Get the most recent event time in the {@code EventQueue} which the {@code source} + * belongs to. + * + * @param source the source of the event + * @exception IllegalArgumentException if source is null. + * @return most recent event time in the {@code EventQueue} + */ + private static long getMostRecentEventTimeForSource(Object source) { + if (source == null) { + // throw the IllegalArgumentException to conform to EventObject spec + throw new IllegalArgumentException("null source"); + } + AppContext appContext = SunToolkit.targetToAppContext(source); + EventQueue eventQueue = SunToolkit.getSystemEventQueueImplPP(appContext); + return AWTAccessor.getEventQueueAccessor().getMostRecentEventTime(eventQueue); + } } diff --git a/jdk/src/share/classes/java/awt/font/StyledParagraph.java b/jdk/src/share/classes/java/awt/font/StyledParagraph.java index 2087fa09455..380fa36e918 100644 --- a/jdk/src/share/classes/java/awt/font/StyledParagraph.java +++ b/jdk/src/share/classes/java/awt/font/StyledParagraph.java @@ -38,9 +38,9 @@ import java.text.AttributedCharacterIterator.Attribute; import java.util.Vector; import java.util.HashMap; import java.util.Map; +import sun.font.CodePointIterator; import sun.font.Decoration; import sun.font.FontResolver; -import sun.text.CodePointIterator; /** * This class stores Font, GraphicAttribute, and Decoration intervals diff --git a/jdk/src/share/classes/java/awt/font/TextLayout.java b/jdk/src/share/classes/java/awt/font/TextLayout.java index 08d779427a1..45da5af89c6 100644 --- a/jdk/src/share/classes/java/awt/font/TextLayout.java +++ b/jdk/src/share/classes/java/awt/font/TextLayout.java @@ -60,13 +60,13 @@ import java.util.Map; import java.util.HashMap; import java.util.Hashtable; import sun.font.AttributeValues; +import sun.font.CodePointIterator; import sun.font.CoreMetrics; import sun.font.Decoration; import sun.font.FontLineMetrics; import sun.font.FontResolver; import sun.font.GraphicComponent; import sun.font.LayoutPathImpl; -import sun.text.CodePointIterator; /** * diff --git a/jdk/src/share/classes/java/awt/font/TextLine.java b/jdk/src/share/classes/java/awt/font/TextLine.java index 9efcdc32de2..c1c4e899997 100644 --- a/jdk/src/share/classes/java/awt/font/TextLine.java +++ b/jdk/src/share/classes/java/awt/font/TextLine.java @@ -50,6 +50,7 @@ import java.util.Hashtable; import java.util.Map; import sun.font.AttributeValues; import sun.font.BidiUtils; +import sun.font.CodePointIterator; import sun.font.CoreMetrics; import sun.font.Decoration; import sun.font.FontLineMetrics; @@ -60,7 +61,6 @@ import sun.font.LayoutPathImpl.EmptyPath; import sun.font.LayoutPathImpl.SegmentPathBuilder; import sun.font.TextLabelFactory; import sun.font.TextLineComponent; -import sun.text.CodePointIterator; import java.awt.geom.Line2D; diff --git a/jdk/src/share/classes/java/awt/geom/Path2D.java b/jdk/src/share/classes/java/awt/geom/Path2D.java index 7a401d36cf4..d75adf0cb57 100644 --- a/jdk/src/share/classes/java/awt/geom/Path2D.java +++ b/jdk/src/share/classes/java/awt/geom/Path2D.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -285,6 +285,8 @@ public abstract class Path2D implements Shape, Cloneable { int grow = size; if (grow > EXPAND_MAX) { grow = EXPAND_MAX; + } else if (grow == 0) { + grow = 1; } pointTypes = Arrays.copyOf(pointTypes, size+grow); } @@ -1121,6 +1123,8 @@ public abstract class Path2D implements Shape, Cloneable { int grow = size; if (grow > EXPAND_MAX) { grow = EXPAND_MAX; + } else if (grow == 0) { + grow = 1; } pointTypes = Arrays.copyOf(pointTypes, size+grow); } diff --git a/jdk/src/share/classes/java/awt/image/renderable/ParameterBlock.java b/jdk/src/share/classes/java/awt/image/renderable/ParameterBlock.java index bf14e8ce2d3..e6b923dda0e 100644 --- a/jdk/src/share/classes/java/awt/image/renderable/ParameterBlock.java +++ b/jdk/src/share/classes/java/awt/image/renderable/ParameterBlock.java @@ -337,7 +337,7 @@ public class ParameterBlock implements Cloneable, Serializable { * the specified parameter. */ public ParameterBlock add(byte b) { - return add(new Byte(b)); + return add(Byte.valueOf(b)); } /** @@ -348,7 +348,7 @@ public class ParameterBlock implements Cloneable, Serializable { * the specified parameter. */ public ParameterBlock add(char c) { - return add(new Character(c)); + return add(Character.valueOf(c)); } /** @@ -359,7 +359,7 @@ public class ParameterBlock implements Cloneable, Serializable { * the specified parameter. */ public ParameterBlock add(short s) { - return add(new Short(s)); + return add(Short.valueOf(s)); } /** @@ -381,7 +381,7 @@ public class ParameterBlock implements Cloneable, Serializable { * the specified parameter. */ public ParameterBlock add(long l) { - return add(new Long(l)); + return add(Long.valueOf(l)); } /** @@ -441,7 +441,7 @@ public class ParameterBlock implements Cloneable, Serializable { * the specified parameter. */ public ParameterBlock set(byte b, int index) { - return set(new Byte(b), index); + return set(Byte.valueOf(b), index); } /** @@ -457,7 +457,7 @@ public class ParameterBlock implements Cloneable, Serializable { * the specified parameter. */ public ParameterBlock set(char c, int index) { - return set(new Character(c), index); + return set(Character.valueOf(c), index); } /** @@ -473,7 +473,7 @@ public class ParameterBlock implements Cloneable, Serializable { * the specified parameter. */ public ParameterBlock set(short s, int index) { - return set(new Short(s), index); + return set(Short.valueOf(s), index); } /** @@ -505,7 +505,7 @@ public class ParameterBlock implements Cloneable, Serializable { * the specified parameter. */ public ParameterBlock set(long l, int index) { - return set(new Long(l), index); + return set(Long.valueOf(l), index); } /** diff --git a/jdk/src/share/classes/java/beans/BeanDescriptor.java b/jdk/src/share/classes/java/beans/BeanDescriptor.java index fee54153bd3..10912ed7f4d 100644 --- a/jdk/src/share/classes/java/beans/BeanDescriptor.java +++ b/jdk/src/share/classes/java/beans/BeanDescriptor.java @@ -33,6 +33,8 @@ import java.lang.ref.Reference; *

    * This is one of the kinds of descriptor returned by a BeanInfo object, * which also returns descriptors for properties, method, and events. + * + * @since 1.1 */ public class BeanDescriptor extends FeatureDescriptor { diff --git a/jdk/src/share/classes/java/beans/BeanInfo.java b/jdk/src/share/classes/java/beans/BeanInfo.java index bb43f2fd4e8..92be1eb81a4 100644 --- a/jdk/src/share/classes/java/beans/BeanInfo.java +++ b/jdk/src/share/classes/java/beans/BeanInfo.java @@ -48,6 +48,8 @@ import java.awt.Image; * the {@code SimpleBeanInfo} class to define specific information. *

    * See also the {@link Introspector} class to learn more about bean behavior. + * + * @since 1.1 */ public interface BeanInfo { diff --git a/jdk/src/share/classes/java/beans/Beans.java b/jdk/src/share/classes/java/beans/Beans.java index 5bf13fa7d09..cd864899ea6 100644 --- a/jdk/src/share/classes/java/beans/Beans.java +++ b/jdk/src/share/classes/java/beans/Beans.java @@ -56,6 +56,8 @@ import java.util.Vector; /** * This class provides some general purpose beans control methods. + * + * @since 1.1 */ public class Beans { @@ -96,6 +98,7 @@ public class Beans { * @exception ClassNotFoundException if the class of a serialized * object could not be found. * @exception IOException if an I/O error occurs. + * @since 1.2 */ public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext) throws IOException, ClassNotFoundException { @@ -152,6 +155,7 @@ public class Beans { * @exception ClassNotFoundException if the class of a serialized * object could not be found. * @exception IOException if an I/O error occurs. + * @since 1.2 */ public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext, AppletInitializer initializer) diff --git a/jdk/src/share/classes/java/beans/Customizer.java b/jdk/src/share/classes/java/beans/Customizer.java index 07d70631e78..5dcd03b0b5a 100644 --- a/jdk/src/share/classes/java/beans/Customizer.java +++ b/jdk/src/share/classes/java/beans/Customizer.java @@ -33,6 +33,8 @@ package java.beans; * it can be instantiated inside an AWT dialog or panel. *

    * Each customizer should have a null constructor. + * + * @since 1.1 */ public interface Customizer { diff --git a/jdk/src/share/classes/java/beans/EventHandler.java b/jdk/src/share/classes/java/beans/EventHandler.java index 470991e11bd..dd41750f2f1 100644 --- a/jdk/src/share/classes/java/beans/EventHandler.java +++ b/jdk/src/share/classes/java/beans/EventHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -446,7 +446,7 @@ public class EventHandler implements InvocationHandler { } if (listenerMethodName == null || listenerMethodName.equals(methodName)) { - Class[] argTypes = null; + Class[] argTypes = null; Object[] newArgs = null; if (eventPropertyName == null) { // Nullary method. diff --git a/jdk/src/share/classes/java/beans/EventSetDescriptor.java b/jdk/src/share/classes/java/beans/EventSetDescriptor.java index 78bc44d2978..d05d2f79375 100644 --- a/jdk/src/share/classes/java/beans/EventSetDescriptor.java +++ b/jdk/src/share/classes/java/beans/EventSetDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,6 +36,8 @@ import java.lang.reflect.Modifier; * The given group of events are all delivered as method calls on a single * event listener interface, and an event listener object can be registered * via a call on a registration method supplied by the event source. + * + * @since 1.1 */ public class EventSetDescriptor extends FeatureDescriptor { @@ -81,7 +83,7 @@ public class EventSetDescriptor extends FeatureDescriptor { String eventName = NameGenerator.capitalize(eventSetName) + "Event"; Method[] listenerMethods = getListenerMethods(); if (listenerMethods.length > 0) { - Class[] args = getParameterTypes(getClass0(), listenerMethods[0]); + Class[] args = getParameterTypes(getClass0(), listenerMethods[0]); // Check for EventSet compliance. Special case for vetoableChange. See 4529996 if (!"vetoableChange".equals(eventSetName) && !args[0].getName().endsWith(eventName)) { throw new IntrospectionException("Method \"" + listenerMethodName + diff --git a/jdk/src/share/classes/java/beans/FeatureDescriptor.java b/jdk/src/share/classes/java/beans/FeatureDescriptor.java index 75f06f33fc2..6a82de9f971 100644 --- a/jdk/src/share/classes/java/beans/FeatureDescriptor.java +++ b/jdk/src/share/classes/java/beans/FeatureDescriptor.java @@ -46,6 +46,8 @@ import java.util.Map.Entry; *

    * In addition it provides an extension mechanism so that arbitrary * attribute/value pairs can be associated with a design feature. + * + * @since 1.1 */ public class FeatureDescriptor { @@ -145,6 +147,7 @@ public class FeatureDescriptor { * important for presenting to humans. * * @return True if this feature should be preferentially shown to human users. + * @since 1.2 */ public boolean isPreferred() { return preferred; @@ -156,6 +159,7 @@ public class FeatureDescriptor { * * @param preferred True if this feature should be preferentially shown * to human users. + * @since 1.2 */ public void setPreferred(boolean preferred) { this.preferred = preferred; diff --git a/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java b/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java index 1f329a31c55..9449421eae2 100644 --- a/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java +++ b/jdk/src/share/classes/java/beans/IndexedPropertyDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,6 +36,8 @@ import java.lang.reflect.Method; * An indexed property may also provide simple non-indexed read and write * methods. If these are present, they read and write arrays of the type * returned by the indexed read method. + * + * @since 1.1 */ public class IndexedPropertyDescriptor extends PropertyDescriptor { @@ -209,6 +211,8 @@ public class IndexedPropertyDescriptor extends PropertyDescriptor { * @param readMethod The new indexed read method. * @throws IntrospectionException if an exception occurs during * introspection. + * + * @since 1.2 */ public synchronized void setIndexedReadMethod(Method readMethod) throws IntrospectionException { @@ -288,6 +292,8 @@ public class IndexedPropertyDescriptor extends PropertyDescriptor { * @param writeMethod The new indexed write method. * @throws IntrospectionException if an exception occurs during * introspection. + * + * @since 1.2 */ public synchronized void setIndexedWriteMethod(Method writeMethod) throws IntrospectionException { @@ -353,7 +359,7 @@ public class IndexedPropertyDescriptor extends PropertyDescriptor { Class indexedPropertyType = null; if (indexedReadMethod != null) { - Class params[] = getParameterTypes(getClass0(), indexedReadMethod); + Class[] params = getParameterTypes(getClass0(), indexedReadMethod); if (params.length != 1) { throw new IntrospectionException("bad indexed read method arg count"); } @@ -366,7 +372,7 @@ public class IndexedPropertyDescriptor extends PropertyDescriptor { } } if (indexedWriteMethod != null) { - Class params[] = getParameterTypes(getClass0(), indexedWriteMethod); + Class[] params = getParameterTypes(getClass0(), indexedWriteMethod); if (params.length != 2) { throw new IntrospectionException("bad indexed write method arg count"); } diff --git a/jdk/src/share/classes/java/beans/IntrospectionException.java b/jdk/src/share/classes/java/beans/IntrospectionException.java index c9cf2eeb44b..432ba99e93b 100644 --- a/jdk/src/share/classes/java/beans/IntrospectionException.java +++ b/jdk/src/share/classes/java/beans/IntrospectionException.java @@ -32,6 +32,8 @@ package java.beans; * to a Class object, not being able to resolve a string method name, * or specifying a method name that has the wrong type signature for * its intended use. + * + * @since 1.1 */ public diff --git a/jdk/src/share/classes/java/beans/Introspector.java b/jdk/src/share/classes/java/beans/Introspector.java index 3f1e564e8f5..85baed810bf 100644 --- a/jdk/src/share/classes/java/beans/Introspector.java +++ b/jdk/src/share/classes/java/beans/Introspector.java @@ -90,6 +90,8 @@ import sun.reflect.misc.ReflectUtil; * For more information about introspection and design patterns, please * consult the * JavaBeans™ specification. + * + * @since 1.1 */ public class Introspector { @@ -97,14 +99,17 @@ public class Introspector { // Flags that can be used to control getBeanInfo: /** * Flag to indicate to use of all beaninfo. + * @since 1.2 */ public final static int USE_ALL_BEANINFO = 1; /** * Flag to indicate to ignore immediate beaninfo. + * @since 1.2 */ public final static int IGNORE_IMMEDIATE_BEANINFO = 2; /** * Flag to indicate to ignore all beaninfo. + * @since 1.2 */ public final static int IGNORE_ALL_BEANINFO = 3; @@ -214,6 +219,7 @@ public class Introspector { * @return A BeanInfo object describing the target bean. * @exception IntrospectionException if an exception occurs during * introspection. + * @since 1.2 */ public static BeanInfo getBeanInfo(Class beanClass, int flags) throws IntrospectionException { @@ -354,6 +360,8 @@ public class Introspector { * not normally required. It is normally only needed by advanced * tools that update existing "Class" objects in-place and need * to make the Introspector re-analyze existing Class objects. + * + * @since 1.2 */ public static void flushCaches() { @@ -377,6 +385,7 @@ public class Introspector { * * @param clz Class object to be flushed. * @throws NullPointerException If the Class object is null. + * @since 1.2 */ public static void flushFromCaches(Class clz) { if (clz == null) { @@ -1384,7 +1393,7 @@ public class Introspector { * parameter list on a given class. */ private static Method internalFindMethod(Class start, String methodName, - int argCount, Class args[]) { + int argCount, Class args[]) { // For overriden methods we need to find the most derived version. // So we start with the given class and walk up the superclass chain. @@ -1426,7 +1435,7 @@ public class Introspector { // Now check any inherited interfaces. This is necessary both when // the argument class is itself an interface, and when the argument // class is an abstract class. - Class ifcs[] = start.getInterfaces(); + Class[] ifcs = start.getInterfaces(); for (int i = 0 ; i < ifcs.length; i++) { // Note: The original implementation had both methods calling // the 3 arg method. This is preserved but perhaps it should @@ -1459,7 +1468,7 @@ public class Introspector { * @return the method or null if not found */ static Method findMethod(Class cls, String methodName, int argCount, - Class args[]) { + Class[] args) { if (methodName == null) { return null; } @@ -1502,7 +1511,7 @@ public class Introspector { * Return true iff the given method throws the given exception. */ private boolean throwsException(Method method, Class exception) { - Class exs[] = method.getExceptionTypes(); + Class[] exs = method.getExceptionTypes(); for (int i = 0; i < exs.length; i++) { if (exs[i] == exception) { return true; diff --git a/jdk/src/share/classes/java/beans/MetaData.java b/jdk/src/share/classes/java/beans/MetaData.java index 3ae1e0375f9..d0e7108179d 100644 --- a/jdk/src/share/classes/java/beans/MetaData.java +++ b/jdk/src/share/classes/java/beans/MetaData.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1401,7 +1401,7 @@ static final class sun_swing_PrintColorUIResource_PersistenceDelegate extends Pe } private static boolean isValid(Constructor constructor, String[] names) { - Class[] parameters = constructor.getParameterTypes(); + Class[] parameters = constructor.getParameterTypes(); if (names.length != parameters.length) { return false; } diff --git a/jdk/src/share/classes/java/beans/MethodDescriptor.java b/jdk/src/share/classes/java/beans/MethodDescriptor.java index 1e169046746..ca295be74dc 100644 --- a/jdk/src/share/classes/java/beans/MethodDescriptor.java +++ b/jdk/src/share/classes/java/beans/MethodDescriptor.java @@ -34,6 +34,8 @@ import java.util.ArrayList; /** * A MethodDescriptor describes a particular method that a Java Bean * supports for external access from other components. + * + * @since 1.1 */ public class MethodDescriptor extends FeatureDescriptor { diff --git a/jdk/src/share/classes/java/beans/ParameterDescriptor.java b/jdk/src/share/classes/java/beans/ParameterDescriptor.java index 3b7013f4ad0..243df016ea0 100644 --- a/jdk/src/share/classes/java/beans/ParameterDescriptor.java +++ b/jdk/src/share/classes/java/beans/ParameterDescriptor.java @@ -32,6 +32,8 @@ package java.beans; * class. *

    * Currently all our state comes from the FeatureDescriptor base class. + * + * @since 1.1 */ public class ParameterDescriptor extends FeatureDescriptor { diff --git a/jdk/src/share/classes/java/beans/PropertyChangeEvent.java b/jdk/src/share/classes/java/beans/PropertyChangeEvent.java index eeaa6512730..ec7d8ed51c0 100644 --- a/jdk/src/share/classes/java/beans/PropertyChangeEvent.java +++ b/jdk/src/share/classes/java/beans/PropertyChangeEvent.java @@ -43,6 +43,8 @@ import java.util.EventObject; * An event source may send a null object as the name to indicate that an * arbitrary set of if its properties have changed. In this case the * old and new values should also be null. + * + * @since 1.1 */ public class PropertyChangeEvent extends EventObject { private static final long serialVersionUID = 7042693688939648123L; diff --git a/jdk/src/share/classes/java/beans/PropertyChangeListener.java b/jdk/src/share/classes/java/beans/PropertyChangeListener.java index 5b78d482439..70d50a85caf 100644 --- a/jdk/src/share/classes/java/beans/PropertyChangeListener.java +++ b/jdk/src/share/classes/java/beans/PropertyChangeListener.java @@ -29,6 +29,7 @@ package java.beans; * A "PropertyChange" event gets fired whenever a bean changes a "bound" * property. You can register a PropertyChangeListener with a source * bean so as to be notified of any bound property updates. + * @since 1.1 */ public interface PropertyChangeListener extends java.util.EventListener { diff --git a/jdk/src/share/classes/java/beans/PropertyChangeSupport.java b/jdk/src/share/classes/java/beans/PropertyChangeSupport.java index d55ae76efc8..40e58ae1e5d 100644 --- a/jdk/src/share/classes/java/beans/PropertyChangeSupport.java +++ b/jdk/src/share/classes/java/beans/PropertyChangeSupport.java @@ -77,6 +77,7 @@ import java.util.Map.Entry; * non-serializable listeners will be skipped during serialization. * * @see VetoableChangeSupport + * @since 1.1 */ public class PropertyChangeSupport implements Serializable { private PropertyChangeListenerMap map = new PropertyChangeListenerMap(); @@ -191,6 +192,7 @@ public class PropertyChangeSupport implements Serializable { * * @param propertyName The name of the property to listen on. * @param listener The PropertyChangeListener to be added + * @since 1.2 */ public void addPropertyChangeListener( String propertyName, @@ -216,6 +218,7 @@ public class PropertyChangeSupport implements Serializable { * * @param propertyName The name of the property that was listened on. * @param listener The PropertyChangeListener to be removed + * @since 1.2 */ public void removePropertyChangeListener( String propertyName, @@ -277,6 +280,7 @@ public class PropertyChangeSupport implements Serializable { * @param propertyName the programmatic name of the property that was changed * @param oldValue the old value of the property * @param newValue the new value of the property + * @since 1.2 */ public void firePropertyChange(String propertyName, int oldValue, int newValue) { if (oldValue != newValue) { @@ -297,6 +301,7 @@ public class PropertyChangeSupport implements Serializable { * @param propertyName the programmatic name of the property that was changed * @param oldValue the old value of the property * @param newValue the new value of the property + * @since 1.2 */ public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { if (oldValue != newValue) { @@ -312,6 +317,7 @@ public class PropertyChangeSupport implements Serializable { * No event is fired if the given event's old and new values are equal and non-null. * * @param event the {@code PropertyChangeEvent} to be fired + * @since 1.2 */ public void firePropertyChange(PropertyChangeEvent event) { Object oldValue = event.getOldValue(); @@ -410,6 +416,7 @@ public class PropertyChangeSupport implements Serializable { * * @param propertyName the property name. * @return true if there are one or more listeners for the given property + * @since 1.2 */ public boolean hasListeners(String propertyName) { return this.map.hasListeners(propertyName); diff --git a/jdk/src/share/classes/java/beans/PropertyDescriptor.java b/jdk/src/share/classes/java/beans/PropertyDescriptor.java index 07149f9752d..9f26590418f 100644 --- a/jdk/src/share/classes/java/beans/PropertyDescriptor.java +++ b/jdk/src/share/classes/java/beans/PropertyDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ import java.lang.reflect.Constructor; /** * A PropertyDescriptor describes one property that a Java Bean * exports via a pair of accessor methods. + * @since 1.1 */ public class PropertyDescriptor extends FeatureDescriptor { @@ -112,7 +113,7 @@ public class PropertyDescriptor extends FeatureDescriptor { // If this class or one of its base classes allow PropertyChangeListener, // then we assume that any properties we discover are "bound". // See Introspector.getTargetPropertyInfo() method. - Class[] args = { PropertyChangeListener.class }; + Class[] args = { PropertyChangeListener.class }; this.bound = null != Introspector.findMethod(beanClass, "addPropertyChangeListener", args.length, args); } @@ -244,6 +245,7 @@ public class PropertyDescriptor extends FeatureDescriptor { * * @param readMethod The new read method. * @throws IntrospectionException if the read method is invalid + * @since 1.2 */ public synchronized void setReadMethod(Method readMethod) throws IntrospectionException { @@ -314,6 +316,7 @@ public class PropertyDescriptor extends FeatureDescriptor { * * @param writeMethod The new write method. * @throws IntrospectionException if the write method is invalid + * @since 1.2 */ public synchronized void setWriteMethod(Method writeMethod) throws IntrospectionException { diff --git a/jdk/src/share/classes/java/beans/PropertyEditor.java b/jdk/src/share/classes/java/beans/PropertyEditor.java index 041cb805d9e..69ad2c04074 100644 --- a/jdk/src/share/classes/java/beans/PropertyEditor.java +++ b/jdk/src/share/classes/java/beans/PropertyEditor.java @@ -51,6 +51,8 @@ package java.beans; * or support setAsText. *

    * Each PropertyEditor should have a null constructor. + * + * @since 1.1 */ public interface PropertyEditor { diff --git a/jdk/src/share/classes/java/beans/PropertyEditorManager.java b/jdk/src/share/classes/java/beans/PropertyEditorManager.java index 46ec87de944..ae664b8c4cc 100644 --- a/jdk/src/share/classes/java/beans/PropertyEditorManager.java +++ b/jdk/src/share/classes/java/beans/PropertyEditorManager.java @@ -48,6 +48,8 @@ package java.beans; * Default PropertyEditors will be provided for the Java primitive types * "boolean", "byte", "short", "int", "long", "float", and "double"; and * for the classes java.lang.String. java.awt.Color, and java.awt.Font. + * + * @since 1.1 */ public class PropertyEditorManager { diff --git a/jdk/src/share/classes/java/beans/PropertyEditorSupport.java b/jdk/src/share/classes/java/beans/PropertyEditorSupport.java index 1569c652e97..cfc350fbb20 100644 --- a/jdk/src/share/classes/java/beans/PropertyEditorSupport.java +++ b/jdk/src/share/classes/java/beans/PropertyEditorSupport.java @@ -31,6 +31,8 @@ import java.beans.*; * This is a support class to help build property editors. *

    * It can be used either as a base class or as a delegate. + * + * @since 1.1 */ public class PropertyEditorSupport implements PropertyEditor { diff --git a/jdk/src/share/classes/java/beans/PropertyVetoException.java b/jdk/src/share/classes/java/beans/PropertyVetoException.java index 27a2f82f341..86220b18785 100644 --- a/jdk/src/share/classes/java/beans/PropertyVetoException.java +++ b/jdk/src/share/classes/java/beans/PropertyVetoException.java @@ -29,6 +29,7 @@ package java.beans; /** * A PropertyVetoException is thrown when a proposed change to a * property represents an unacceptable value. + * @since 1.1 */ public diff --git a/jdk/src/share/classes/java/beans/SimpleBeanInfo.java b/jdk/src/share/classes/java/beans/SimpleBeanInfo.java index 29fd9cc4b5a..7b97e414ebb 100644 --- a/jdk/src/share/classes/java/beans/SimpleBeanInfo.java +++ b/jdk/src/share/classes/java/beans/SimpleBeanInfo.java @@ -34,6 +34,8 @@ package java.beans; * When the introspector sees the "noop" values, it will apply low * level introspection and design patterns to automatically analyze * the target bean. + * + * @since 1.1 */ public class SimpleBeanInfo implements BeanInfo { diff --git a/jdk/src/share/classes/java/beans/Statement.java b/jdk/src/share/classes/java/beans/Statement.java index d1e6717817f..fc11a42be12 100644 --- a/jdk/src/share/classes/java/beans/Statement.java +++ b/jdk/src/share/classes/java/beans/Statement.java @@ -248,7 +248,7 @@ public class Statement { // ignored elsewhere. if (target == Character.class && arguments.length == 1 && argClasses[0] == String.class) { - return new Character(((String)arguments[0]).charAt(0)); + return ((String)arguments[0]).charAt(0); } try { m = ConstructorFinder.findConstructor((Class)target, argClasses); diff --git a/jdk/src/share/classes/java/beans/VetoableChangeListener.java b/jdk/src/share/classes/java/beans/VetoableChangeListener.java index 898fd82fb4b..9edc175375d 100644 --- a/jdk/src/share/classes/java/beans/VetoableChangeListener.java +++ b/jdk/src/share/classes/java/beans/VetoableChangeListener.java @@ -29,6 +29,7 @@ package java.beans; * A VetoableChange event gets fired whenever a bean changes a "constrained" * property. You can register a VetoableChangeListener with a source bean * so as to be notified of any constrained property updates. + * @since 1.1 */ public interface VetoableChangeListener extends java.util.EventListener { /** diff --git a/jdk/src/share/classes/java/beans/VetoableChangeSupport.java b/jdk/src/share/classes/java/beans/VetoableChangeSupport.java index 293ae5af2c6..14902cc6276 100644 --- a/jdk/src/share/classes/java/beans/VetoableChangeSupport.java +++ b/jdk/src/share/classes/java/beans/VetoableChangeSupport.java @@ -77,6 +77,7 @@ import java.util.Map.Entry; * non-serializable listeners will be skipped during serialization. * * @see PropertyChangeSupport + * @since 1.1 */ public class VetoableChangeSupport implements Serializable { private VetoableChangeListenerMap map = new VetoableChangeListenerMap(); @@ -191,6 +192,7 @@ public class VetoableChangeSupport implements Serializable { * * @param propertyName The name of the property to listen on. * @param listener The VetoableChangeListener to be added + * @since 1.2 */ public void addVetoableChangeListener( String propertyName, @@ -216,6 +218,7 @@ public class VetoableChangeSupport implements Serializable { * * @param propertyName The name of the property that was listened on. * @param listener The VetoableChangeListener to be removed + * @since 1.2 */ public void removeVetoableChangeListener( String propertyName, @@ -292,6 +295,7 @@ public class VetoableChangeSupport implements Serializable { * @param oldValue the old value of the property * @param newValue the new value of the property * @throws PropertyVetoException if one of listeners vetoes the property update + * @since 1.2 */ public void fireVetoableChange(String propertyName, int oldValue, int newValue) throws PropertyVetoException { @@ -320,6 +324,7 @@ public class VetoableChangeSupport implements Serializable { * @param oldValue the old value of the property * @param newValue the new value of the property * @throws PropertyVetoException if one of listeners vetoes the property update + * @since 1.2 */ public void fireVetoableChange(String propertyName, boolean oldValue, boolean newValue) throws PropertyVetoException { @@ -343,6 +348,7 @@ public class VetoableChangeSupport implements Serializable { * * @param event the {@code PropertyChangeEvent} to be fired * @throws PropertyVetoException if one of listeners vetoes the property update + * @since 1.2 */ public void fireVetoableChange(PropertyChangeEvent event) throws PropertyVetoException { @@ -399,6 +405,7 @@ public class VetoableChangeSupport implements Serializable { * * @param propertyName the property name. * @return true if there are one or more listeners for the given property + * @since 1.2 */ public boolean hasListeners(String propertyName) { return this.map.hasListeners(propertyName); diff --git a/jdk/src/share/classes/java/beans/Visibility.java b/jdk/src/share/classes/java/beans/Visibility.java index af413833879..5aab3f3afe7 100644 --- a/jdk/src/share/classes/java/beans/Visibility.java +++ b/jdk/src/share/classes/java/beans/Visibility.java @@ -34,6 +34,8 @@ package java.beans; * This interface is for expert developers, and is not needed * for normal simple beans. To avoid confusing end-users we * avoid using getXXX setXXX design patterns for these methods. + * + * @since 1.1 */ public interface Visibility { diff --git a/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceAvailableEvent.java b/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceAvailableEvent.java index c1034ef73cc..24eb66aa96f 100644 --- a/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceAvailableEvent.java +++ b/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceAvailableEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -47,7 +47,7 @@ public class BeanContextServiceAvailableEvent extends BeanContextEvent { * @param bcs The context in which the service has become available * @param sc A Class reference to the newly available service */ - public BeanContextServiceAvailableEvent(BeanContextServices bcs, Class sc) { + public BeanContextServiceAvailableEvent(BeanContextServices bcs, Class sc) { super((BeanContext)bcs); serviceClass = sc; @@ -65,13 +65,13 @@ public class BeanContextServiceAvailableEvent extends BeanContextEvent { * Gets the service class that is the subject of this notification. * @return A Class reference to the newly available service */ - public Class getServiceClass() { return serviceClass; } + public Class getServiceClass() { return serviceClass; } /** * Gets the list of service dependent selectors. * @return the current selectors available from the service */ - public Iterator getCurrentServiceSelectors() { + public Iterator getCurrentServiceSelectors() { return ((BeanContextServices)getSource()).getCurrentServiceSelectors(serviceClass); } @@ -82,5 +82,5 @@ public class BeanContextServiceAvailableEvent extends BeanContextEvent { /** * A Class reference to the newly available service */ - protected Class serviceClass; + protected Class serviceClass; } diff --git a/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceProvider.java b/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceProvider.java index 5e724ca325f..104051e3952 100644 --- a/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceProvider.java +++ b/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -70,7 +70,7 @@ public interface BeanContextServiceProvider { * * @return a reference to the requested service */ - Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector); + Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector); /** * Invoked by BeanContextServices, @@ -100,5 +100,5 @@ public interface BeanContextServiceProvider { * @param serviceClass the specified service * @return the current service selectors for the specified serviceClass */ - Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass); + Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass); } diff --git a/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceRevokedEvent.java b/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceRevokedEvent.java index 30d99862903..b886e30a86f 100644 --- a/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceRevokedEvent.java +++ b/jdk/src/share/classes/java/beans/beancontext/BeanContextServiceRevokedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,7 +46,7 @@ public class BeanContextServiceRevokedEvent extends BeanContextEvent { * @param sc the service that is being revoked * @param invalidate true for immediate revocation */ - public BeanContextServiceRevokedEvent(BeanContextServices bcs, Class sc, boolean invalidate) { + public BeanContextServiceRevokedEvent(BeanContextServices bcs, Class sc, boolean invalidate) { super((BeanContext)bcs); serviceClass = sc; @@ -67,7 +67,7 @@ public class BeanContextServiceRevokedEvent extends BeanContextEvent { * @return A Class reference to the * service that is being revoked */ - public Class getServiceClass() { return serviceClass; } + public Class getServiceClass() { return serviceClass; } /** * Checks this event to determine whether or not @@ -76,7 +76,7 @@ public class BeanContextServiceRevokedEvent extends BeanContextEvent { * @return true if the service being revoked is of the * same class as the specified service */ - public boolean isServiceClass(Class service) { + public boolean isServiceClass(Class service) { return serviceClass.equals(service); } @@ -94,6 +94,6 @@ public class BeanContextServiceRevokedEvent extends BeanContextEvent { /** * A Class reference to the service that is being revoked. */ - protected Class serviceClass; + protected Class serviceClass; private boolean invalidateRefs; } diff --git a/jdk/src/share/classes/java/beans/beancontext/BeanContextServices.java b/jdk/src/share/classes/java/beans/beancontext/BeanContextServices.java index 0348817bfe8..62652ec5443 100644 --- a/jdk/src/share/classes/java/beans/beancontext/BeanContextServices.java +++ b/jdk/src/share/classes/java/beans/beancontext/BeanContextServices.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -62,7 +62,7 @@ public interface BeanContextServices extends BeanContext, BeanContextServicesLis * associated with the service * @return true if the service was successful added, false otherwise */ - boolean addService(Class serviceClass, BeanContextServiceProvider serviceProvider); + boolean addService(Class serviceClass, BeanContextServiceProvider serviceProvider); /** * BeanContextServiceProviders wishing to remove @@ -83,7 +83,7 @@ public interface BeanContextServices extends BeanContext, BeanContextServicesLis * terminate service to all currently outstanding references * to the specified service. */ - void revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow); + void revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow); /** * Reports whether or not a given service is @@ -91,7 +91,7 @@ public interface BeanContextServices extends BeanContext, BeanContextServicesLis * @param serviceClass the service in question * @return true if the service is available */ - boolean hasService(Class serviceClass); + boolean hasService(Class serviceClass); /** * A BeanContextChild, or any arbitrary object @@ -113,7 +113,7 @@ public interface BeanContextServices extends BeanContext, BeanContextServicesLis * @return a reference to this context's named * Service as requested or null */ - Object getService(BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException; + Object getService(BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException; /** * Releases a BeanContextChild's @@ -131,7 +131,7 @@ public interface BeanContextServices extends BeanContext, BeanContextServicesLis * @return an Iterator consisting of the * currently available services */ - Iterator getCurrentServiceClasses(); + Iterator getCurrentServiceClasses(); /** * Gets the list of service dependent service parameters @@ -142,7 +142,7 @@ public interface BeanContextServices extends BeanContext, BeanContextServicesLis * @return the currently available service selectors * for the named serviceClass */ - Iterator getCurrentServiceSelectors(Class serviceClass); + Iterator getCurrentServiceSelectors(Class serviceClass); /** * Adds a BeanContextServicesListener to this BeanContext diff --git a/jdk/src/share/classes/java/beans/beancontext/BeanContextServicesSupport.java b/jdk/src/share/classes/java/beans/beancontext/BeanContextServicesSupport.java index 41cfa9d7a89..507e8ec0215 100644 --- a/jdk/src/share/classes/java/beans/beancontext/BeanContextServicesSupport.java +++ b/jdk/src/share/classes/java/beans/beancontext/BeanContextServicesSupport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -129,9 +129,8 @@ public class BeanContextServicesSupport extends BeanContextSupport public void initialize() { super.initialize(); - - services = new HashMap(serializable + 1); - bcsListeners = new ArrayList(1); + services = new HashMap<>(serializable + 1); + bcsListeners = new ArrayList<>(1); } /** @@ -169,7 +168,7 @@ public class BeanContextServicesSupport extends BeanContextSupport // create an instance of a service ref - BCSSCServiceClassRef(Class sc, BeanContextServiceProvider bcsp, boolean delegated) { + BCSSCServiceClassRef(Class sc, BeanContextServiceProvider bcsp, boolean delegated) { super(); serviceClass = sc; @@ -183,7 +182,7 @@ public class BeanContextServicesSupport extends BeanContextSupport // add a requestor and assoc listener void addRequestor(Object requestor, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { - BeanContextServiceRevokedListener cbcsrl = (BeanContextServiceRevokedListener)requestors.get(requestor); + BeanContextServiceRevokedListener cbcsrl = requestors.get(requestor); if (cbcsrl != null && !cbcsrl.equals(bcsrl)) throw new TooManyListenersException(); @@ -200,7 +199,7 @@ public class BeanContextServicesSupport extends BeanContextSupport // check a requestors listener void verifyRequestor(Object requestor, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { - BeanContextServiceRevokedListener cbcsrl = (BeanContextServiceRevokedListener)requestors.get(requestor); + BeanContextServiceRevokedListener cbcsrl = requestors.get(requestor); if (cbcsrl != null && !cbcsrl.equals(bcsrl)) throw new TooManyListenersException(); @@ -230,15 +229,18 @@ public class BeanContextServicesSupport extends BeanContextSupport } - Iterator cloneOfEntries() { - return ((HashMap)requestors.clone()).entrySet().iterator(); + @SuppressWarnings("unchecked") // Cast from clone + Iterator> cloneOfEntries() { + return ((HashMap)requestors.clone()).entrySet().iterator(); } - Iterator entries() { return requestors.entrySet().iterator(); } + Iterator> entries() { + return requestors.entrySet().iterator(); + } boolean isEmpty() { return requestors.isEmpty(); } - Class getServiceClass() { return serviceClass; } + Class getServiceClass() { return serviceClass; } BeanContextServiceProvider getServiceProvider() { return serviceProvider; @@ -281,7 +283,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * fields */ - Class serviceClass; + Class serviceClass; BeanContextServiceProvider serviceProvider; int serviceRefs; @@ -289,7 +291,7 @@ public class BeanContextServicesSupport extends BeanContextSupport BeanContextServiceProvider delegateProvider; // proxy int delegateRefs; - HashMap requestors = new HashMap(1); + HashMap requestors = new HashMap<>(1); } /* @@ -322,16 +324,16 @@ public class BeanContextServicesSupport extends BeanContextSupport // note usage of service per requestor, per service - synchronized void usingService(Object requestor, Object service, Class serviceClass, BeanContextServiceProvider bcsp, boolean isDelegated, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException, UnsupportedOperationException { + synchronized void usingService(Object requestor, Object service, Class serviceClass, BeanContextServiceProvider bcsp, boolean isDelegated, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException, UnsupportedOperationException { // first, process mapping from serviceClass to requestor(s) BCSSCServiceClassRef serviceClassRef = null; if (serviceClasses == null) - serviceClasses = new HashMap(1); + serviceClasses = new HashMap<>(1); else - serviceClassRef = (BCSSCServiceClassRef)serviceClasses.get(serviceClass); + serviceClassRef = serviceClasses.get(serviceClass); if (serviceClassRef == null) { // new service being used ... serviceClassRef = new BCSSCServiceClassRef(serviceClass, bcsp, isDelegated); @@ -348,20 +350,20 @@ public class BeanContextServicesSupport extends BeanContextSupport // now handle mapping from requestor to service(s) BCSSCServiceRef serviceRef = null; - Map services = null; + Map services = null; if (serviceRequestors == null) { - serviceRequestors = new HashMap(1); + serviceRequestors = new HashMap<>(1); } else { - services = (Map)serviceRequestors.get(requestor); + services = serviceRequestors.get(requestor); } if (services == null) { - services = new HashMap(1); + services = new HashMap<>(1); serviceRequestors.put(requestor, services); } else - serviceRef = (BCSSCServiceRef)services.get(service); + serviceRef = services.get(service); if (serviceRef == null) { serviceRef = new BCSSCServiceRef(serviceClassRef, isDelegated); @@ -377,11 +379,11 @@ public class BeanContextServicesSupport extends BeanContextSupport synchronized void releaseService(Object requestor, Object service) { if (serviceRequestors == null) return; - Map services = (Map)serviceRequestors.get(requestor); + Map services = serviceRequestors.get(requestor); if (services == null) return; // oops its not there anymore! - BCSSCServiceRef serviceRef = (BCSSCServiceRef)services.get(service); + BCSSCServiceRef serviceRef = services.get(service); if (serviceRef == null) return; // oops its not there anymore! @@ -418,33 +420,33 @@ public class BeanContextServicesSupport extends BeanContextSupport // revoke a service - synchronized void revokeService(Class serviceClass, boolean isDelegated, boolean revokeNow) { + synchronized void revokeService(Class serviceClass, boolean isDelegated, boolean revokeNow) { if (serviceClasses == null) return; - BCSSCServiceClassRef serviceClassRef = (BCSSCServiceClassRef)serviceClasses.get(serviceClass); + BCSSCServiceClassRef serviceClassRef = serviceClasses.get(serviceClass); if (serviceClassRef == null) return; - Iterator i = serviceClassRef.cloneOfEntries(); + Iterator> i = serviceClassRef.cloneOfEntries(); BeanContextServiceRevokedEvent bcsre = new BeanContextServiceRevokedEvent(BeanContextServicesSupport.this.getBeanContextServicesPeer(), serviceClass, revokeNow); boolean noMoreRefs = false; while (i.hasNext() && serviceRequestors != null) { - Map.Entry entry = (Map.Entry)i.next(); - BeanContextServiceRevokedListener listener = (BeanContextServiceRevokedListener)entry.getValue(); + Map.Entry entry = i.next(); + BeanContextServiceRevokedListener listener = entry.getValue(); if (revokeNow) { Object requestor = entry.getKey(); - Map services = (Map)serviceRequestors.get(requestor); + Map services = serviceRequestors.get(requestor); if (services != null) { - Iterator i1 = services.entrySet().iterator(); + Iterator> i1 = services.entrySet().iterator(); while (i1.hasNext()) { - Map.Entry tmp = (Map.Entry)i1.next(); + Map.Entry tmp = i1.next(); - BCSSCServiceRef serviceRef = (BCSSCServiceRef)tmp.getValue(); + BCSSCServiceRef serviceRef = tmp.getValue(); if (serviceRef.getServiceClassRef().equals(serviceClassRef) && isDelegated == serviceRef.isDelegated()) { i1.remove(); } @@ -479,19 +481,19 @@ public class BeanContextServicesSupport extends BeanContextSupport if (serviceRequestors == null) return; - Iterator requestors = serviceRequestors.entrySet().iterator(); + Iterator>> requestors = serviceRequestors.entrySet().iterator(); while(requestors.hasNext()) { - Map.Entry tmp = (Map.Entry)requestors.next(); + Map.Entry> tmp = requestors.next(); Object requestor = tmp.getKey(); - Iterator services = ((Map)tmp.getValue()).entrySet().iterator(); + Iterator> services = tmp.getValue().entrySet().iterator(); requestors.remove(); while (services.hasNext()) { - Map.Entry entry = (Map.Entry)services.next(); + Map.Entry entry = services.next(); Object service = entry.getKey(); - BCSSCServiceRef sref = (BCSSCServiceRef)entry.getValue(); + BCSSCServiceRef sref = entry.getValue(); BCSSCServiceClassRef scref = sref.getServiceClassRef(); @@ -513,32 +515,32 @@ public class BeanContextServicesSupport extends BeanContextSupport void revokeAllDelegatedServicesNow() { if (serviceClasses == null) return; - Iterator serviceClassRefs = - new HashSet(serviceClasses.values()).iterator(); + Iterator serviceClassRefs = + new HashSet<>(serviceClasses.values()).iterator(); while (serviceClassRefs.hasNext()) { - BCSSCServiceClassRef serviceClassRef = (BCSSCServiceClassRef)serviceClassRefs.next(); + BCSSCServiceClassRef serviceClassRef = serviceClassRefs.next(); if (!serviceClassRef.isDelegated()) continue; - Iterator i = serviceClassRef.cloneOfEntries(); + Iterator> i = serviceClassRef.cloneOfEntries(); BeanContextServiceRevokedEvent bcsre = new BeanContextServiceRevokedEvent(BeanContextServicesSupport.this.getBeanContextServicesPeer(), serviceClassRef.getServiceClass(), true); boolean noMoreRefs = false; while (i.hasNext()) { - Map.Entry entry = (Map.Entry)i.next(); - BeanContextServiceRevokedListener listener = (BeanContextServiceRevokedListener)entry.getValue(); + Map.Entry entry = i.next(); + BeanContextServiceRevokedListener listener = entry.getValue(); Object requestor = entry.getKey(); - Map services = (Map)serviceRequestors.get(requestor); + Map services = serviceRequestors.get(requestor); if (services != null) { - Iterator i1 = services.entrySet().iterator(); + Iterator> i1 = services.entrySet().iterator(); while (i1.hasNext()) { - Map.Entry tmp = (Map.Entry)i1.next(); + Map.Entry tmp = i1.next(); - BCSSCServiceRef serviceRef = (BCSSCServiceRef)tmp.getValue(); + BCSSCServiceRef serviceRef = tmp.getValue(); if (serviceRef.getServiceClassRef().equals(serviceClassRef) && serviceRef.isDelegated()) { i1.remove(); } @@ -568,8 +570,8 @@ public class BeanContextServicesSupport extends BeanContextSupport * fields */ - private transient HashMap serviceClasses; - private transient HashMap serviceRequestors; + private transient HashMap, BCSSCServiceClassRef> serviceClasses; + private transient HashMap> serviceRequestors; } /** @@ -597,7 +599,7 @@ public class BeanContextServicesSupport extends BeanContextSupport protected static class BCSSServiceProvider implements Serializable { private static final long serialVersionUID = 861278251667444782L; - BCSSServiceProvider(Class sc, BeanContextServiceProvider bcsp) { + BCSSServiceProvider(Class sc, BeanContextServiceProvider bcsp) { super(); serviceProvider = bcsp; @@ -627,7 +629,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * @return a service provider without overriding addService() */ - protected BCSSServiceProvider createBCSSServiceProvider(Class sc, BeanContextServiceProvider bcsp) { + protected BCSSServiceProvider createBCSSServiceProvider(Class sc, BeanContextServiceProvider bcsp) { return new BCSSServiceProvider(sc, bcsp); } @@ -671,7 +673,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * @param bcsp the service provider */ - public boolean addService(Class serviceClass, BeanContextServiceProvider bcsp) { + public boolean addService(Class serviceClass, BeanContextServiceProvider bcsp) { return addService(serviceClass, bcsp, true); } @@ -683,7 +685,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * @return true if the service was successfully added */ - protected boolean addService(Class serviceClass, BeanContextServiceProvider bcsp, boolean fireEvent) { + protected boolean addService(Class serviceClass, BeanContextServiceProvider bcsp, boolean fireEvent) { if (serviceClass == null) throw new NullPointerException("serviceClass"); if (bcsp == null) throw new NullPointerException("bcsp"); @@ -704,7 +706,7 @@ public class BeanContextServicesSupport extends BeanContextSupport fireServiceAdded(bcssae); synchronized(children) { - Iterator i = children.keySet().iterator(); + Iterator i = children.keySet().iterator(); while (i.hasNext()) { Object c = i.next(); @@ -727,7 +729,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * @param revokeCurrentServicesNow whether or not to revoke the service */ - public void revokeService(Class serviceClass, BeanContextServiceProvider bcsp, boolean revokeCurrentServicesNow) { + public void revokeService(Class serviceClass, BeanContextServiceProvider bcsp, boolean revokeCurrentServicesNow) { if (serviceClass == null) throw new NullPointerException("serviceClass"); if (bcsp == null) throw new NullPointerException("bcsp"); @@ -735,7 +737,7 @@ public class BeanContextServicesSupport extends BeanContextSupport synchronized(BeanContext.globalHierarchyLock) { if (!services.containsKey(serviceClass)) return; - BCSSServiceProvider bcsssp = (BCSSServiceProvider)services.get(serviceClass); + BCSSServiceProvider bcsssp = services.get(serviceClass); if (!bcsssp.getServiceProvider().equals(bcsp)) throw new IllegalArgumentException("service provider mismatch"); @@ -744,7 +746,7 @@ public class BeanContextServicesSupport extends BeanContextSupport if (bcsp instanceof Serializable) serializable--; - Iterator i = bcsChildren(); // get the BCSChild values. + Iterator i = bcsChildren(); // get the BCSChild values. while (i.hasNext()) { ((BCSSChild)i.next()).revokeService(serviceClass, false, revokeCurrentServicesNow); @@ -758,7 +760,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * has a service, which may be delegated */ - public synchronized boolean hasService(Class serviceClass) { + public synchronized boolean hasService(Class serviceClass) { if (serviceClass == null) throw new NullPointerException("serviceClass"); synchronized(BeanContext.globalHierarchyLock) { @@ -791,7 +793,7 @@ public class BeanContextServicesSupport extends BeanContextSupport nestingCtxt = bcs; } - public Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector) { + public Object getService(BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector) { Object service = null; try { @@ -807,12 +809,12 @@ public class BeanContextServicesSupport extends BeanContextSupport nestingCtxt.releaseService(bcs, requestor, service); } - public Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass) { + public Iterator getCurrentServiceSelectors(BeanContextServices bcs, Class serviceClass) { return nestingCtxt.getCurrentServiceSelectors(serviceClass); } public void serviceRevoked(BeanContextServiceRevokedEvent bcsre) { - Iterator i = bcsChildren(); // get the BCSChild values. + Iterator i = bcsChildren(); // get the BCSChild values. while (i.hasNext()) { ((BCSSChild)i.next()).revokeService(bcsre.getServiceClass(), true, bcsre.isCurrentServiceInvalidNow()); @@ -832,7 +834,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * obtain a service which may be delegated */ - public Object getService(BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { + public Object getService(BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) throws TooManyListenersException { if (child == null) throw new NullPointerException("child"); if (serviceClass == null) throw new NullPointerException("serviceClass"); if (requestor == null) throw new NullPointerException("requestor"); @@ -847,7 +849,7 @@ public class BeanContextServicesSupport extends BeanContextSupport if (bcsc == null) throw new IllegalArgumentException("not a child of this context"); // not a child ... - BCSSServiceProvider bcsssp = (BCSSServiceProvider)services.get(serviceClass); + BCSSServiceProvider bcsssp = services.get(serviceClass); if (bcsssp != null) { BeanContextServiceProvider bcsp = bcsssp.getServiceProvider(); @@ -918,7 +920,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * @return an iterator for all the currently registered service classes. */ - public Iterator getCurrentServiceClasses() { + public Iterator getCurrentServiceClasses() { return new BCSIterator(services.keySet().iterator()); } @@ -927,9 +929,9 @@ public class BeanContextServicesSupport extends BeanContextSupport * (if any) available for the specified service. */ - public Iterator getCurrentServiceSelectors(Class serviceClass) { + public Iterator getCurrentServiceSelectors(Class serviceClass) { - BCSSServiceProvider bcsssp = (BCSSServiceProvider)services.get(serviceClass); + BCSSServiceProvider bcsssp = services.get(serviceClass); return bcsssp != null ? new BCSIterator(bcsssp.getServiceProvider().getCurrentServiceSelectors(getBeanContextServicesPeer(), serviceClass)) : null; } @@ -950,7 +952,7 @@ public class BeanContextServicesSupport extends BeanContextSupport fireServiceAdded(bcssae); - Iterator i; + Iterator i; synchronized(children) { i = children.keySet().iterator(); @@ -982,7 +984,7 @@ public class BeanContextServicesSupport extends BeanContextSupport fireServiceRevoked(bcssre); - Iterator i; + Iterator i; synchronized(children) { i = children.keySet().iterator(); @@ -1085,7 +1087,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * Fires a BeanContextServiceEvent notifying of a new service. * @param serviceClass the service class */ - protected final void fireServiceAdded(Class serviceClass) { + protected final void fireServiceAdded(Class serviceClass) { BeanContextServiceAvailableEvent bcssae = new BeanContextServiceAvailableEvent(getBeanContextServicesPeer(), serviceClass); fireServiceAdded(bcssae); @@ -1129,7 +1131,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * @param serviceClass the service class * @param revokeNow whether or not the event should be revoked now */ - protected final void fireServiceRevoked(Class serviceClass, boolean revokeNow) { + protected final void fireServiceRevoked(Class serviceClass, boolean revokeNow) { Object[] copy; BeanContextServiceRevokedEvent bcsre = new BeanContextServiceRevokedEvent(getBeanContextServicesPeer(), serviceClass, revokeNow); @@ -1159,14 +1161,14 @@ public class BeanContextServicesSupport extends BeanContextSupport int count = 0; - Iterator i = services.entrySet().iterator(); + Iterator> i = services.entrySet().iterator(); while (i.hasNext() && count < serializable) { - Map.Entry entry = (Map.Entry)i.next(); + Map.Entry entry = i.next(); BCSSServiceProvider bcsp = null; try { - bcsp = (BCSSServiceProvider)entry.getValue(); + bcsp = entry.getValue(); } catch (ClassCastException cce) { continue; } @@ -1201,7 +1203,7 @@ public class BeanContextServicesSupport extends BeanContextSupport int count = serializable; while (count > 0) { - services.put(ois.readObject(), ois.readObject()); + services.put(ois.readObject(), (BCSSServiceProvider)ois.readObject()); count--; } } @@ -1236,7 +1238,7 @@ public class BeanContextServicesSupport extends BeanContextSupport * all accesses to the protected transient HashMap services * field should be synchronized on that object */ - protected transient HashMap services; + protected transient HashMap services; /** * The number of instances of a serializable BeanContextServceProvider. @@ -1253,5 +1255,5 @@ public class BeanContextServicesSupport extends BeanContextSupport /** * List of BeanContextServicesListener objects. */ - protected transient ArrayList bcsListeners; + protected transient ArrayList bcsListeners; } diff --git a/jdk/src/share/classes/java/beans/beancontext/BeanContextSupport.java b/jdk/src/share/classes/java/beans/beancontext/BeanContextSupport.java index e8cd43b6293..4845650e745 100644 --- a/jdk/src/share/classes/java/beans/beancontext/BeanContextSupport.java +++ b/jdk/src/share/classes/java/beans/beancontext/BeanContextSupport.java @@ -254,7 +254,7 @@ public class BeanContextSupport extends BeanContextChildSupport * currently nested in this BeanContext. * @return an Iterator of the nested children */ - public Iterator iterator() { + public Iterator iterator() { synchronized(children) { return new BCSIterator(children.keySet().iterator()); } @@ -292,14 +292,14 @@ public class BeanContextSupport extends BeanContextChildSupport * a noop remove() method. */ - protected static final class BCSIterator implements Iterator { - BCSIterator(Iterator i) { super(); src = i; } + protected static final class BCSIterator implements Iterator { + BCSIterator(Iterator i) { super(); src = i; } public boolean hasNext() { return src.hasNext(); } - public Object next() { return src.next(); } + public Object next() { return src.next(); } public void remove() { /* do nothing */ } - private Iterator src; + private Iterator src; } /************************************************************************/ @@ -504,7 +504,7 @@ public class BeanContextSupport extends BeanContextChildSupport throw new IllegalStateException(); } - BCSChild bcsc = (BCSChild)children.get(targetChild); + BCSChild bcsc = children.get(targetChild); BCSChild pbcsc = null; Object peer = null; @@ -533,7 +533,7 @@ public class BeanContextSupport extends BeanContextChildSupport children.remove(targetChild); if (bcsc.isProxyPeer()) { - pbcsc = (BCSChild)children.get(peer = bcsc.getProxyPeer()); + pbcsc = children.get(peer = bcsc.getProxyPeer()); children.remove(peer); } } @@ -566,9 +566,10 @@ public class BeanContextSupport extends BeanContextChildSupport * in the collection are children of * this BeanContext, false if not. */ + @SuppressWarnings("rawtypes") public boolean containsAll(Collection c) { synchronized(children) { - Iterator i = c.iterator(); + Iterator i = c.iterator(); while (i.hasNext()) if(!contains(i.next())) return false; @@ -583,6 +584,7 @@ public class BeanContextSupport extends BeanContextChildSupport * @throws UnsupportedOperationException thrown unconditionally by this implementation * @return this implementation unconditionally throws {@code UnsupportedOperationException} */ + @SuppressWarnings("rawtypes") public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } @@ -594,6 +596,7 @@ public class BeanContextSupport extends BeanContextChildSupport * @return this implementation unconditionally throws {@code UnsupportedOperationException} */ + @SuppressWarnings("rawtypes") public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } @@ -605,6 +608,7 @@ public class BeanContextSupport extends BeanContextChildSupport * @throws UnsupportedOperationException thrown unconditionally by this implementation * @return this implementation unconditionally throws {@code UnsupportedOperationException} */ + @SuppressWarnings("rawtypes") public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } @@ -763,7 +767,7 @@ public class BeanContextSupport extends BeanContextChildSupport } synchronized(children) { - for (Iterator i = children.keySet().iterator(); i.hasNext();) { + for (Iterator i = children.keySet().iterator(); i.hasNext();) { Object c = i.next(); try { @@ -790,7 +794,7 @@ public class BeanContextSupport extends BeanContextChildSupport // lets also tell the Children that can that they may not use their GUI's synchronized(children) { - for (Iterator i = children.keySet().iterator(); i.hasNext();) { + for (Iterator i = children.keySet().iterator(); i.hasNext();) { Visibility v = getChildVisibility(i.next()); if (v != null) v.dontUseGui(); @@ -809,7 +813,7 @@ public class BeanContextSupport extends BeanContextChildSupport // lets also tell the Children that can that they may use their GUI's synchronized(children) { - for (Iterator i = children.keySet().iterator(); i.hasNext();) { + for (Iterator i = children.keySet().iterator(); i.hasNext();) { Visibility v = getChildVisibility(i.next()); if (v != null) v.okToUseGui(); @@ -841,7 +845,7 @@ public class BeanContextSupport extends BeanContextChildSupport * of this BeanContext. * @return an iterator for all the current BCSChild values */ - protected Iterator bcsChildren() { synchronized(children) { return children.values().iterator(); } } + protected Iterator bcsChildren() { synchronized(children) { return children.values().iterator(); } } /** * called by writeObject after defaultWriteObject() but prior to @@ -896,7 +900,7 @@ public class BeanContextSupport extends BeanContextChildSupport * @param coll the Collection to serialize * @throws IOException if serialization failed */ - protected final void serialize(ObjectOutputStream oos, Collection coll) throws IOException { + protected final void serialize(ObjectOutputStream oos, Collection coll) throws IOException { int count = 0; Object[] objects = coll.toArray(); @@ -926,6 +930,7 @@ public class BeanContextSupport extends BeanContextChildSupport * @throws IOException if deserialization failed * @throws ClassNotFoundException if needed classes are not found */ + @SuppressWarnings({"rawtypes", "unchecked"}) protected final void deserialize(ObjectInputStream ois, Collection coll) throws IOException, ClassNotFoundException { int count = 0; @@ -953,10 +958,10 @@ public class BeanContextSupport extends BeanContextChildSupport int count = 0; synchronized(children) { - Iterator i = children.entrySet().iterator(); + Iterator> i = children.entrySet().iterator(); while (i.hasNext() && count < serializable) { - Map.Entry entry = (Map.Entry)i.next(); + Map.Entry entry = i.next(); if (entry.getKey() instanceof Serializable) { try { @@ -1082,7 +1087,7 @@ public class BeanContextSupport extends BeanContextChildSupport if (serializable > 0 && this.equals(getBeanContextPeer())) readChildren(ois); - deserialize(ois, bcmListeners = new ArrayList(1)); + deserialize(ois, bcmListeners = new ArrayList<>(1)); } } @@ -1101,7 +1106,7 @@ public class BeanContextSupport extends BeanContextChildSupport ) { if (!validatePendingRemove(source)) { throw new PropertyVetoException("current BeanContext vetoes setBeanContext()", pce); - } else ((BCSChild)children.get(source)).setRemovePending(true); + } else children.get(source).setRemovePending(true); } } } @@ -1117,13 +1122,13 @@ public class BeanContextSupport extends BeanContextChildSupport synchronized(children) { if ("beanContext".equals(propertyName) && containsKey(source) && - ((BCSChild)children.get(source)).isRemovePending()) { + children.get(source).isRemovePending()) { BeanContext bc = getBeanContextPeer(); if (bc.equals(pce.getOldValue()) && !bc.equals(pce.getNewValue())) { remove(source, false); } else { - ((BCSChild)children.get(source)).setRemovePending(false); + children.get(source).setRemovePending(false); } } } @@ -1312,8 +1317,8 @@ public class BeanContextSupport extends BeanContextChildSupport */ protected synchronized void initialize() { - children = new HashMap(serializable + 1); - bcmListeners = new ArrayList(1); + children = new HashMap<>(serializable + 1); + bcmListeners = new ArrayList<>(1); childPCL = new PropertyChangeListener() { @@ -1359,7 +1364,7 @@ public class BeanContextSupport extends BeanContextChildSupport * @param second the second object * @return true if equal, false if not */ - protected static final boolean classEquals(Class first, Class second) { + protected static final boolean classEquals(Class first, Class second) { return first.equals(second) || first.getName().equals(second.getName()); } @@ -1373,7 +1378,7 @@ public class BeanContextSupport extends BeanContextChildSupport * all accesses to the protected HashMap children field * shall be synchronized on that object. */ - protected transient HashMap children; + protected transient HashMap children; private int serializable = 0; // children serializable @@ -1381,7 +1386,7 @@ public class BeanContextSupport extends BeanContextChildSupport * all accesses to the protected ArrayList bcmListeners field * shall be synchronized on that object. */ - protected transient ArrayList bcmListeners; + protected transient ArrayList bcmListeners; // diff --git a/jdk/src/share/classes/java/io/File.java b/jdk/src/share/classes/java/io/File.java index f0528c73754..306cc84097d 100644 --- a/jdk/src/share/classes/java/io/File.java +++ b/jdk/src/share/classes/java/io/File.java @@ -1997,8 +1997,10 @@ public class File File directory) throws IOException { - if (prefix.length() < 3) - throw new IllegalArgumentException("Prefix string too short"); + if (prefix.length() < 3) { + throw new IllegalArgumentException("Prefix string \"" + prefix + + "\" too short: length must be at least 3"); + } if (suffix == null) suffix = ".tmp"; diff --git a/jdk/src/share/classes/java/lang/ClassLoader.java b/jdk/src/share/classes/java/lang/ClassLoader.java index 876b1855012..1652d6cc4eb 100644 --- a/jdk/src/share/classes/java/lang/ClassLoader.java +++ b/jdk/src/share/classes/java/lang/ClassLoader.java @@ -1859,18 +1859,17 @@ public abstract class ClassLoader { String name = NativeLibrary.findBuiltinLib(file.getName()); boolean isBuiltin = (name != null); if (!isBuiltin) { - boolean exists = AccessController.doPrivileged( - new PrivilegedAction() { - public Object run() { - return file.exists() ? Boolean.TRUE : null; - }}) - != null; - if (!exists) { - return false; - } - try { - name = file.getCanonicalPath(); - } catch (IOException e) { + name = AccessController.doPrivileged( + new PrivilegedAction() { + public String run() { + try { + return file.exists() ? file.getCanonicalPath() : null; + } catch (IOException e) { + return null; + } + } + }); + if (name == null) { return false; } } diff --git a/jdk/src/share/classes/java/lang/Package.java b/jdk/src/share/classes/java/lang/Package.java index f59176f558e..95abe98cd4b 100644 --- a/jdk/src/share/classes/java/lang/Package.java +++ b/jdk/src/share/classes/java/lang/Package.java @@ -107,6 +107,7 @@ import java.lang.annotation.Annotation; * loader to be found. * * @see ClassLoader#definePackage + * @since 1.2 */ public class Package implements java.lang.reflect.AnnotatedElement { /** diff --git a/jdk/src/share/classes/java/lang/SafeVarargs.java b/jdk/src/share/classes/java/lang/SafeVarargs.java index 6fcd48e97d7..9f49bf7a73f 100644 --- a/jdk/src/share/classes/java/lang/SafeVarargs.java +++ b/jdk/src/share/classes/java/lang/SafeVarargs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -45,7 +45,7 @@ import java.lang.annotation.*; *
  • the declaration is a fixed arity method or constructor * *
  • the declaration is a variable arity method that is neither - * {@code static} nor {@code final}. + * {@code static} nor {@code final} nor {@code private}. * * * diff --git a/jdk/src/share/classes/java/security/package-info.java b/jdk/src/share/classes/java/security/package-info.java index 599e95259ba..2c8205b09b9 100644 --- a/jdk/src/share/classes/java/security/package-info.java +++ b/jdk/src/share/classes/java/security/package-info.java @@ -92,14 +92,14 @@ *
  • * *
  • keytool - * ( + * ( * for Solaris/Linux) * ( * for Windows) *
  • * *
  • jarsigner - * ( + * ( * for Solaris/Linux) * ( * for Windows) diff --git a/jdk/src/share/classes/java/text/DecimalFormat.java b/jdk/src/share/classes/java/text/DecimalFormat.java index f89fd151749..a82011fd7d5 100644 --- a/jdk/src/share/classes/java/text/DecimalFormat.java +++ b/jdk/src/share/classes/java/text/DecimalFormat.java @@ -2094,7 +2094,7 @@ public class DecimalFormat extends NumberFormat { } return gotDouble ? - (Number)new Double(doubleResult) : (Number)new Long(longResult); + (Number)new Double(doubleResult) : (Number)Long.valueOf(longResult); } } diff --git a/jdk/src/share/classes/java/util/Collections.java b/jdk/src/share/classes/java/util/Collections.java index e229f5f5dd4..f6a65c7b106 100644 --- a/jdk/src/share/classes/java/util/Collections.java +++ b/jdk/src/share/classes/java/util/Collections.java @@ -3031,9 +3031,11 @@ public class Collections { final Collection c; final Class type; - void typeCheck(Object o) { + @SuppressWarnings("unchecked") + E typeCheck(Object o) { if (o != null && !type.isInstance(o)) throw new ClassCastException(badElementMsg(o)); + return (E) o; } private String badElementMsg(Object o) { @@ -3042,10 +3044,8 @@ public class Collections { } CheckedCollection(Collection c, Class type) { - if (c==null || type == null) - throw new NullPointerException(); - this.c = c; - this.type = type; + this.c = Objects.requireNonNull(c, "c"); + this.type = Objects.requireNonNull(type, "type"); } public int size() { return c.size(); } @@ -3077,10 +3077,7 @@ public class Collections { public void remove() { it.remove(); }}; } - public boolean add(E e) { - typeCheck(e); - return c.add(e); - } + public boolean add(E e) { return c.add(typeCheck(e)); } private E[] zeroLengthElementArray; // Lazily initialized @@ -3091,7 +3088,7 @@ public class Collections { @SuppressWarnings("unchecked") Collection checkedCopyOf(Collection coll) { - Object[] a = null; + Object[] a; try { E[] z = zeroLengthElementArray(); a = coll.toArray(z); @@ -3187,11 +3184,7 @@ public class Collections { public E peek() {return queue.peek();} public E poll() {return queue.poll();} public E remove() {return queue.remove();} - - public boolean offer(E e) { - typeCheck(e); - return add(e); - } + public boolean offer(E e) {return queue.offer(typeCheck(e));} } /** @@ -3440,13 +3433,11 @@ public class Collections { public int lastIndexOf(Object o) { return list.lastIndexOf(o); } public E set(int index, E element) { - typeCheck(element); - return list.set(index, element); + return list.set(index, typeCheck(element)); } public void add(int index, E element) { - typeCheck(element); - list.add(index, element); + list.add(index, typeCheck(element)); } public boolean addAll(int index, Collection c) { @@ -3467,13 +3458,11 @@ public class Collections { public void remove() { i.remove(); } public void set(E e) { - typeCheck(e); - i.set(e); + i.set(typeCheck(e)); } public void add(E e) { - typeCheck(e); - i.add(e); + i.add(typeCheck(e)); } @Override @@ -3487,10 +3476,19 @@ public class Collections { return new CheckedList<>(list.subList(fromIndex, toIndex), type); } + /** + * {@inheritDoc} + * + * @throws ClassCastException if the class of an element returned by the + * operator prevents it from being added to this collection. The + * exception may be thrown after some elements of the list have + * already been replaced. + */ @Override public void replaceAll(UnaryOperator operator) { - list.replaceAll(operator); + list.replaceAll(e -> typeCheck(operator.apply(e))); } + @Override public void sort(Comparator c) { list.sort(c); diff --git a/jdk/src/share/classes/java/util/Currency.java b/jdk/src/share/classes/java/util/Currency.java index 2c4a2e720be..5af9c7193ca 100644 --- a/jdk/src/share/classes/java/util/Currency.java +++ b/jdk/src/share/classes/java/util/Currency.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -212,13 +212,9 @@ public final class Currency implements Serializable { AccessController.doPrivileged(new PrivilegedAction() { @Override public Void run() { - String homeDir = System.getProperty("java.home"); try { - String dataFile = homeDir + File.separator + - "lib" + File.separator + "currency.data"; try (DataInputStream dis = new DataInputStream( - new BufferedInputStream( - new FileInputStream(dataFile)))) { + new BufferedInputStream(getClass().getResourceAsStream("/java/util/currency.data")))) { if (dis.readInt() != MAGIC_NUMBER) { throw new InternalError("Currency data is possibly corrupted"); } @@ -248,7 +244,7 @@ public final class Currency implements Serializable { // look for the properties file for overrides String propsFile = System.getProperty("java.util.currency.data"); if (propsFile == null) { - propsFile = homeDir + File.separator + "lib" + + propsFile = System.getProperty("java.home") + File.separator + "lib" + File.separator + "currency.properties"; } try { diff --git a/jdk/src/share/classes/java/util/stream/Collectors.java b/jdk/src/share/classes/java/util/stream/Collectors.java index 75ca1ca0f50..6f68322119d 100644 --- a/jdk/src/share/classes/java/util/stream/Collectors.java +++ b/jdk/src/share/classes/java/util/stream/Collectors.java @@ -729,7 +729,7 @@ public final class Collectors { * person in each city: *
    {@code
          *     Comparator byHeight = Comparator.comparing(Person::getHeight);
    -     *     Map tallestByCity
    +     *     Map> tallestByCity
          *         = people.stream().collect(groupingBy(Person::getCity, reducing(BinaryOperator.maxBy(byHeight))));
          * }
    * @@ -784,7 +784,7 @@ public final class Collectors { * Comparator byLength = Comparator.comparing(String::length); * Map longestLastNameByCity * = people.stream().collect(groupingBy(Person::getCity, - * reducing(Person::getLastName, BinaryOperator.maxBy(byLength)))); + * reducing("", Person::getLastName, BinaryOperator.maxBy(byLength)))); * } * * @param the type of the input elements @@ -1220,7 +1220,7 @@ public final class Collectors { * students to their grade point average: *
    {@code
          *     Map studentToGPA
    -     *         students.stream().collect(toMap(Functions.identity(),
    +     *         students.stream().collect(toMap(Function.identity(),
          *                                         student -> computeGPA(student)));
          * }
    * And the following produces a {@code Map} mapping a unique identifier to @@ -1228,7 +1228,7 @@ public final class Collectors { *
    {@code
          *     Map studentIdToStudent
          *         students.stream().collect(toMap(Student::getId,
    -     *                                         Functions.identity());
    +     *                                         Function.identity());
          * }
    * * @implNote @@ -1390,7 +1390,7 @@ public final class Collectors { * students to their grade point average: *
    {@code
          *     Map studentToGPA
    -     *         students.stream().collect(toMap(Functions.identity(),
    +     *         students.stream().collect(toMap(Function.identity(),
          *                                         student -> computeGPA(student)));
          * }
    * And the following produces a {@code Map} mapping a unique identifier to @@ -1398,7 +1398,7 @@ public final class Collectors { *
    {@code
          *     Map studentIdToStudent
          *         students.stream().collect(toConcurrentMap(Student::getId,
    -     *                                                   Functions.identity());
    +     *                                                   Function.identity());
          * }
    * *

    This is a {@link Collector.Characteristics#CONCURRENT concurrent} and diff --git a/jdk/src/share/classes/java/util/stream/package-info.java b/jdk/src/share/classes/java/util/stream/package-info.java index 016c86dd382..2353870425e 100644 --- a/jdk/src/share/classes/java/util/stream/package-info.java +++ b/jdk/src/share/classes/java/util/stream/package-info.java @@ -468,7 +468,7 @@ *

    {@code
      *     int sumOfWeights = widgets.stream()
      *                               .reduce(0,
    - *                                       (sum, b) -> sum + b.getWeight())
    + *                                       (sum, b) -> sum + b.getWeight(),
      *                                       Integer::sum);
      * }
    * though the explicit map-reduce form is more readable and therefore should diff --git a/jdk/src/share/classes/javax/crypto/CipherInputStream.java b/jdk/src/share/classes/javax/crypto/CipherInputStream.java index 0e80a6013d5..f9be4611d83 100644 --- a/jdk/src/share/classes/javax/crypto/CipherInputStream.java +++ b/jdk/src/share/classes/javax/crypto/CipherInputStream.java @@ -170,7 +170,6 @@ public class CipherInputStream extends FilterInputStream { * @return the next byte of data, or -1 if the end of the * stream is reached. * @exception IOException if an I/O error occurs. - * @since JCE1.2 */ public int read() throws IOException { if (ostart >= ofinish) { @@ -196,7 +195,6 @@ public class CipherInputStream extends FilterInputStream { * the stream has been reached. * @exception IOException if an I/O error occurs. * @see java.io.InputStream#read(byte[], int, int) - * @since JCE1.2 */ public int read(byte b[]) throws IOException { return read(b, 0, b.length); @@ -217,7 +215,6 @@ public class CipherInputStream extends FilterInputStream { * the stream has been reached. * @exception IOException if an I/O error occurs. * @see java.io.InputStream#read() - * @since JCE1.2 */ public int read(byte b[], int off, int len) throws IOException { if (ostart >= ofinish) { @@ -254,7 +251,6 @@ public class CipherInputStream extends FilterInputStream { * @param n the number of bytes to be skipped. * @return the actual number of bytes skipped. * @exception IOException if an I/O error occurs. - * @since JCE1.2 */ public long skip(long n) throws IOException { int available = ofinish - ostart; @@ -277,7 +273,6 @@ public class CipherInputStream extends FilterInputStream { * @return the number of bytes that can be read from this input stream * without blocking. * @exception IOException if an I/O error occurs. - * @since JCE1.2 */ public int available() throws IOException { return (ofinish - ostart); @@ -292,7 +287,6 @@ public class CipherInputStream extends FilterInputStream { * stream. * * @exception IOException if an I/O error occurs. - * @since JCE1.2 */ public void close() throws IOException { if (closed) { @@ -321,7 +315,6 @@ public class CipherInputStream extends FilterInputStream { * mark and reset methods. * @see java.io.InputStream#mark(int) * @see java.io.InputStream#reset() - * @since JCE1.2 */ public boolean markSupported() { return false; diff --git a/jdk/src/share/classes/javax/crypto/CipherOutputStream.java b/jdk/src/share/classes/javax/crypto/CipherOutputStream.java index 6b8d2734901..40e7dc49a6a 100644 --- a/jdk/src/share/classes/javax/crypto/CipherOutputStream.java +++ b/jdk/src/share/classes/javax/crypto/CipherOutputStream.java @@ -114,7 +114,6 @@ public class CipherOutputStream extends FilterOutputStream { * * @param b the byte. * @exception IOException if an I/O error occurs. - * @since JCE1.2 */ public void write(int b) throws IOException { ibuffer[0] = (byte) b; @@ -138,7 +137,6 @@ public class CipherOutputStream extends FilterOutputStream { * @exception NullPointerException if b is null. * @exception IOException if an I/O error occurs. * @see javax.crypto.CipherOutputStream#write(byte[], int, int) - * @since JCE1.2 */ public void write(byte b[]) throws IOException { write(b, 0, b.length); @@ -152,7 +150,6 @@ public class CipherOutputStream extends FilterOutputStream { * @param off the start offset in the data. * @param len the number of bytes to write. * @exception IOException if an I/O error occurs. - * @since JCE1.2 */ public void write(byte b[], int off, int len) throws IOException { obuffer = cipher.update(b, off, len); @@ -174,7 +171,6 @@ public class CipherOutputStream extends FilterOutputStream { * the cipher's block size, no bytes will be written out. * * @exception IOException if an I/O error occurs. - * @since JCE1.2 */ public void flush() throws IOException { if (obuffer != null) { @@ -198,7 +194,6 @@ public class CipherOutputStream extends FilterOutputStream { * stream. * * @exception IOException if an I/O error occurs. - * @since JCE1.2 */ public void close() throws IOException { if (closed) { diff --git a/jdk/src/share/classes/javax/management/loading/MLet.java b/jdk/src/share/classes/javax/management/loading/MLet.java index ac80c38b93c..54f2a872512 100644 --- a/jdk/src/share/classes/javax/management/loading/MLet.java +++ b/jdk/src/share/classes/javax/management/loading/MLet.java @@ -1307,11 +1307,11 @@ public class MLet extends java.net.URLClassLoader if (type.compareTo("java.lang.Boolean") == 0) return Boolean.valueOf(param); if (type.compareTo("java.lang.Byte") == 0) - return new Byte(param); + return Byte.valueOf(param); if (type.compareTo("java.lang.Short") == 0) - return new Short(param); + return Short.valueOf(param); if (type.compareTo("java.lang.Long") == 0) - return new Long(param); + return Long.valueOf(param); if (type.compareTo("java.lang.Integer") == 0) return new Integer(param); if (type.compareTo("java.lang.Float") == 0) diff --git a/jdk/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java b/jdk/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java index 869a2c8cdc8..d9323203a03 100644 --- a/jdk/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java +++ b/jdk/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java @@ -544,7 +544,7 @@ public class RequiredModelMBean } // convert seconds to milliseconds for time comparison - currencyPeriod = ((new Long(expTime)).longValue()) * 1000; + currencyPeriod = Long.parseLong(expTime) * 1000; if (currencyPeriod < 0) { /* if currencyTimeLimit is -1 then value is never cached */ returnCachedValue = false; @@ -580,7 +580,7 @@ public class RequiredModelMBean if (tStamp == null) tStamp = "0"; - long lastTime = (new Long(tStamp)).longValue(); + long lastTime = Long.parseLong(tStamp); if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, diff --git a/jdk/src/share/classes/javax/naming/InitialContext.java b/jdk/src/share/classes/javax/naming/InitialContext.java index 7d5b6b45374..867af4ca598 100644 --- a/jdk/src/share/classes/javax/naming/InitialContext.java +++ b/jdk/src/share/classes/javax/naming/InitialContext.java @@ -125,7 +125,7 @@ import com.sun.naming.internal.ResourceManager; * @see Context * @see NamingManager#setInitialContextFactoryBuilder * NamingManager.setInitialContextFactoryBuilder - * @since JNDI 1.1 / Java 2 Platform, Standard Edition, v 1.3 + * @since 1.3, JNDI 1.1 */ public class InitialContext implements Context { diff --git a/jdk/src/share/classes/javax/print/AttributeException.java b/jdk/src/share/classes/javax/print/AttributeException.java index f941e8109f3..136d3376810 100644 --- a/jdk/src/share/classes/javax/print/AttributeException.java +++ b/jdk/src/share/classes/javax/print/AttributeException.java @@ -52,7 +52,7 @@ public interface AttributeException { * * @return unsupported attribute classes */ - public Class[] getUnsupportedAttributes(); + public Class[] getUnsupportedAttributes(); /** * Returns the array of printing attributes for which the Print Service diff --git a/jdk/src/share/classes/javax/print/DocFlavor.java b/jdk/src/share/classes/javax/print/DocFlavor.java index d016cb7edb8..eac9d38954d 100644 --- a/jdk/src/share/classes/javax/print/DocFlavor.java +++ b/jdk/src/share/classes/javax/print/DocFlavor.java @@ -545,8 +545,7 @@ public class DocFlavor implements Serializable, Cloneable { * @exception NullPointerException if paramName is null. */ public String getParameter(String paramName) { - return - (String)myMimeType.getParameterMap().get(paramName.toLowerCase()); + return myMimeType.getParameterMap().get(paramName.toLowerCase()); } /** diff --git a/jdk/src/share/classes/javax/print/MimeType.java b/jdk/src/share/classes/javax/print/MimeType.java index 3336d093319..87891f655b7 100644 --- a/jdk/src/share/classes/javax/print/MimeType.java +++ b/jdk/src/share/classes/javax/print/MimeType.java @@ -117,18 +117,18 @@ class MimeType implements Serializable, Cloneable { /** * Parameter map entry. */ - private class ParameterMapEntry implements Map.Entry { + private class ParameterMapEntry implements Map.Entry { private int myIndex; public ParameterMapEntry(int theIndex) { myIndex = theIndex; } - public Object getKey(){ + public String getKey(){ return myPieces[myIndex]; } - public Object getValue(){ + public String getValue(){ return myPieces[myIndex+1]; } - public Object setValue (Object value) { + public String setValue (String value) { throw new UnsupportedOperationException(); } public boolean equals(Object o) { @@ -145,12 +145,12 @@ class MimeType implements Serializable, Cloneable { /** * Parameter map entry set iterator. */ - private class ParameterMapEntrySetIterator implements Iterator { + private class ParameterMapEntrySetIterator implements Iterator> { private int myIndex = 2; public boolean hasNext() { return myIndex < myPieces.length; } - public Object next() { + public Map.Entry next() { if (hasNext()) { ParameterMapEntry result = new ParameterMapEntry (myIndex); myIndex += 2; @@ -167,8 +167,8 @@ class MimeType implements Serializable, Cloneable { /** * Parameter map entry set. */ - private class ParameterMapEntrySet extends AbstractSet { - public Iterator iterator() { + private class ParameterMapEntrySet extends AbstractSet> { + public Iterator> iterator() { return new ParameterMapEntrySetIterator(); } public int size() { @@ -179,8 +179,8 @@ class MimeType implements Serializable, Cloneable { /** * Parameter map. */ - private class ParameterMap extends AbstractMap { - public Set entrySet() { + private class ParameterMap extends AbstractMap { + public Set> entrySet() { if (myEntrySet == null) { myEntrySet = new ParameterMapEntrySet(); } @@ -234,7 +234,7 @@ class MimeType implements Serializable, Cloneable { * * @return Parameter map for this MIME type object. */ - public Map getParameterMap() { + public Map getParameterMap() { if (myParameterMap == null) { myParameterMap = new ParameterMap(); } @@ -548,7 +548,7 @@ class MimeType implements Serializable, Cloneable { } LexicalAnalyzer theLexer = new LexicalAnalyzer (s); int theLexemeType; - Vector thePieces = new Vector(); + Vector thePieces = new Vector<>(); boolean mediaTypeIsText = false; boolean parameterNameIsCharset = false; @@ -623,7 +623,7 @@ class MimeType implements Serializable, Cloneable { // Save the pieces. Parameters are not in ascending order yet. int n = thePieces.size(); - myPieces = (String[]) thePieces.toArray (new String [n]); + myPieces = thePieces.toArray (new String [n]); // Sort the parameters into ascending order using an insertion sort. int i, j; diff --git a/jdk/src/share/classes/javax/print/PrintServiceLookup.java b/jdk/src/share/classes/javax/print/PrintServiceLookup.java index a466a8a4b38..aece5d1205a 100644 --- a/jdk/src/share/classes/javax/print/PrintServiceLookup.java +++ b/jdk/src/share/classes/javax/print/PrintServiceLookup.java @@ -69,8 +69,8 @@ import java.util.ServiceConfigurationError; public abstract class PrintServiceLookup { static class Services { - private ArrayList listOfLookupServices = null; - private ArrayList registeredServices = null; + private ArrayList listOfLookupServices = null; + private ArrayList registeredServices = null; } private static Services getServicesForContext() { @@ -83,23 +83,23 @@ public abstract class PrintServiceLookup { return services; } - private static ArrayList getListOfLookupServices() { + private static ArrayList getListOfLookupServices() { return getServicesForContext().listOfLookupServices; } - private static ArrayList initListOfLookupServices() { - ArrayList listOfLookupServices = new ArrayList(); + private static ArrayList initListOfLookupServices() { + ArrayList listOfLookupServices = new ArrayList<>(); getServicesForContext().listOfLookupServices = listOfLookupServices; return listOfLookupServices; } - private static ArrayList getRegisteredServices() { + private static ArrayList getRegisteredServices() { return getServicesForContext().registeredServices; } - private static ArrayList initRegisteredServices() { - ArrayList registeredServices = new ArrayList(); + private static ArrayList initRegisteredServices() { + ArrayList registeredServices = new ArrayList<>(); getServicesForContext().registeredServices = registeredServices; return registeredServices; } @@ -120,8 +120,8 @@ public abstract class PrintServiceLookup { public static final PrintService[] lookupPrintServices(DocFlavor flavor, AttributeSet attributes) { - ArrayList list = getServices(flavor, attributes); - return (PrintService[])(list.toArray(new PrintService[list.size()])); + ArrayList list = getServices(flavor, attributes); + return list.toArray(new PrintService[list.size()]); } @@ -148,9 +148,8 @@ public abstract class PrintServiceLookup { public static final MultiDocPrintService[] lookupMultiDocPrintServices(DocFlavor[] flavors, AttributeSet attributes) { - ArrayList list = getMultiDocServices(flavors, attributes); - return (MultiDocPrintService[]) - list.toArray(new MultiDocPrintService[list.size()]); + ArrayList list = getMultiDocServices(flavors, attributes); + return list.toArray(new MultiDocPrintService[list.size()]); } @@ -177,10 +176,10 @@ public abstract class PrintServiceLookup { public static final PrintService lookupDefaultPrintService() { - Iterator psIterator = getAllLookupServices().iterator(); + Iterator psIterator = getAllLookupServices().iterator(); while (psIterator.hasNext()) { try { - PrintServiceLookup lus = (PrintServiceLookup)psIterator.next(); + PrintServiceLookup lus = psIterator.next(); PrintService service = lus.getDefaultPrintService(); if (service != null) { return service; @@ -208,7 +207,8 @@ public abstract class PrintServiceLookup { */ public static boolean registerServiceProvider(PrintServiceLookup sp) { synchronized (PrintServiceLookup.class) { - Iterator psIterator = getAllLookupServices().iterator(); + Iterator psIterator = + getAllLookupServices().iterator(); while (psIterator.hasNext()) { try { Object lus = psIterator.next(); @@ -249,7 +249,7 @@ public abstract class PrintServiceLookup { if (service instanceof StreamPrintService) { return false; } - ArrayList registeredServices = getRegisteredServices(); + ArrayList registeredServices = getRegisteredServices(); if (registeredServices == null) { registeredServices = initRegisteredServices(); } @@ -326,9 +326,9 @@ public abstract class PrintServiceLookup { */ public abstract PrintService getDefaultPrintService(); - private static ArrayList getAllLookupServices() { + private static ArrayList getAllLookupServices() { synchronized (PrintServiceLookup.class) { - ArrayList listOfLookupServices = getListOfLookupServices(); + ArrayList listOfLookupServices = getListOfLookupServices(); if (listOfLookupServices != null) { return listOfLookupServices; } else { @@ -336,12 +336,12 @@ public abstract class PrintServiceLookup { } try { java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { + new java.security.PrivilegedExceptionAction() { public Object run() { Iterator iterator = ServiceLoader.load(PrintServiceLookup.class). iterator(); - ArrayList los = getListOfLookupServices(); + ArrayList los = getListOfLookupServices(); while (iterator.hasNext()) { try { los.add(iterator.next()); @@ -364,14 +364,14 @@ public abstract class PrintServiceLookup { } } - private static ArrayList getServices(DocFlavor flavor, - AttributeSet attributes) { + private static ArrayList getServices(DocFlavor flavor, + AttributeSet attributes) { - ArrayList listOfServices = new ArrayList(); - Iterator psIterator = getAllLookupServices().iterator(); + ArrayList listOfServices = new ArrayList<>(); + Iterator psIterator = getAllLookupServices().iterator(); while (psIterator.hasNext()) { try { - PrintServiceLookup lus = (PrintServiceLookup)psIterator.next(); + PrintServiceLookup lus = psIterator.next(); PrintService[] services=null; if (flavor == null && attributes == null) { try { @@ -391,7 +391,7 @@ public abstract class PrintServiceLookup { } } /* add any directly registered services */ - ArrayList registeredServices = null; + ArrayList registeredServices = null; try { SecurityManager security = System.getSecurityManager(); if (security != null) { @@ -401,8 +401,7 @@ public abstract class PrintServiceLookup { } catch (SecurityException se) { } if (registeredServices != null) { - PrintService[] services = (PrintService[]) - registeredServices.toArray( + PrintService[] services = registeredServices.toArray( new PrintService[registeredServices.size()]); for (int i=0; i getMultiDocServices(DocFlavor[] flavors, + AttributeSet attributes) { - ArrayList listOfServices = new ArrayList(); - Iterator psIterator = getAllLookupServices().iterator(); + ArrayList listOfServices = new ArrayList<>(); + Iterator psIterator = getAllLookupServices().iterator(); while (psIterator.hasNext()) { try { - PrintServiceLookup lus = (PrintServiceLookup)psIterator.next(); + PrintServiceLookup lus = psIterator.next(); MultiDocPrintService[] services = lus.getMultiDocPrintServices(flavors, attributes); if (services == null) { @@ -442,7 +441,7 @@ public abstract class PrintServiceLookup { } } /* add any directly registered services */ - ArrayList registeredServices = null; + ArrayList registeredServices = null; try { SecurityManager security = System.getSecurityManager(); if (security != null) { @@ -452,14 +451,13 @@ public abstract class PrintServiceLookup { } catch (Exception e) { } if (registeredServices != null) { - PrintService[] services = (PrintService[]) - registeredServices.toArray( - new PrintService[registeredServices.size()]); + PrintService[] services = + registeredServices.toArray(new PrintService[registeredServices.size()]); for (int i=0; i dstCategory = Destination.class; + Class amCategory = SunAlternateMedia.class; + Class fdCategory = Fidelity.class; if (attributes.containsKey(dstCategory) && !newas.containsKey(dstCategory)) @@ -315,7 +315,7 @@ public class ServiceUI { Attribute[] usAttrs = asUnsupported.toArray(); for (int i=0; i category = usAttrs[i].getCategory(); if (ps.isAttributeCategorySupported(category)) { Attribute attr = diff --git a/jdk/src/share/classes/javax/print/SimpleDoc.java b/jdk/src/share/classes/javax/print/SimpleDoc.java index 8bb812a66f4..3cf0d779086 100644 --- a/jdk/src/share/classes/javax/print/SimpleDoc.java +++ b/jdk/src/share/classes/javax/print/SimpleDoc.java @@ -89,7 +89,7 @@ public final class SimpleDoc implements Doc { throw new IllegalArgumentException("null argument(s)"); } - Class repClass = null; + Class repClass = null; try { String className = flavor.getRepresentationClassName(); sun.reflect.misc.ReflectUtil.checkPackageAccess(className); diff --git a/jdk/src/share/classes/javax/print/StreamPrintServiceFactory.java b/jdk/src/share/classes/javax/print/StreamPrintServiceFactory.java index 3199dac2985..dfa91a70fcb 100644 --- a/jdk/src/share/classes/javax/print/StreamPrintServiceFactory.java +++ b/jdk/src/share/classes/javax/print/StreamPrintServiceFactory.java @@ -59,7 +59,7 @@ import java.util.ServiceConfigurationError; public abstract class StreamPrintServiceFactory { static class Services { - private ArrayList listOfFactories = null; + private ArrayList listOfFactories = null; } private static Services getServices() { @@ -72,12 +72,12 @@ public abstract class StreamPrintServiceFactory { return services; } - private static ArrayList getListOfFactories() { + private static ArrayList getListOfFactories() { return getServices().listOfFactories; } - private static ArrayList initListOfFactories() { - ArrayList listOfFactories = new ArrayList(); + private static ArrayList initListOfFactories() { + ArrayList listOfFactories = new ArrayList<>(); getServices().listOfFactories = listOfFactories; return listOfFactories; } @@ -108,9 +108,8 @@ public abstract class StreamPrintServiceFactory { lookupStreamPrintServiceFactories(DocFlavor flavor, String outputMimeType) { - ArrayList list = getFactories(flavor, outputMimeType); - return (StreamPrintServiceFactory[]) - (list.toArray(new StreamPrintServiceFactory[list.size()])); + ArrayList list = getFactories(flavor, outputMimeType); + return list.toArray(new StreamPrintServiceFactory[list.size()]); } /** Queries the factory for the document format that is emitted @@ -162,10 +161,10 @@ public abstract class StreamPrintServiceFactory { public abstract StreamPrintService getPrintService(OutputStream out); - private static ArrayList getAllFactories() { + private static ArrayList getAllFactories() { synchronized (StreamPrintServiceFactory.class) { - ArrayList listOfFactories = getListOfFactories(); + ArrayList listOfFactories = getListOfFactories(); if (listOfFactories != null) { return listOfFactories; } else { @@ -174,12 +173,12 @@ public abstract class StreamPrintServiceFactory { try { java.security.AccessController.doPrivileged( - new java.security.PrivilegedExceptionAction() { + new java.security.PrivilegedExceptionAction() { public Object run() { Iterator iterator = ServiceLoader.load (StreamPrintServiceFactory.class).iterator(); - ArrayList lof = getListOfFactories(); + ArrayList lof = getListOfFactories(); while (iterator.hasNext()) { try { lof.add(iterator.next()); @@ -210,17 +209,16 @@ public abstract class StreamPrintServiceFactory { return false; } - private static ArrayList getFactories(DocFlavor flavor, String outType) { + private static ArrayList getFactories(DocFlavor flavor, String outType) { if (flavor == null && outType == null) { return getAllFactories(); } - ArrayList list = new ArrayList(); - Iterator iterator = getAllFactories().iterator(); + ArrayList list = new ArrayList<>(); + Iterator iterator = getAllFactories().iterator(); while (iterator.hasNext()) { - StreamPrintServiceFactory factory = - (StreamPrintServiceFactory)iterator.next(); + StreamPrintServiceFactory factory = iterator.next(); if ((outType == null || outType.equalsIgnoreCase(factory.getOutputFormat())) && (flavor == null || diff --git a/jdk/src/share/classes/javax/print/attribute/AttributeSetUtilities.java b/jdk/src/share/classes/javax/print/attribute/AttributeSetUtilities.java index 42ebc1f512d..2c5896f633f 100644 --- a/jdk/src/share/classes/javax/print/attribute/AttributeSetUtilities.java +++ b/jdk/src/share/classes/javax/print/attribute/AttributeSetUtilities.java @@ -523,7 +523,7 @@ public final class AttributeSetUtilities { public static Class verifyAttributeCategory(Object object, Class interfaceName) { - Class result = (Class) object; + Class result = (Class) object; if (interfaceName.isAssignableFrom (result)) { return result; } diff --git a/jdk/src/share/classes/javax/print/attribute/HashAttributeSet.java b/jdk/src/share/classes/javax/print/attribute/HashAttributeSet.java index a1995014525..7956794d304 100644 --- a/jdk/src/share/classes/javax/print/attribute/HashAttributeSet.java +++ b/jdk/src/share/classes/javax/print/attribute/HashAttributeSet.java @@ -48,13 +48,13 @@ public class HashAttributeSet implements AttributeSet, Serializable { * or a subinterface thereof. * @serial */ - private Class myInterface; + private Class myInterface; /* * A HashMap used by the implementation. * The serialised form doesn't include this instance variable. */ - private transient HashMap attrMap = new HashMap(); + private transient HashMap, Attribute> attrMap = new HashMap<>(); /** * Write the instance to a stream (ie serialize the object) @@ -82,7 +82,7 @@ public class HashAttributeSet implements AttributeSet, Serializable { throws ClassNotFoundException, IOException { s.defaultReadObject(); - attrMap = new HashMap(); + attrMap = new HashMap<>(); int count = s.readInt(); Attribute attr; for (int i = 0; i < count; i++) { @@ -274,10 +274,9 @@ public class HashAttributeSet implements AttributeSet, Serializable { * Attribute Attribute}. */ public Attribute get(Class category) { - return (Attribute) - attrMap.get(AttributeSetUtilities. - verifyAttributeCategory(category, - Attribute.class)); + return attrMap.get(AttributeSetUtilities. + verifyAttributeCategory(category, + Attribute.class)); } /** diff --git a/jdk/src/share/classes/javax/print/attribute/SetOfIntegerSyntax.java b/jdk/src/share/classes/javax/print/attribute/SetOfIntegerSyntax.java index 9afdd1e6411..0aed773fe6e 100644 --- a/jdk/src/share/classes/javax/print/attribute/SetOfIntegerSyntax.java +++ b/jdk/src/share/classes/javax/print/attribute/SetOfIntegerSyntax.java @@ -112,7 +112,7 @@ public abstract class SetOfIntegerSyntax implements Serializable, Cloneable { private static int[][] parse(String members) { // Create vector to hold int[] elements, each element being one range // parsed out of members. - Vector theRanges = new Vector(); + Vector theRanges = new Vector<>(); // Run state machine over members. int n = (members == null ? 0 : members.length()); @@ -243,7 +243,7 @@ public abstract class SetOfIntegerSyntax implements Serializable, Cloneable { * Accumulate the given range (lb .. ub) into the canonical array form * into the given vector of int[] objects. */ - private static void accumulate(Vector ranges, int lb,int ub) { + private static void accumulate(Vector ranges, int lb,int ub) { // Make sure range is non-null. if (lb <= ub) { // Stick range at the back of the vector. @@ -253,10 +253,10 @@ public abstract class SetOfIntegerSyntax implements Serializable, Cloneable { // with the existing ranges. for (int j = ranges.size()-2; j >= 0; -- j) { // Get lower and upper bounds of the two ranges being compared. - int[] rangea = (int[]) ranges.elementAt (j); + int[] rangea = ranges.elementAt (j); int lba = rangea[0]; int uba = rangea[1]; - int[] rangeb = (int[]) ranges.elementAt (j+1); + int[] rangeb = ranges.elementAt (j+1); int lbb = rangeb[0]; int ubb = rangeb[1]; @@ -293,8 +293,8 @@ public abstract class SetOfIntegerSyntax implements Serializable, Cloneable { /** * Convert the given vector of int[] objects to canonical array form. */ - private static int[][] canonicalArrayForm(Vector ranges) { - return (int[][]) ranges.toArray (new int[ranges.size()][]); + private static int[][] canonicalArrayForm(Vector ranges) { + return ranges.toArray (new int[ranges.size()][]); } /** @@ -323,7 +323,7 @@ public abstract class SetOfIntegerSyntax implements Serializable, Cloneable { private static int[][] parse(int[][] members) { // Create vector to hold int[] elements, each element being one range // parsed out of members. - Vector ranges = new Vector(); + Vector ranges = new Vector<>(); // Process all integer groups in members. int n = (members == null ? 0 : members.length); diff --git a/jdk/src/share/classes/javax/print/attribute/standard/DialogTypeSelection.java b/jdk/src/share/classes/javax/print/attribute/standard/DialogTypeSelection.java index 0a41fc23830..43cc15ee96a 100644 --- a/jdk/src/share/classes/javax/print/attribute/standard/DialogTypeSelection.java +++ b/jdk/src/share/classes/javax/print/attribute/standard/DialogTypeSelection.java @@ -26,6 +26,7 @@ package javax.print.attribute.standard; import javax.print.attribute.EnumSyntax; +import javax.print.attribute.Attribute; import javax.print.attribute.PrintRequestAttribute; /** @@ -110,7 +111,7 @@ public final class DialogTypeSelection extends EnumSyntax * @return Printing attribute class (category), an instance of class * {@link java.lang.Class java.lang.Class}. */ - public final Class getCategory() { + public final Class getCategory() { return DialogTypeSelection.class; } diff --git a/jdk/src/share/classes/javax/print/attribute/standard/MediaSize.java b/jdk/src/share/classes/javax/print/attribute/standard/MediaSize.java index e50960e5060..af173a8d6ea 100644 --- a/jdk/src/share/classes/javax/print/attribute/standard/MediaSize.java +++ b/jdk/src/share/classes/javax/print/attribute/standard/MediaSize.java @@ -56,9 +56,9 @@ public class MediaSize extends Size2DSyntax implements Attribute { private MediaSizeName mediaName; - private static HashMap mediaMap = new HashMap(100, 10); + private static HashMap mediaMap = new HashMap<>(100, 10); - private static Vector sizeVector = new Vector(100, 10); + private static Vector sizeVector = new Vector<>(100, 10); /** * Construct a new media size attribute from the given floating-point @@ -174,7 +174,7 @@ public class MediaSize extends Size2DSyntax implements Attribute { * with any size. */ public static MediaSize getMediaSizeForName(MediaSizeName media) { - return (MediaSize)mediaMap.get(media); + return mediaMap.get(media); } /** @@ -213,7 +213,7 @@ public class MediaSize extends Size2DSyntax implements Attribute { float diffy = y; for (int i=0; i < sizeVector.size() ; i++) { - MediaSize mediaSize = (MediaSize)sizeVector.elementAt(i); + MediaSize mediaSize = sizeVector.elementAt(i); dim = mediaSize.getSize(units); if (x == dim[0] && y == dim[1]) { match = mediaSize; diff --git a/jdk/src/share/classes/javax/print/attribute/standard/PrinterStateReasons.java b/jdk/src/share/classes/javax/print/attribute/standard/PrinterStateReasons.java index de695b78aa0..89b08f311ad 100644 --- a/jdk/src/share/classes/javax/print/attribute/standard/PrinterStateReasons.java +++ b/jdk/src/share/classes/javax/print/attribute/standard/PrinterStateReasons.java @@ -242,16 +242,18 @@ public final class PrinterStateReasons extends AbstractSet { private Severity mySeverity; - private Set myEntrySet; - public PrinterStateReasonSet(Severity severity, Set entrySet) { + private Set> myEntrySet; + + public PrinterStateReasonSet(Severity severity, + Set> entrySet) { mySeverity = severity; myEntrySet = entrySet; } public int size() { int result = 0; - Iterator iter = iterator(); + Iterator iter = iterator(); while (iter.hasNext()) { iter.next(); ++ result; @@ -259,19 +261,19 @@ public final class PrinterStateReasons return result; } - public Iterator iterator() { + public Iterator iterator() { return new PrinterStateReasonSetIterator(mySeverity, myEntrySet.iterator()); } } - private class PrinterStateReasonSetIterator implements Iterator { + private class PrinterStateReasonSetIterator implements Iterator { private Severity mySeverity; - private Iterator myIterator; - private Map.Entry myEntry; + private Iterator> myIterator; + private Map.Entry myEntry; public PrinterStateReasonSetIterator(Severity severity, - Iterator iterator) { + Iterator> iterator) { mySeverity = severity; myIterator = iterator; goToNext(); @@ -280,8 +282,8 @@ public final class PrinterStateReasons private void goToNext() { myEntry = null; while (myEntry == null && myIterator.hasNext()) { - myEntry = (Map.Entry) myIterator.next(); - if ((Severity) myEntry.getValue() != mySeverity) { + myEntry = myIterator.next(); + if (myEntry.getValue() != mySeverity) { myEntry = null; } } @@ -291,11 +293,11 @@ public final class PrinterStateReasons return myEntry != null; } - public Object next() { + public PrinterStateReason next() { if (myEntry == null) { throw new NoSuchElementException(); } - Object result = myEntry.getKey(); + PrinterStateReason result = myEntry.getKey(); goToNext(); return result; } diff --git a/jdk/src/share/classes/javax/security/auth/Subject.java b/jdk/src/share/classes/javax/security/auth/Subject.java index 2c9e8b8083f..e8ce12c9eee 100644 --- a/jdk/src/share/classes/javax/security/auth/Subject.java +++ b/jdk/src/share/classes/javax/security/auth/Subject.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -142,7 +142,9 @@ public final class Subject implements java.io.Serializable { *

    The newly constructed Sets check whether this {@code Subject} * has been set read-only before permitting subsequent modifications. * The newly created Sets also prevent illegal modifications - * by ensuring that callers have sufficient permissions. + * by ensuring that callers have sufficient permissions. These Sets + * also prohibit null elements, and attempts to add or query a null + * element will result in a {@code NullPointerException}. * *

    To modify the Principals Set, the caller must have * {@code AuthPermission("modifyPrincipals")}. @@ -170,7 +172,9 @@ public final class Subject implements java.io.Serializable { * These newly created Sets check whether this {@code Subject} * has been set read-only before permitting subsequent modifications. * The newly created Sets also prevent illegal modifications - * by ensuring that callers have sufficient permissions. + * by ensuring that callers have sufficient permissions. These Sets + * also prohibit null elements, and attempts to add or query a null + * element will result in a {@code NullPointerException}. * *

    To modify the Principals Set, the caller must have * {@code AuthPermission("modifyPrincipals")}. @@ -194,17 +198,16 @@ public final class Subject implements java.io.Serializable { * * @exception NullPointerException if the specified * {@code principals}, {@code pubCredentials}, - * or {@code privCredentials} are {@code null}. + * or {@code privCredentials} are {@code null}, + * or a null value exists within any of these three + * Sets. */ public Subject(boolean readOnly, Set principals, Set pubCredentials, Set privCredentials) { - - if (principals == null || - pubCredentials == null || - privCredentials == null) - throw new NullPointerException - (ResourcesMgr.getString("invalid.null.input.s.")); + collectionNullClean(principals); + collectionNullClean(pubCredentials); + collectionNullClean(privCredentials); this.principals = Collections.synchronizedSet(new SecureSet (this, PRINCIPAL_SET, principals)); @@ -287,18 +290,17 @@ public final class Subject implements java.io.Serializable { sm.checkPermission(AuthPermissionHolder.GET_SUBJECT_PERMISSION); } - if (acc == null) { - throw new NullPointerException(ResourcesMgr.getString + Objects.requireNonNull(acc, ResourcesMgr.getString ("invalid.null.AccessControlContext.provided")); - } // return the Subject from the DomainCombiner of the provided context return AccessController.doPrivileged (new java.security.PrivilegedAction() { public Subject run() { DomainCombiner dc = acc.getDomainCombiner(); - if (!(dc instanceof SubjectDomainCombiner)) + if (!(dc instanceof SubjectDomainCombiner)) { return null; + } SubjectDomainCombiner sdc = (SubjectDomainCombiner)dc; return sdc.getSubject(); } @@ -347,9 +349,9 @@ public final class Subject implements java.io.Serializable { if (sm != null) { sm.checkPermission(AuthPermissionHolder.DO_AS_PERMISSION); } - if (action == null) - throw new NullPointerException - (ResourcesMgr.getString("invalid.null.action.provided")); + + Objects.requireNonNull(action, + ResourcesMgr.getString("invalid.null.action.provided")); // set up the new Subject-based AccessControlContext // for doPrivileged @@ -410,9 +412,8 @@ public final class Subject implements java.io.Serializable { sm.checkPermission(AuthPermissionHolder.DO_AS_PERMISSION); } - if (action == null) - throw new NullPointerException - (ResourcesMgr.getString("invalid.null.action.provided")); + Objects.requireNonNull(action, + ResourcesMgr.getString("invalid.null.action.provided")); // set up the new Subject-based AccessControlContext for doPrivileged final AccessControlContext currentAcc = AccessController.getContext(); @@ -467,9 +468,8 @@ public final class Subject implements java.io.Serializable { sm.checkPermission(AuthPermissionHolder.DO_AS_PRIVILEGED_PERMISSION); } - if (action == null) - throw new NullPointerException - (ResourcesMgr.getString("invalid.null.action.provided")); + Objects.requireNonNull(action, + ResourcesMgr.getString("invalid.null.action.provided")); // set up the new Subject-based AccessControlContext // for doPrivileged @@ -534,9 +534,8 @@ public final class Subject implements java.io.Serializable { sm.checkPermission(AuthPermissionHolder.DO_AS_PRIVILEGED_PERMISSION); } - if (action == null) - throw new NullPointerException - (ResourcesMgr.getString("invalid.null.action.provided")); + Objects.requireNonNull(action, + ResourcesMgr.getString("invalid.null.action.provided")); // set up the new Subject-based AccessControlContext for doPrivileged final AccessControlContext callerAcc = @@ -557,13 +556,14 @@ public final class Subject implements java.io.Serializable { return java.security.AccessController.doPrivileged (new java.security.PrivilegedAction() { public AccessControlContext run() { - if (subject == null) + if (subject == null) { return new AccessControlContext(acc, null); - else + } else { return new AccessControlContext (acc, new SubjectDomainCombiner(subject)); } + } }); } @@ -615,9 +615,8 @@ public final class Subject implements java.io.Serializable { */ public Set getPrincipals(Class c) { - if (c == null) - throw new NullPointerException - (ResourcesMgr.getString("invalid.null.Class.provided")); + Objects.requireNonNull(c, + ResourcesMgr.getString("invalid.null.Class.provided")); // always return an empty Set instead of null // so LoginModules can add to the Set if necessary @@ -711,9 +710,8 @@ public final class Subject implements java.io.Serializable { */ public Set getPublicCredentials(Class c) { - if (c == null) - throw new NullPointerException - (ResourcesMgr.getString("invalid.null.Class.provided")); + Objects.requireNonNull(c, + ResourcesMgr.getString("invalid.null.Class.provided")); // always return an empty Set instead of null // so LoginModules can add to the Set if necessary @@ -758,9 +756,8 @@ public final class Subject implements java.io.Serializable { // would do is protect the set operations themselves // (like size()), which don't seem security-sensitive. - if (c == null) - throw new NullPointerException - (ResourcesMgr.getString("invalid.null.Class.provided")); + Objects.requireNonNull(c, + ResourcesMgr.getString("invalid.null.Class.provided")); // always return an empty Set instead of null // so LoginModules can add to the Set if necessary @@ -790,11 +787,13 @@ public final class Subject implements java.io.Serializable { */ public boolean equals(Object o) { - if (o == null) + if (o == null) { return false; + } - if (this == o) + if (this == o) { return true; + } if (o instanceof Subject) { @@ -969,11 +968,10 @@ public final class Subject implements java.io.Serializable { Set inputPrincs = (Set)gf.get("principals", null); + Objects.requireNonNull(inputPrincs, + ResourcesMgr.getString("invalid.null.input.s.")); + // Rewrap the principals into a SecureSet - if (inputPrincs == null) { - throw new NullPointerException - (ResourcesMgr.getString("invalid.null.input.s.")); - } try { principals = Collections.synchronizedSet(new SecureSet (this, PRINCIPAL_SET, inputPrincs)); @@ -992,14 +990,44 @@ public final class Subject implements java.io.Serializable { (new SecureSet(this, PRIV_CREDENTIAL_SET)); } + /** + * Tests for null-clean collections (both non-null reference and + * no null elements) + * + * @param coll A {@code Collection} to be tested for null references + * + * @exception NullPointerException if the specified collection is either + * {@code null} or contains a {@code null} element + */ + private static void collectionNullClean(Collection coll) { + boolean hasNullElements = false; + + Objects.requireNonNull(coll, + ResourcesMgr.getString("invalid.null.input.s.")); + + try { + hasNullElements = coll.contains(null); + } catch (NullPointerException npe) { + // A null-hostile collection may choose to throw + // NullPointerException if contains(null) is called on it + // rather than returning false. + // If this happens we know the collection is null-clean. + hasNullElements = false; + } finally { + if (hasNullElements) { + throw new NullPointerException + (ResourcesMgr.getString("invalid.null.input.s.")); + } + } + } + /** * Prevent modifications unless caller has permission. * * @serial include */ private static class SecureSet - extends AbstractSet - implements java.io.Serializable { + implements Set, java.io.Serializable { private static final long serialVersionUID = 7911754171111800359L; @@ -1098,6 +1126,9 @@ public final class Subject implements java.io.Serializable { public boolean add(E o) { + Objects.requireNonNull(o, + ResourcesMgr.getString("invalid.null.input.s.")); + if (subject.isReadOnly()) { throw new IllegalStateException (ResourcesMgr.getString("Subject.is.read.only")); @@ -1133,12 +1164,16 @@ public final class Subject implements java.io.Serializable { // check for duplicates if (!elements.contains(o)) return elements.add(o); - else + else { return false; } + } public boolean remove(Object o) { + Objects.requireNonNull(o, + ResourcesMgr.getString("invalid.null.input.s.")); + final Iterator e = iterator(); while (e.hasNext()) { E next; @@ -1153,12 +1188,7 @@ public final class Subject implements java.io.Serializable { }); } - if (next == null) { - if (o == null) { - e.remove(); - return true; - } - } else if (next.equals(o)) { + if (next.equals(o)) { e.remove(); return true; } @@ -1167,6 +1197,10 @@ public final class Subject implements java.io.Serializable { } public boolean contains(Object o) { + + Objects.requireNonNull(o, + ResourcesMgr.getString("invalid.null.input.s.")); + final Iterator e = iterator(); while (e.hasNext()) { E next; @@ -1194,19 +1228,28 @@ public final class Subject implements java.io.Serializable { }); } - if (next == null) { - if (o == null) { - return true; - } - } else if (next.equals(o)) { + if (next.equals(o)) { return true; } } return false; } + public boolean addAll(Collection c) { + boolean result = false; + + collectionNullClean(c); + + for (E item : c) { + result |= this.add(item); + } + + return result; + } + public boolean removeAll(Collection c) { - Objects.requireNonNull(c); + collectionNullClean(c); + boolean modified = false; final Iterator e = iterator(); while (e.hasNext()) { @@ -1224,30 +1267,34 @@ public final class Subject implements java.io.Serializable { Iterator ce = c.iterator(); while (ce.hasNext()) { - Object o = ce.next(); - if (next == null) { - if (o == null) { + if (next.equals(ce.next())) { e.remove(); modified = true; break; } - } else if (next.equals(o)) { - e.remove(); - modified = true; - break; - } } } return modified; } + public boolean containsAll(Collection c) { + collectionNullClean(c); + + for (Object item : c) { + if (this.contains(item) == false) { + return false; + } + } + + return true; + } + public boolean retainAll(Collection c) { - Objects.requireNonNull(c); + collectionNullClean(c); + boolean modified = false; - boolean retain = false; final Iterator e = iterator(); while (e.hasNext()) { - retain = false; E next; if (which != Subject.PRIV_CREDENTIAL_SET) { next = e.next(); @@ -1260,26 +1307,12 @@ public final class Subject implements java.io.Serializable { }); } - Iterator ce = c.iterator(); - while (ce.hasNext()) { - Object o = ce.next(); - if (next == null) { - if (o == null) { - retain = true; - break; - } - } else if (next.equals(o)) { - retain = true; - break; + if (c.contains(next) == false) { + e.remove(); + modified = true; } } - if (!retain) { - e.remove(); - retain = false; - modified = true; - } - } return modified; } @@ -1301,6 +1334,73 @@ public final class Subject implements java.io.Serializable { } } + public boolean isEmpty() { + return elements.isEmpty(); + } + + public Object[] toArray() { + final Iterator e = iterator(); + while (e.hasNext()) { + // The next() method performs a security manager check + // on each element in the SecureSet. If we make it all + // the way through we should be able to simply return + // element's toArray results. Otherwise we'll let + // the SecurityException pass up the call stack. + e.next(); + } + + return elements.toArray(); + } + + public T[] toArray(T[] a) { + final Iterator e = iterator(); + while (e.hasNext()) { + // The next() method performs a security manager check + // on each element in the SecureSet. If we make it all + // the way through we should be able to simply return + // element's toArray results. Otherwise we'll let + // the SecurityException pass up the call stack. + e.next(); + } + + return elements.toArray(a); + } + + public boolean equals(Object o) { + if (o == this) { + return true; + } + + if (!(o instanceof Set)) { + return false; + } + + Collection c = (Collection) o; + if (c.size() != size()) { + return false; + } + + try { + return containsAll(c); + } catch (ClassCastException unused) { + return false; + } catch (NullPointerException unused) { + return false; + } + } + + public int hashCode() { + int h = 0; + Iterator i = iterator(); + while (i.hasNext()) { + E obj = i.next(); + if (obj != null) { + h += obj.hashCode(); + } + } + return h; + } + /** * Writes this object out to a stream (i.e., serializes it). * @@ -1338,12 +1438,16 @@ public final class Subject implements java.io.Serializable { which = fields.get("which", 0); LinkedList tmp = (LinkedList) fields.get("elements", null); + + Subject.collectionNullClean(tmp); + if (tmp.getClass() != LinkedList.class) { elements = new LinkedList(tmp); } else { elements = tmp; } } + } /** diff --git a/jdk/src/share/classes/javax/sound/midi/MidiFileFormat.java b/jdk/src/share/classes/javax/sound/midi/MidiFileFormat.java index 0d496490dd0..c34bb6d1900 100644 --- a/jdk/src/share/classes/javax/sound/midi/MidiFileFormat.java +++ b/jdk/src/share/classes/javax/sound/midi/MidiFileFormat.java @@ -266,6 +266,7 @@ public class MidiFileFormat { * @see #getProperty(String) * @since 1.5 */ + @SuppressWarnings("unchecked") // Cast of result of clone public Map properties() { Map ret; if (properties == null) { diff --git a/jdk/src/share/classes/javax/sound/midi/MidiSystem.java b/jdk/src/share/classes/javax/sound/midi/MidiSystem.java index c661e23304d..d6ef5432978 100644 --- a/jdk/src/share/classes/javax/sound/midi/MidiSystem.java +++ b/jdk/src/share/classes/javax/sound/midi/MidiSystem.java @@ -187,17 +187,17 @@ public class MidiSystem { * an array of length 0 is returned. */ public static MidiDevice.Info[] getMidiDeviceInfo() { - List allInfos = new ArrayList(); - List providers = getMidiDeviceProviders(); + List allInfos = new ArrayList<>(); + List providers = getMidiDeviceProviders(); for(int i = 0; i < providers.size(); i++) { - MidiDeviceProvider provider = (MidiDeviceProvider) providers.get(i); + MidiDeviceProvider provider = providers.get(i); MidiDevice.Info[] tmpinfo = provider.getDeviceInfo(); for (int j = 0; j < tmpinfo.length; j++) { allInfos.add( tmpinfo[j] ); } } - MidiDevice.Info[] infosArray = (MidiDevice.Info[]) allInfos.toArray(new MidiDevice.Info[0]); + MidiDevice.Info[] infosArray = allInfos.toArray(new MidiDevice.Info[0]); return infosArray; } @@ -214,10 +214,10 @@ public class MidiSystem { * @see #getMidiDeviceInfo */ public static MidiDevice getMidiDevice(MidiDevice.Info info) throws MidiUnavailableException { - List providers = getMidiDeviceProviders(); + List providers = getMidiDeviceProviders(); for(int i = 0; i < providers.size(); i++) { - MidiDeviceProvider provider = (MidiDeviceProvider) providers.get(i); + MidiDeviceProvider provider = providers.get(i); if (provider.isDeviceSupported(info)) { MidiDevice device = provider.getDevice(info); return device; @@ -528,10 +528,10 @@ public class MidiSystem { SoundbankReader sp = null; Soundbank s = null; - List providers = getSoundbankReaders(); + List providers = getSoundbankReaders(); for(int i = 0; i < providers.size(); i++) { - sp = (SoundbankReader)providers.get(i); + sp = providers.get(i); s = sp.getSoundbank(stream); if( s!= null) { @@ -559,10 +559,10 @@ public class MidiSystem { SoundbankReader sp = null; Soundbank s = null; - List providers = getSoundbankReaders(); + List providers = getSoundbankReaders(); for(int i = 0; i < providers.size(); i++) { - sp = (SoundbankReader)providers.get(i); + sp = providers.get(i); s = sp.getSoundbank(url); if( s!= null) { @@ -591,10 +591,10 @@ public class MidiSystem { SoundbankReader sp = null; Soundbank s = null; - List providers = getSoundbankReaders(); + List providers = getSoundbankReaders(); for(int i = 0; i < providers.size(); i++) { - sp = (SoundbankReader)providers.get(i); + sp = providers.get(i); s = sp.getSoundbank(file); if( s!= null) { @@ -641,11 +641,11 @@ public class MidiSystem { public static MidiFileFormat getMidiFileFormat(InputStream stream) throws InvalidMidiDataException, IOException { - List providers = getMidiFileReaders(); + List providers = getMidiFileReaders(); MidiFileFormat format = null; for(int i = 0; i < providers.size(); i++) { - MidiFileReader reader = (MidiFileReader) providers.get(i); + MidiFileReader reader = providers.get(i); try { format = reader.getMidiFileFormat( stream ); // throws IOException break; @@ -687,11 +687,11 @@ public class MidiSystem { public static MidiFileFormat getMidiFileFormat(URL url) throws InvalidMidiDataException, IOException { - List providers = getMidiFileReaders(); + List providers = getMidiFileReaders(); MidiFileFormat format = null; for(int i = 0; i < providers.size(); i++) { - MidiFileReader reader = (MidiFileReader) providers.get(i); + MidiFileReader reader = providers.get(i); try { format = reader.getMidiFileFormat( url ); // throws IOException break; @@ -733,11 +733,11 @@ public class MidiSystem { public static MidiFileFormat getMidiFileFormat(File file) throws InvalidMidiDataException, IOException { - List providers = getMidiFileReaders(); + List providers = getMidiFileReaders(); MidiFileFormat format = null; for(int i = 0; i < providers.size(); i++) { - MidiFileReader reader = (MidiFileReader) providers.get(i); + MidiFileReader reader = providers.get(i); try { format = reader.getMidiFileFormat( file ); // throws IOException break; @@ -788,11 +788,11 @@ public class MidiSystem { public static Sequence getSequence(InputStream stream) throws InvalidMidiDataException, IOException { - List providers = getMidiFileReaders(); + List providers = getMidiFileReaders(); Sequence sequence = null; for(int i = 0; i < providers.size(); i++) { - MidiFileReader reader = (MidiFileReader) providers.get(i); + MidiFileReader reader = providers.get(i); try { sequence = reader.getSequence( stream ); // throws IOException break; @@ -832,11 +832,11 @@ public class MidiSystem { public static Sequence getSequence(URL url) throws InvalidMidiDataException, IOException { - List providers = getMidiFileReaders(); + List providers = getMidiFileReaders(); Sequence sequence = null; for(int i = 0; i < providers.size(); i++) { - MidiFileReader reader = (MidiFileReader) providers.get(i); + MidiFileReader reader = providers.get(i); try { sequence = reader.getSequence( url ); // throws IOException break; @@ -876,11 +876,11 @@ public class MidiSystem { public static Sequence getSequence(File file) throws InvalidMidiDataException, IOException { - List providers = getMidiFileReaders(); + List providers = getMidiFileReaders(); Sequence sequence = null; for(int i = 0; i < providers.size(); i++) { - MidiFileReader reader = (MidiFileReader) providers.get(i); + MidiFileReader reader = providers.get(i); try { sequence = reader.getSequence( file ); // throws IOException break; @@ -905,13 +905,13 @@ public class MidiSystem { */ public static int[] getMidiFileTypes() { - List providers = getMidiFileWriters(); - Set allTypes = new HashSet(); + List providers = getMidiFileWriters(); + Set allTypes = new HashSet<>(); // gather from all the providers for (int i = 0; i < providers.size(); i++ ) { - MidiFileWriter writer = (MidiFileWriter) providers.get(i); + MidiFileWriter writer = providers.get(i); int[] types = writer.getMidiFileTypes(); for (int j = 0; j < types.length; j++ ) { allTypes.add(new Integer(types[j])); @@ -919,9 +919,9 @@ public class MidiSystem { } int resultTypes[] = new int[allTypes.size()]; int index = 0; - Iterator iterator = allTypes.iterator(); + Iterator iterator = allTypes.iterator(); while (iterator.hasNext()) { - Integer integer = (Integer) iterator.next(); + Integer integer = iterator.next(); resultTypes[index++] = integer.intValue(); } return resultTypes; @@ -937,10 +937,10 @@ public class MidiSystem { */ public static boolean isFileTypeSupported(int fileType) { - List providers = getMidiFileWriters(); + List providers = getMidiFileWriters(); for (int i = 0; i < providers.size(); i++ ) { - MidiFileWriter writer = (MidiFileWriter) providers.get(i); + MidiFileWriter writer = providers.get(i); if( writer.isFileTypeSupported(fileType)) { return true; } @@ -959,13 +959,13 @@ public class MidiSystem { */ public static int[] getMidiFileTypes(Sequence sequence) { - List providers = getMidiFileWriters(); - Set allTypes = new HashSet(); + List providers = getMidiFileWriters(); + Set allTypes = new HashSet<>(); // gather from all the providers for (int i = 0; i < providers.size(); i++ ) { - MidiFileWriter writer = (MidiFileWriter) providers.get(i); + MidiFileWriter writer = providers.get(i); int[] types = writer.getMidiFileTypes(sequence); for (int j = 0; j < types.length; j++ ) { allTypes.add(new Integer(types[j])); @@ -973,9 +973,9 @@ public class MidiSystem { } int resultTypes[] = new int[allTypes.size()]; int index = 0; - Iterator iterator = allTypes.iterator(); + Iterator iterator = allTypes.iterator(); while (iterator.hasNext()) { - Integer integer = (Integer) iterator.next(); + Integer integer = iterator.next(); resultTypes[index++] = integer.intValue(); } return resultTypes; @@ -993,10 +993,10 @@ public class MidiSystem { */ public static boolean isFileTypeSupported(int fileType, Sequence sequence) { - List providers = getMidiFileWriters(); + List providers = getMidiFileWriters(); for (int i = 0; i < providers.size(); i++ ) { - MidiFileWriter writer = (MidiFileWriter) providers.get(i); + MidiFileWriter writer = providers.get(i); if( writer.isFileTypeSupported(fileType,sequence)) { return true; } @@ -1020,12 +1020,12 @@ public class MidiSystem { */ public static int write(Sequence in, int fileType, OutputStream out) throws IOException { - List providers = getMidiFileWriters(); + List providers = getMidiFileWriters(); //$$fb 2002-04-17: Fix for 4635287: Standard MidiFileWriter cannot write empty Sequences int bytesWritten = -2; for (int i = 0; i < providers.size(); i++ ) { - MidiFileWriter writer = (MidiFileWriter) providers.get(i); + MidiFileWriter writer = providers.get(i); if( writer.isFileTypeSupported( fileType, in ) ) { bytesWritten = writer.write(in, fileType, out); @@ -1054,12 +1054,12 @@ public class MidiSystem { */ public static int write(Sequence in, int type, File out) throws IOException { - List providers = getMidiFileWriters(); + List providers = getMidiFileWriters(); //$$fb 2002-04-17: Fix for 4635287: Standard MidiFileWriter cannot write empty Sequences int bytesWritten = -2; for (int i = 0; i < providers.size(); i++ ) { - MidiFileWriter writer = (MidiFileWriter) providers.get(i); + MidiFileWriter writer = providers.get(i); if( writer.isFileTypeSupported( type, in ) ) { bytesWritten = writer.write(in, type, out); @@ -1075,24 +1075,24 @@ public class MidiSystem { // HELPER METHODS - - private static List getMidiDeviceProviders() { - return getProviders(MidiDeviceProvider.class); + @SuppressWarnings("unchecked") + private static List getMidiDeviceProviders() { + return (List) getProviders(MidiDeviceProvider.class); } - - private static List getSoundbankReaders() { - return getProviders(SoundbankReader.class); + @SuppressWarnings("unchecked") + private static List getSoundbankReaders() { + return (List) getProviders(SoundbankReader.class); } - - private static List getMidiFileWriters() { - return getProviders(MidiFileWriter.class); + @SuppressWarnings("unchecked") + private static List getMidiFileWriters() { + return (List) getProviders(MidiFileWriter.class); } - - private static List getMidiFileReaders() { - return getProviders(MidiFileReader.class); + @SuppressWarnings("unchecked") + private static List getMidiFileReaders() { + return (List) getProviders(MidiFileReader.class); } @@ -1109,7 +1109,7 @@ public class MidiSystem { * Sequencer.class, Receiver.class or Transmitter.class. * @throws MidiUnavalableException on failure. */ - private static MidiDevice getDefaultDeviceWrapper(Class deviceClass) + private static MidiDevice getDefaultDeviceWrapper(Class deviceClass) throws MidiUnavailableException{ try { return getDefaultDevice(deviceClass); @@ -1128,8 +1128,8 @@ public class MidiSystem { * Sequencer.class, Receiver.class or Transmitter.class. * @throws IllegalArgumentException on failure. */ - private static MidiDevice getDefaultDevice(Class deviceClass) { - List providers = getMidiDeviceProviders(); + private static MidiDevice getDefaultDevice(Class deviceClass) { + List providers = getMidiDeviceProviders(); String providerClassName = JDK13Services.getDefaultProviderClassName(deviceClass); String instanceName = JDK13Services.getDefaultInstanceName(deviceClass); MidiDevice device; @@ -1179,9 +1179,10 @@ public class MidiSystem { @return A MidiDeviceProvider of the requested class, or null if none is found. */ - private static MidiDeviceProvider getNamedProvider(String providerClassName, List providers) { + private static MidiDeviceProvider getNamedProvider(String providerClassName, + List providers) { for(int i = 0; i < providers.size(); i++) { - MidiDeviceProvider provider = (MidiDeviceProvider) providers.get(i); + MidiDeviceProvider provider = providers.get(i); if (provider.getClass().getName().equals(providerClassName)) { return provider; } @@ -1200,7 +1201,7 @@ public class MidiSystem { */ private static MidiDevice getNamedDevice(String deviceName, MidiDeviceProvider provider, - Class deviceClass) { + Class deviceClass) { MidiDevice device; // try to get MIDI port device = getNamedDevice(deviceName, provider, deviceClass, @@ -1232,7 +1233,7 @@ public class MidiSystem { */ private static MidiDevice getNamedDevice(String deviceName, MidiDeviceProvider provider, - Class deviceClass, + Class deviceClass, boolean allowSynthesizer, boolean allowSequencer) { MidiDevice.Info[] infos = provider.getDeviceInfo(); @@ -1259,8 +1260,8 @@ public class MidiSystem { @return A Mixer matching the requirements, or null if none is found. */ private static MidiDevice getNamedDevice(String deviceName, - List providers, - Class deviceClass) { + List providers, + Class deviceClass) { MidiDevice device; // try to get MIDI port device = getNamedDevice(deviceName, providers, deviceClass, @@ -1292,12 +1293,12 @@ public class MidiSystem { @return A Mixer matching the requirements, or null if none is found. */ private static MidiDevice getNamedDevice(String deviceName, - List providers, - Class deviceClass, + List providers, + Class deviceClass, boolean allowSynthesizer, boolean allowSequencer) { for(int i = 0; i < providers.size(); i++) { - MidiDeviceProvider provider = (MidiDeviceProvider) providers.get(i); + MidiDeviceProvider provider = providers.get(i); MidiDevice device = getNamedDevice(deviceName, provider, deviceClass, allowSynthesizer, @@ -1318,7 +1319,7 @@ public class MidiSystem { appropriate device is found. */ private static MidiDevice getFirstDevice(MidiDeviceProvider provider, - Class deviceClass) { + Class deviceClass) { MidiDevice device; // try to get MIDI port device = getFirstDevice(provider, deviceClass, @@ -1348,7 +1349,7 @@ public class MidiSystem { appropriate device is found. */ private static MidiDevice getFirstDevice(MidiDeviceProvider provider, - Class deviceClass, + Class deviceClass, boolean allowSynthesizer, boolean allowSequencer) { MidiDevice.Info[] infos = provider.getDeviceInfo(); @@ -1371,8 +1372,8 @@ public class MidiSystem { @return A MidiDevice that is considered appropriate, or null if none is found. */ - private static MidiDevice getFirstDevice(List providers, - Class deviceClass) { + private static MidiDevice getFirstDevice(List providers, + Class deviceClass) { MidiDevice device; // try to get MIDI port device = getFirstDevice(providers, deviceClass, @@ -1402,12 +1403,12 @@ public class MidiSystem { @return A MidiDevice that is considered appropriate, or null if none is found. */ - private static MidiDevice getFirstDevice(List providers, - Class deviceClass, + private static MidiDevice getFirstDevice(List providers, + Class deviceClass, boolean allowSynthesizer, boolean allowSequencer) { for(int i = 0; i < providers.size(); i++) { - MidiDeviceProvider provider = (MidiDeviceProvider) providers.get(i); + MidiDeviceProvider provider = providers.get(i); MidiDevice device = getFirstDevice(provider, deviceClass, allowSynthesizer, allowSequencer); @@ -1441,11 +1442,11 @@ public class MidiSystem { rules given above, false otherwise. */ private static boolean isAppropriateDevice(MidiDevice device, - Class deviceClass, + Class deviceClass, boolean allowSynthesizer, boolean allowSequencer) { if (deviceClass.isInstance(device)) { - // This clause is for deviceClass being either Synthesizer + // This clause is for deviceClass being either Synthesizer // or Sequencer. return true; } else { @@ -1479,7 +1480,7 @@ public class MidiSystem { * @return a List of instances of providers for the requested service. * If no providers are available, a List of length 0 will be returned. */ - private static List getProviders(Class providerClass) { - return JDK13Services.getProviders(providerClass); + private static List getProviders(Class providerClass) { + return JDK13Services.getProviders(providerClass); } } diff --git a/jdk/src/share/classes/javax/sound/midi/SoundbankResource.java b/jdk/src/share/classes/javax/sound/midi/SoundbankResource.java index 87c0864a627..52ba8f78feb 100644 --- a/jdk/src/share/classes/javax/sound/midi/SoundbankResource.java +++ b/jdk/src/share/classes/javax/sound/midi/SoundbankResource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -83,7 +83,7 @@ public abstract class SoundbankResource { /** * The class used to represent the sample's data. */ - private final Class dataClass; + private final Class dataClass; /** diff --git a/jdk/src/share/classes/javax/sound/midi/Track.java b/jdk/src/share/classes/javax/sound/midi/Track.java index 4e54a8aa3dd..d9e0f438b6c 100644 --- a/jdk/src/share/classes/javax/sound/midi/Track.java +++ b/jdk/src/share/classes/javax/sound/midi/Track.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -66,10 +66,10 @@ public class Track { // TODO: use arrays for faster access // the list containing the events - private ArrayList eventsList = new ArrayList(); + private ArrayList eventsList = new ArrayList<>(); // use a hashset to detect duplicate events in add(MidiEvent) - private HashSet set = new HashSet(); + private HashSet set = new HashSet<>(); private MidiEvent eotEvent; @@ -108,7 +108,7 @@ public class Track { // get the last event MidiEvent lastEvent = null; if (eventsCount > 0) { - lastEvent = (MidiEvent) eventsList.get(eventsCount - 1); + lastEvent = eventsList.get(eventsCount - 1); } // sanity check that we have a correct end-of-track if (lastEvent != eotEvent) { @@ -148,7 +148,7 @@ public class Track { // tick order int i = eventsCount; for ( ; i > 0; i--) { - if (event.getTick() >= ((MidiEvent)eventsList.get(i-1)).getTick()) { + if (event.getTick() >= (eventsList.get(i-1)).getTick()) { break; } } @@ -220,7 +220,7 @@ public class Track { public MidiEvent get(int index) throws ArrayIndexOutOfBoundsException { try { synchronized(eventsList) { - return (MidiEvent)eventsList.get(index); + return eventsList.get(index); } } catch (IndexOutOfBoundsException ioobe) { throw new ArrayIndexOutOfBoundsException(ioobe.getMessage()); @@ -253,7 +253,7 @@ public class Track { long ret = 0; synchronized (eventsList) { if (eventsList.size() > 0) { - ret = ((MidiEvent)eventsList.get(eventsList.size() - 1)).getTick(); + ret = (eventsList.get(eventsList.size() - 1)).getTick(); } } return ret; diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioFileFormat.java b/jdk/src/share/classes/javax/sound/sampled/AudioFileFormat.java index 63f43dcc160..9c6ba5a3e4e 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioFileFormat.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioFileFormat.java @@ -25,36 +25,29 @@ package javax.sound.sampled; -import java.io.File; -import java.io.OutputStream; -import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; - /** - * An instance of the AudioFileFormat class describes - * an audio file, including the file type, the file's length in bytes, - * the length in sample frames of the audio data contained in the file, - * and the format of the audio data. + * An instance of the {@code AudioFileFormat} class describes an audio file, + * including the file type, the file's length in bytes, the length in sample + * frames of the audio data contained in the file, and the format of the audio + * data. *

    - * The {@link AudioSystem} class includes methods for determining the format - * of an audio file, obtaining an audio input stream from an audio file, and + * The {@link AudioSystem} class includes methods for determining the format of + * an audio file, obtaining an audio input stream from an audio file, and * writing an audio file from an audio input stream. - * - *

    An AudioFileFormat object can - * include a set of properties. A property is a pair of key and value: - * the key is of type String, the associated property - * value is an arbitrary object. - * Properties specify additional informational - * meta data (like a author, copyright, or file duration). - * Properties are optional information, and file reader and file - * writer implementations are not required to provide or - * recognize properties. - * - *

    The following table lists some common properties that should - * be used in implementations: + *

    + * An {@code AudioFileFormat} object can include a set of properties. A property + * is a pair of key and value: the key is of type {@code String}, the associated + * property value is an arbitrary object. Properties specify additional + * informational meta data (like a author, copyright, or file duration). + * Properties are optional information, and file reader and file writer + * implementations are not required to provide or recognize properties. + *

    + * The following table lists some common properties that should be used in + * implementations: * * * @@ -104,17 +97,13 @@ import java.util.Map; */ public class AudioFileFormat { - - // INSTANCE VARIABLES - - /** * File type. */ private Type type; /** - * File length in bytes + * File length in bytes. */ private int byteLength; @@ -124,25 +113,26 @@ public class AudioFileFormat { private AudioFormat format; /** - * Audio data length in sample frames + * Audio data length in sample frames. */ private int frameLength; - - /** The set of properties */ + /** + * The set of properties. + */ private HashMap properties; - /** - * Constructs an audio file format object. - * This protected constructor is intended for use by providers of file-reading - * services when returning information about an audio file or about supported audio file - * formats. - * @param type the type of the audio file - * @param byteLength the length of the file in bytes, or AudioSystem.NOT_SPECIFIED - * @param format the format of the audio data contained in the file - * @param frameLength the audio data length in sample frames, or AudioSystem.NOT_SPECIFIED + * Constructs an audio file format object. This protected constructor is + * intended for use by providers of file-reading services when returning + * information about an audio file or about supported audio file formats. * + * @param type the type of the audio file + * @param byteLength the length of the file in bytes, or + * {@code AudioSystem.NOT_SPECIFIED} + * @param format the format of the audio data contained in the file + * @param frameLength the audio data length in sample frames, or + * {@code AudioSystem.NOT_SPECIFIED} * @see #getType */ protected AudioFileFormat(Type type, int byteLength, AudioFormat format, int frameLength) { @@ -154,14 +144,15 @@ public class AudioFileFormat { this.properties = null; } - /** - * Constructs an audio file format object. - * This public constructor may be used by applications to describe the - * properties of a requested audio file. - * @param type the type of the audio file - * @param format the format of the audio data contained in the file - * @param frameLength the audio data length in sample frames, or AudioSystem.NOT_SPECIFIED + * Constructs an audio file format object. This public constructor may be + * used by applications to describe the properties of a requested audio + * file. + * + * @param type the type of the audio file + * @param format the format of the audio data contained in the file + * @param frameLength the audio data length in sample frames, or + * {@code AudioSystem.NOT_SPECIFIED} */ public AudioFileFormat(Type type, AudioFormat format, int frameLength) { @@ -170,19 +161,16 @@ public class AudioFileFormat { } /** - * Construct an audio file format object with a set of - * defined properties. + * Construct an audio file format object with a set of defined properties. * This public constructor may be used by applications to describe the - * properties of a requested audio file. The properties map - * will be copied to prevent any changes to it. - * - * @param type the type of the audio file - * @param format the format of the audio data contained in the file - * @param frameLength the audio data length in sample frames, or - * AudioSystem.NOT_SPECIFIED - * @param properties a Map<String,Object> object - * with properties + * properties of a requested audio file. The properties map will be copied + * to prevent any changes to it. * + * @param type the type of the audio file + * @param format the format of the audio data contained in the file + * @param frameLength the audio data length in sample frames, or + * {@code AudioSystem.NOT_SPECIFIED} + * @param properties a {@code Map} object with properties * @since 1.5 */ public AudioFileFormat(Type type, AudioFormat format, @@ -191,11 +179,10 @@ public class AudioFileFormat { this.properties = new HashMap(properties); } - /** - * Obtains the audio file type, such as WAVE or AU. - * @return the audio file type + * Obtains the audio file type, such as {@code WAVE} or {@code AU}. * + * @return the audio file type * @see Type#WAVE * @see Type#AU * @see Type#AIFF @@ -207,7 +194,9 @@ public class AudioFileFormat { } /** - * Obtains the size in bytes of the entire audio file (not just its audio data). + * Obtains the size in bytes of the entire audio file (not just its audio + * data). + * * @return the audio file length in bytes * @see AudioSystem#NOT_SPECIFIED */ @@ -217,6 +206,7 @@ public class AudioFileFormat { /** * Obtains the format of the audio data contained in the audio file. + * * @return the audio data format */ public AudioFormat getFormat() { @@ -224,7 +214,9 @@ public class AudioFileFormat { } /** - * Obtains the length of the audio data contained in the file, expressed in sample frames. + * Obtains the length of the audio data contained in the file, expressed in + * sample frames. + * * @return the number of sample frames of audio data in the file * @see AudioSystem#NOT_SPECIFIED */ @@ -233,41 +225,35 @@ public class AudioFileFormat { } /** - * Obtain an unmodifiable map of properties. - * The concept of properties is further explained in - * the {@link AudioFileFormat class description}. - * - * @return a Map<String,Object> object containing - * all properties. If no properties are recognized, an empty map is - * returned. + * Obtain an unmodifiable map of properties. The concept of properties is + * further explained in the {@link AudioFileFormat class description}. * + * @return a {@code Map} object containing all properties. + * If no properties are recognized, an empty map is returned. * @see #getProperty(String) * @since 1.5 */ - public Map properties() { + @SuppressWarnings("unchecked") // Cast of result of clone + public Map properties() { Map ret; if (properties == null) { - ret = new HashMap(0); + ret = new HashMap<>(0); } else { ret = (Map) (properties.clone()); } return Collections.unmodifiableMap(ret); } - /** - * Obtain the property value specified by the key. - * The concept of properties is further explained in - * the {@link AudioFileFormat class description}. - * - *

    If the specified property is not defined for a - * particular file format, this method returns - * null. - * - * @param key the key of the desired property - * @return the value of the property with the specified key, - * or null if the property does not exist. + * Obtain the property value specified by the key. The concept of properties + * is further explained in the {@link AudioFileFormat class description}. + *

    + * If the specified property is not defined for a particular file format, + * this method returns {@code null}. * + * @param key the key of the desired property + * @return the value of the property with the specified key, or {@code null} + * if the property does not exist * @see #properties() * @since 1.5 */ @@ -278,11 +264,12 @@ public class AudioFileFormat { return properties.get(key); } - /** * Provides a string representation of the file format. + * * @return the file format as a string */ + @Override public String toString() { StringBuffer buf = new StringBuffer(); @@ -307,11 +294,9 @@ public class AudioFileFormat { return new String(buf); } - /** - * An instance of the Type class represents one of the - * standard types of audio file. Static instances are provided for the - * common types. + * An instance of the {@code Type} class represents one of the standard + * types of audio file. Static instances are provided for the common types. */ public static class Type { @@ -342,9 +327,6 @@ public class AudioFileFormat { */ public static final Type SND = new Type("SND", "snd"); - - // INSTANCE VARIABLES - /** * File type name. */ @@ -355,27 +337,22 @@ public class AudioFileFormat { */ private final String extension; - - // CONSTRUCTOR - /** * Constructs a file type. - * @param name the string that names the file type - * @param extension the string that commonly marks the file type - * without leading dot. + * + * @param name the string that names the file type + * @param extension the string that commonly marks the file type + * without leading dot */ public Type(String name, String extension) { - this.name = name; this.extension = extension; } - - // METHODS - /** - * Finalizes the equals method + * Finalizes the equals method. */ + @Override public final boolean equals(Object obj) { if (toString() == null) { return (obj != null) && (obj.toString() == null); @@ -387,8 +364,9 @@ public class AudioFileFormat { } /** - * Finalizes the hashCode method + * Finalizes the hashCode method. */ + @Override public final int hashCode() { if (toString() == null) { return 0; @@ -397,22 +375,23 @@ public class AudioFileFormat { } /** - * Provides the file type's name as the String representation - * of the file type. + * Provides the file type's name as the {@code String} representation of + * the file type. + * * @return the file type's name */ + @Override public final String toString() { return name; } /** * Obtains the common file name extension for this file type. + * * @return file type extension */ public String getExtension() { return extension; } - - } // class Type - -} // class AudioFileFormat + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioFormat.java b/jdk/src/share/classes/javax/sound/sampled/AudioFormat.java index cd084fcd32d..39264aacf84 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioFormat.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioFormat.java @@ -30,59 +30,63 @@ import java.util.HashMap; import java.util.Map; /** - * AudioFormat is the class that specifies a particular arrangement of data in a sound stream. - * By examining the information stored in the audio format, you can discover how to interpret the bits in the - * binary sound data. + * {@code AudioFormat} is the class that specifies a particular arrangement of + * data in a sound stream. By examining the information stored in the audio + * format, you can discover how to interpret the bits in the binary sound data. *

    - * Every data line has an audio format associated with its data stream. The audio format of a source (playback) data line indicates - * what kind of data the data line expects to receive for output. For a target (capture) data line, the audio format specifies the kind - * of the data that can be read from the line. - * Sound files also have audio formats, of course. The {@link AudioFileFormat} - * class encapsulates an AudioFormat in addition to other, - * file-specific information. Similarly, an {@link AudioInputStream} has an - * AudioFormat. + * Every data line has an audio format associated with its data stream. The + * audio format of a source (playback) data line indicates what kind of data the + * data line expects to receive for output. For a target (capture) data line, + * the audio format specifies the kind of the data that can be read from the + * line. + * Sound files also have audio formats, of course. The {@link AudioFileFormat} + * class encapsulates an {@code AudioFormat} in addition to other, file-specific + * information. Similarly, an {@link AudioInputStream} has an + * {@code AudioFormat}. *

    - * The AudioFormat class accommodates a number of common sound-file encoding techniques, including - * pulse-code modulation (PCM), mu-law encoding, and a-law encoding. These encoding techniques are predefined, - * but service providers can create new encoding types. - * The encoding that a specific format uses is named by its encoding field. - *

    - * In addition to the encoding, the audio format includes other properties that further specify the exact - * arrangement of the data. - * These include the number of channels, sample rate, sample size, byte order, frame rate, and frame size. - * Sounds may have different numbers of audio channels: one for mono, two for stereo. - * The sample rate measures how many "snapshots" (samples) of the sound pressure are taken per second, per channel. - * (If the sound is stereo rather than mono, two samples are actually measured at each instant of time: one for the left channel, - * and another for the right channel; however, the sample rate still measures the number per channel, so the rate is the same - * regardless of the number of channels. This is the standard use of the term.) - * The sample size indicates how many bits are used to store each snapshot; 8 and 16 are typical values. - * For 16-bit samples (or any other sample size larger than a byte), - * byte order is important; the bytes in each sample are arranged in - * either the "little-endian" or "big-endian" style. - * For encodings like PCM, a frame consists of the set of samples for all channels at a given - * point in time, and so the size of a frame (in bytes) is always equal to the size of a sample (in bytes) times - * the number of channels. However, with some other sorts of encodings a frame can contain - * a bundle of compressed data for a whole series of samples, as well as additional, non-sample - * data. For such encodings, the sample rate and sample size refer to the data after it is decoded into PCM, - * and so they are completely different from the frame rate and frame size. - * - *

    An AudioFormat object can include a set of - * properties. A property is a pair of key and value: the key - * is of type String, the associated property - * value is an arbitrary object. Properties specify - * additional format specifications, like the bit rate for - * compressed formats. Properties are mainly used as a means - * to transport additional information of the audio format - * to and from the service providers. Therefore, properties - * are ignored in the {@link #matches(AudioFormat)} method. - * However, methods which rely on the installed service - * providers, like {@link AudioSystem#isConversionSupported - * (AudioFormat, AudioFormat) isConversionSupported} may consider - * properties, depending on the respective service provider - * implementation. - * - *

    The following table lists some common properties which - * service providers should use, if applicable: + * The {@code AudioFormat} class accommodates a number of common sound-file + * encoding techniques, including pulse-code modulation (PCM), mu-law encoding, + * and a-law encoding. These encoding techniques are predefined, but service + * providers can create new encoding types. The encoding that a specific format + * uses is named by its {@code encoding} field. + *

    + * In addition to the encoding, the audio format includes other properties that + * further specify the exact arrangement of the data. These include the number + * of channels, sample rate, sample size, byte order, frame rate, and frame + * size. Sounds may have different numbers of audio channels: one for mono, two + * for stereo. The sample rate measures how many "snapshots" (samples) of the + * sound pressure are taken per second, per channel. (If the sound is stereo + * rather than mono, two samples are actually measured at each instant of time: + * one for the left channel, and another for the right channel; however, the + * sample rate still measures the number per channel, so the rate is the same + * regardless of the number of channels. This is the standard use of the term.) + * The sample size indicates how many bits are used to store each snapshot; 8 + * and 16 are typical values. For 16-bit samples (or any other sample size + * larger than a byte), byte order is important; the bytes in each sample are + * arranged in either the "little-endian" or "big-endian" style. For encodings + * like PCM, a frame consists of the set of samples for all channels at a given + * point in time, and so the size of a frame (in bytes) is always equal to the + * size of a sample (in bytes) times the number of channels. However, with some + * other sorts of encodings a frame can contain a bundle of compressed data for + * a whole series of samples, as well as additional, non-sample data. For such + * encodings, the sample rate and sample size refer to the data after it is + * decoded into PCM, and so they are completely different from the frame rate + * and frame size. + *

    + * An {@code AudioFormat} object can include a set of properties. A property is + * a pair of key and value: the key is of type {@code String}, the associated + * property value is an arbitrary object. Properties specify additional format + * specifications, like the bit rate for compressed formats. Properties are + * mainly used as a means to transport additional information of the audio + * format to and from the service providers. Therefore, properties are ignored + * in the {@link #matches(AudioFormat)} method. However, methods which rely on + * the installed service providers, like + * {@link AudioSystem#isConversionSupported (AudioFormat, AudioFormat) + * isConversionSupported} may consider properties, depending on the respective + * service provider implementation. + *

    + * The following table lists some common properties which service providers + * should use, if applicable: * *

    Audio File Format Properties
    * @@ -99,7 +103,7 @@ import java.util.Map; * * * - * * * @@ -108,11 +112,10 @@ import java.util.Map; * * *
    Audio Format Properties
    "vbr"{@link java.lang.Boolean Boolean}true, if the file is encoded in variable bit + * {@code true}, if the file is encoded in variable bit * rate (VBR)
    encoding/conversion quality, 1..100
    - * - *

    Vendors of service providers (plugins) are encouraged - * to seek information about other already established - * properties in third party plugins, and follow the same - * conventions. + *

    + * Vendors of service providers (plugins) are encouraged to seek information + * about other already established properties in third party plugins, and follow + * the same conventions. * * @author Kara Kytle * @author Florian Bomers @@ -124,16 +127,14 @@ import java.util.Map; */ public class AudioFormat { - // INSTANCE VARIABLES - - /** * The audio encoding technique used by this format. */ protected Encoding encoding; /** - * The number of samples played or recorded per second, for sounds that have this format. + * The number of samples played or recorded per second, for sounds that have + * this format. */ protected float sampleRate; @@ -153,34 +154,37 @@ public class AudioFormat { protected int frameSize; /** - * The number of frames played or recorded per second, for sounds that have this format. + * The number of frames played or recorded per second, for sounds that have + * this format. */ protected float frameRate; /** - * Indicates whether the audio data is stored in big-endian or little-endian order. + * Indicates whether the audio data is stored in big-endian or little-endian + * order. */ protected boolean bigEndian; - - /** The set of properties */ + /** + * The set of properties. + */ private HashMap properties; - /** - * Constructs an AudioFormat with the given parameters. - * The encoding specifies the convention used to represent the data. - * The other parameters are further explained in the {@link AudioFormat - * class description}. - * @param encoding the audio encoding technique - * @param sampleRate the number of samples per second - * @param sampleSizeInBits the number of bits in each sample - * @param channels the number of channels (1 for mono, 2 for stereo, and so on) - * @param frameSize the number of bytes in each frame - * @param frameRate the number of frames per second - * @param bigEndian indicates whether the data for a single sample - * is stored in big-endian byte order (false - * means little-endian) + * Constructs an {@code AudioFormat} with the given parameters. The encoding + * specifies the convention used to represent the data. The other parameters + * are further explained in the {@link AudioFormat class description}. + * + * @param encoding the audio encoding technique + * @param sampleRate the number of samples per second + * @param sampleSizeInBits the number of bits in each sample + * @param channels the number of channels (1 for mono, 2 for stereo, + * and so on) + * @param frameSize the number of bytes in each frame + * @param frameRate the number of frames per second + * @param bigEndian indicates whether the data for a single sample is + * stored in big-endian byte order ({@code false} means + * little-endian) */ public AudioFormat(Encoding encoding, float sampleRate, int sampleSizeInBits, int channels, int frameSize, float frameRate, boolean bigEndian) { @@ -195,25 +199,22 @@ public class AudioFormat { this.properties = null; } - /** - * Constructs an AudioFormat with the given parameters. - * The encoding specifies the convention used to represent the data. - * The other parameters are further explained in the {@link AudioFormat - * class description}. - * @param encoding the audio encoding technique - * @param sampleRate the number of samples per second - * @param sampleSizeInBits the number of bits in each sample - * @param channels the number of channels (1 for mono, 2 for - * stereo, and so on) - * @param frameSize the number of bytes in each frame - * @param frameRate the number of frames per second - * @param bigEndian indicates whether the data for a single sample - * is stored in big-endian byte order - * (false means little-endian) - * @param properties a Map<String,Object> object - * containing format properties + * Constructs an {@code AudioFormat} with the given parameters. The encoding + * specifies the convention used to represent the data. The other parameters + * are further explained in the {@link AudioFormat class description}. * + * @param encoding the audio encoding technique + * @param sampleRate the number of samples per second + * @param sampleSizeInBits the number of bits in each sample + * @param channels the number of channels (1 for mono, 2 for stereo, and so + * on) + * @param frameSize the number of bytes in each frame + * @param frameRate the number of frames per second + * @param bigEndian indicates whether the data for a single sample is + * stored in big-endian byte order ({@code false} means little-endian) + * @param properties a {@code Map} object containing format + * properties * @since 1.5 */ public AudioFormat(Encoding encoding, float sampleRate, @@ -225,20 +226,20 @@ public class AudioFormat { this.properties = new HashMap(properties); } - /** - * Constructs an AudioFormat with a linear PCM encoding and - * the given parameters. The frame size is set to the number of bytes - * required to contain one sample from each channel, and the frame rate - * is set to the sample rate. + * Constructs an {@code AudioFormat} with a linear PCM encoding and the + * given parameters. The frame size is set to the number of bytes required + * to contain one sample from each channel, and the frame rate is set to the + * sample rate. * - * @param sampleRate the number of samples per second - * @param sampleSizeInBits the number of bits in each sample - * @param channels the number of channels (1 for mono, 2 for stereo, and so on) - * @param signed indicates whether the data is signed or unsigned - * @param bigEndian indicates whether the data for a single sample - * is stored in big-endian byte order (false - * means little-endian) + * @param sampleRate the number of samples per second + * @param sampleSizeInBits the number of bits in each sample + * @param channels the number of channels (1 for mono, 2 for stereo, and so + * on) + * @param signed indicates whether the data is signed or unsigned + * @param bigEndian indicates whether the data for a single sample is + * stored in big-endian byte order ({@code false} means + * little-endian) */ public AudioFormat(float sampleRate, int sampleSizeInBits, int channels, boolean signed, boolean bigEndian) { @@ -269,19 +270,17 @@ public class AudioFormat { } /** - * Obtains the sample rate. - * For compressed formats, the return value is the sample rate of the uncompressed - * audio data. - * When this AudioFormat is used for queries (e.g. {@link - * AudioSystem#isConversionSupported(AudioFormat, AudioFormat) - * AudioSystem.isConversionSupported}) or capabilities (e.g. {@link - * DataLine.Info#getFormats() DataLine.Info.getFormats}), a sample rate of - * AudioSystem.NOT_SPECIFIED means that any sample rate is - * acceptable. AudioSystem.NOT_SPECIFIED is also returned when - * the sample rate is not defined for this audio format. - * @return the number of samples per second, - * or AudioSystem.NOT_SPECIFIED + * Obtains the sample rate. For compressed formats, the return value is the + * sample rate of the uncompressed audio data. When this AudioFormat is used + * for queries (e.g. {@link AudioSystem#isConversionSupported(AudioFormat, + * AudioFormat) AudioSystem.isConversionSupported}) or capabilities (e.g. + * {@link DataLine.Info#getFormats DataLine.Info.getFormats}), a sample rate + * of {@code AudioSystem.NOT_SPECIFIED} means that any sample rate is + * acceptable. {@code AudioSystem.NOT_SPECIFIED} is also returned when the + * sample rate is not defined for this audio format. * + * @return the number of samples per second, or + * {@code AudioSystem.NOT_SPECIFIED} * @see #getFrameRate() * @see AudioSystem#NOT_SPECIFIED */ @@ -291,19 +290,18 @@ public class AudioFormat { } /** - * Obtains the size of a sample. - * For compressed formats, the return value is the sample size of the - * uncompressed audio data. - * When this AudioFormat is used for queries (e.g. {@link - * AudioSystem#isConversionSupported(AudioFormat, AudioFormat) - * AudioSystem.isConversionSupported}) or capabilities (e.g. {@link - * DataLine.Info#getFormats() DataLine.Info.getFormats}), a sample size of - * AudioSystem.NOT_SPECIFIED means that any sample size is - * acceptable. AudioSystem.NOT_SPECIFIED is also returned when - * the sample size is not defined for this audio format. - * @return the number of bits in each sample, - * or AudioSystem.NOT_SPECIFIED + * Obtains the size of a sample. For compressed formats, the return value is + * the sample size of the uncompressed audio data. When this AudioFormat is + * used for queries (e.g. {@link AudioSystem#isConversionSupported( + * AudioFormat,AudioFormat) AudioSystem.isConversionSupported}) or + * capabilities (e.g. + * {@link DataLine.Info#getFormats DataLine.Info.getFormats}), a sample size + * of {@code AudioSystem.NOT_SPECIFIED} means that any sample size is + * acceptable. {@code AudioSystem.NOT_SPECIFIED} is also returned when the + * sample size is not defined for this audio format. * + * @return the number of bits in each sample, or + * {@code AudioSystem.NOT_SPECIFIED} * @see #getFrameSize() * @see AudioSystem#NOT_SPECIFIED */ @@ -313,16 +311,15 @@ public class AudioFormat { } /** - * Obtains the number of channels. - * When this AudioFormat is used for queries (e.g. {@link - * AudioSystem#isConversionSupported(AudioFormat, AudioFormat) - * AudioSystem.isConversionSupported}) or capabilities (e.g. {@link - * DataLine.Info#getFormats() DataLine.Info.getFormats}), a return value of - * AudioSystem.NOT_SPECIFIED means that any (positive) number of channels is - * acceptable. - * @return The number of channels (1 for mono, 2 for stereo, etc.), - * or AudioSystem.NOT_SPECIFIED + * Obtains the number of channels. When this AudioFormat is used for queries + * (e.g. {@link AudioSystem#isConversionSupported(AudioFormat, AudioFormat) + * AudioSystem.isConversionSupported}) or capabilities (e.g. + * {@link DataLine.Info#getFormats DataLine.Info.getFormats}), a return + * value of {@code AudioSystem.NOT_SPECIFIED} means that any (positive) + * number of channels is acceptable. * + * @return The number of channels (1 for mono, 2 for stereo, etc.), or + * {@code AudioSystem.NOT_SPECIFIED} * @see AudioSystem#NOT_SPECIFIED */ public int getChannels() { @@ -331,17 +328,16 @@ public class AudioFormat { } /** - * Obtains the frame size in bytes. - * When this AudioFormat is used for queries (e.g. {@link - * AudioSystem#isConversionSupported(AudioFormat, AudioFormat) - * AudioSystem.isConversionSupported}) or capabilities (e.g. {@link - * DataLine.Info#getFormats() DataLine.Info.getFormats}), a frame size of - * AudioSystem.NOT_SPECIFIED means that any frame size is - * acceptable. AudioSystem.NOT_SPECIFIED is also returned when - * the frame size is not defined for this audio format. - * @return the number of bytes per frame, - * or AudioSystem.NOT_SPECIFIED + * Obtains the frame size in bytes. When this AudioFormat is used for + * queries (e.g. {@link AudioSystem#isConversionSupported(AudioFormat, + * AudioFormat) AudioSystem.isConversionSupported}) or capabilities (e.g. + * {@link DataLine.Info#getFormats DataLine.Info.getFormats}), a frame size + * of {@code AudioSystem.NOT_SPECIFIED} means that any frame size is + * acceptable. {@code AudioSystem.NOT_SPECIFIED} is also returned when the + * frame size is not defined for this audio format. * + * @return the number of bytes per frame, or + * {@code AudioSystem.NOT_SPECIFIED} * @see #getSampleSizeInBits() * @see AudioSystem#NOT_SPECIFIED */ @@ -351,17 +347,17 @@ public class AudioFormat { } /** - * Obtains the frame rate in frames per second. - * When this AudioFormat is used for queries (e.g. {@link - * AudioSystem#isConversionSupported(AudioFormat, AudioFormat) - * AudioSystem.isConversionSupported}) or capabilities (e.g. {@link - * DataLine.Info#getFormats() DataLine.Info.getFormats}), a frame rate of - * AudioSystem.NOT_SPECIFIED means that any frame rate is - * acceptable. AudioSystem.NOT_SPECIFIED is also returned when - * the frame rate is not defined for this audio format. - * @return the number of frames per second, - * or AudioSystem.NOT_SPECIFIED + * Obtains the frame rate in frames per second. When this AudioFormat is + * used for queries (e.g. {@link AudioSystem#isConversionSupported( + * AudioFormat,AudioFormat) AudioSystem.isConversionSupported}) or + * capabilities (e.g. + * {@link DataLine.Info#getFormats DataLine.Info.getFormats}), a frame rate + * of {@code AudioSystem.NOT_SPECIFIED} means that any frame rate is + * acceptable. {@code AudioSystem.NOT_SPECIFIED} is also returned when the + * frame rate is not defined for this audio format. * + * @return the number of frames per second, or + * {@code AudioSystem.NOT_SPECIFIED} * @see #getSampleRate() * @see AudioSystem#NOT_SPECIFIED */ @@ -370,56 +366,49 @@ public class AudioFormat { return frameRate; } - /** * Indicates whether the audio data is stored in big-endian or little-endian - * byte order. If the sample size is not more than one byte, the return value is - * irrelevant. - * @return true if the data is stored in big-endian byte order, - * false if little-endian + * byte order. If the sample size is not more than one byte, the return + * value is irrelevant. + * + * @return {@code true} if the data is stored in big-endian byte order, + * {@code false} if little-endian */ public boolean isBigEndian() { return bigEndian; } - /** - * Obtain an unmodifiable map of properties. - * The concept of properties is further explained in - * the {@link AudioFileFormat class description}. - * - * @return a Map<String,Object> object containing - * all properties. If no properties are recognized, an empty map is - * returned. + * Obtain an unmodifiable map of properties. The concept of properties is + * further explained in the {@link AudioFileFormat class description}. * + * @return a {@code Map} object containing all properties. + * If no properties are recognized, an empty map is returned. * @see #getProperty(String) * @since 1.5 */ + @SuppressWarnings("unchecked") // Cast of result of clone. public Map properties() { Map ret; if (properties == null) { - ret = new HashMap(0); + ret = new HashMap<>(0); } else { ret = (Map) (properties.clone()); } return Collections.unmodifiableMap(ret); } - /** - * Obtain the property value specified by the key. - * The concept of properties is further explained in - * the {@link AudioFileFormat class description}. - * - *

    If the specified property is not defined for a - * particular file format, this method returns - * null. - * - * @param key the key of the desired property - * @return the value of the property with the specified key, - * or null if the property does not exist. + * Obtain the property value specified by the key. The concept of properties + * is further explained in the {@link AudioFileFormat class description}. + *

    + * If the specified property is not defined for a particular file format, + * this method returns {@code null}. * + * @param key the key of the desired property + * @return the value of the property with the specified key, or {@code null} + * if the property does not exist * @see #properties() * @since 1.5 */ @@ -430,21 +419,18 @@ public class AudioFormat { return properties.get(key); } - /** - * Indicates whether this format matches the one specified. - * To match, two formats must have the same encoding, - * and consistent values of the number of channels, sample rate, sample size, - * frame rate, and frame size. - * The values of the property are consistent if they are equal - * or the specified format has the property value - * {@code AudioSystem.NOT_SPECIFIED}. - * The byte order (big-endian or little-endian) must be the same - * if the sample size is greater than one byte. + * Indicates whether this format matches the one specified. To match, two + * formats must have the same encoding, and consistent values of the number + * of channels, sample rate, sample size, frame rate, and frame size. The + * values of the property are consistent if they are equal or the specified + * format has the property value {@code AudioSystem.NOT_SPECIFIED}. The byte + * order (big-endian or little-endian) must be the same if the sample size + * is greater than one byte. * - * @param format format to test for match + * @param format format to test for match * @return {@code true} if this format matches the one specified, - * {@code false} otherwise. + * {@code false} otherwise */ public boolean matches(AudioFormat format) { if (format.getEncoding().equals(getEncoding()) @@ -465,14 +451,14 @@ public class AudioFormat { return false; } - /** - * Returns a string that describes the format, such as: - * "PCM SIGNED 22050 Hz 16 bit mono big-endian". The contents of the string - * may vary between implementations of Java Sound. + * Returns a string that describes the format, such as: "PCM SIGNED 22050 Hz + * 16 bit mono big-endian". The contents of the string may vary between + * implementations of Java Sound. * * @return a string that describes the format parameters */ + @Override public String toString() { String sEncoding = ""; if (getEncoding() != null) { @@ -546,42 +532,36 @@ public class AudioFormat { } /** - * The Encoding class names the specific type of data representation - * used for an audio stream. The encoding includes aspects of the - * sound format other than the number of channels, sample rate, sample size, - * frame rate, frame size, and byte order. + * The {@code Encoding} class names the specific type of data representation + * used for an audio stream. The encoding includes aspects of the sound + * format other than the number of channels, sample rate, sample size, frame + * rate, frame size, and byte order. *

    * One ubiquitous type of audio encoding is pulse-code modulation (PCM), * which is simply a linear (proportional) representation of the sound - * waveform. With PCM, the number stored in each sample is proportional - * to the instantaneous amplitude of the sound pressure at that point in - * time. The numbers may be signed or unsigned integers or floats. - * Besides PCM, other encodings include mu-law and a-law, which are nonlinear - * mappings of the sound amplitude that are often used for recording speech. + * waveform. With PCM, the number stored in each sample is proportional to + * the instantaneous amplitude of the sound pressure at that point in time. + * The numbers may be signed or unsigned integers or floats. Besides PCM, + * other encodings include mu-law and a-law, which are nonlinear mappings of + * the sound amplitude that are often used for recording speech. *

    * You can use a predefined encoding by referring to one of the static - * objects created by this class, such as PCM_SIGNED or - * PCM_UNSIGNED. Service providers can create new encodings, such as - * compressed audio formats, and make - * these available through the {@link AudioSystem} class. + * objects created by this class, such as PCM_SIGNED or PCM_UNSIGNED. + * Service providers can create new encodings, such as compressed audio + * formats, and make these available through the {@link AudioSystem} class. *

    - * The Encoding class is static, so that all - * AudioFormat objects that have the same encoding will refer - * to the same object (rather than different instances of the same class). - * This allows matches to be made by checking that two format's encodings - * are equal. - * - * @see AudioFormat - * @see javax.sound.sampled.spi.FormatConversionProvider + * The {@code Encoding} class is static, so that all {@code AudioFormat} + * objects that have the same encoding will refer to the same object (rather + * than different instances of the same class). This allows matches to be + * made by checking that two format's encodings are equal. * * @author Kara Kytle + * @see AudioFormat + * @see javax.sound.sampled.spi.FormatConversionProvider * @since 1.3 */ public static class Encoding { - - // ENCODING DEFINES - /** * Specifies signed, linear PCM data. */ @@ -609,31 +589,24 @@ public class AudioFormat { */ public static final Encoding ALAW = new Encoding("ALAW"); - - // INSTANCE VARIABLES - /** * Encoding name. */ private String name; - - // CONSTRUCTOR - /** * Constructs a new encoding. - * @param name the name of the new type of encoding + * + * @param name the name of the new type of encoding */ public Encoding(String name) { this.name = name; } - - // METHODS - /** - * Finalizes the equals method + * Finalizes the equals method. */ + @Override public final boolean equals(Object obj) { if (toString() == null) { return (obj != null) && (obj.toString() == null); @@ -645,8 +618,9 @@ public class AudioFormat { } /** - * Finalizes the hashCode method + * Finalizes the hashCode method. */ + @Override public final int hashCode() { if (toString() == null) { return 0; @@ -655,16 +629,17 @@ public class AudioFormat { } /** - * Provides the String representation of the encoding. This String is - * the same name that was passed to the constructor. For the predefined encodings, the name - * is similar to the encoding's variable (field) name. For example, PCM_SIGNED.toString() returns - * the name "pcm_signed". + * Provides the {@code String} representation of the encoding. This + * {@code String} is the same name that was passed to the constructor. + * For the predefined encodings, the name is similar to the encoding's + * variable (field) name. For example, {@code PCM_SIGNED.toString()} + * returns the name "pcm_signed". * * @return the encoding name */ + @Override public final String toString() { return name; } - - } // class Encoding + } } diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioInputStream.java b/jdk/src/share/classes/javax/sound/sampled/AudioInputStream.java index ea4162fa2f3..14e7b537f1b 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioInputStream.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,27 +25,24 @@ package javax.sound.sampled; -import java.io.InputStream; -import java.io.PushbackInputStream; import java.io.IOException; +import java.io.InputStream; /** * An audio input stream is an input stream with a specified audio format and - * length. The length is expressed in sample frames, not bytes. - * Several methods are provided for reading a certain number of bytes from - * the stream, or an unspecified number of bytes. - * The audio input stream keeps track of the last byte that was read. - * You can skip over an arbitrary number of bytes to get to a later position - * for reading. An audio input stream may support marks. When you set a mark, - * the current position is remembered so that you can return to it later. + * length. The length is expressed in sample frames, not bytes. Several methods + * are provided for reading a certain number of bytes from the stream, or an + * unspecified number of bytes. The audio input stream keeps track of the last + * byte that was read. You can skip over an arbitrary number of bytes to get to + * a later position for reading. An audio input stream may support marks. When + * you set a mark, the current position is remembered so that you can return to + * it later. *

    - * The AudioSystem class includes many methods that manipulate - * AudioInputStream objects. - * For example, the methods let you: + * The {@code AudioSystem} class includes many methods that manipulate + * {@code AudioInputStream} objects. For example, the methods let you: *

      - *
    • obtain an - * audio input stream from an external audio file, stream, or URL + *
    • obtain an audio input stream from an external audio file, stream, or URL *
    • write an external file from an audio input stream *
    • convert an audio input stream to a different audio format *
    @@ -53,16 +50,15 @@ import java.io.IOException; * @author David Rivas * @author Kara Kytle * @author Florian Bomers - * * @see AudioSystem - * @see Clip#open(AudioInputStream) Clip.open(AudioInputStream) + * @see Clip#open(AudioInputStream) * @since 1.3 */ public class AudioInputStream extends InputStream { /** - * The InputStream from which this AudioInputStream - * object was constructed. + * The {@code InputStream} from which this {@code AudioInputStream} object + * was constructed. */ private InputStream stream; @@ -92,35 +88,34 @@ public class AudioInputStream extends InputStream { private long markpos; /** - * When the underlying stream could only return - * a non-integral number of frames, store - * the remainder in a temporary buffer + * When the underlying stream could only return a non-integral number of + * frames, store the remainder in a temporary buffer. */ private byte[] pushBackBuffer = null; /** - * number of valid bytes in the pushBackBuffer + * number of valid bytes in the pushBackBuffer. */ private int pushBackLen = 0; /** - * MarkBuffer at mark position + * MarkBuffer at mark position. */ private byte[] markPushBackBuffer = null; /** - * number of valid bytes in the markPushBackBuffer + * number of valid bytes in the markPushBackBuffer. */ private int markPushBackLen = 0; - /** - * Constructs an audio input stream that has the requested format and length in sample frames, - * using audio data from the specified input stream. - * @param stream the stream on which this AudioInputStream - * object is based - * @param format the format of this stream's audio data - * @param length the length in sample frames of the data in this stream + * Constructs an audio input stream that has the requested format and length + * in sample frames, using audio data from the specified input stream. + * + * @param stream the stream on which this {@code AudioInputStream} object + * is based + * @param format the format of this stream's audio data + * @param length the length in sample frames of the data in this stream */ public AudioInputStream(InputStream stream, AudioFormat format, long length) { @@ -141,12 +136,12 @@ public class AudioInputStream extends InputStream { markpos = 0; } - /** - * Constructs an audio input stream that reads its data from the target - * data line indicated. The format of the stream is the same as that of - * the target data line, and the length is AudioSystem#NOT_SPECIFIED. - * @param line the target data line from which this stream obtains its data. + * Constructs an audio input stream that reads its data from the target data + * line indicated. The format of the stream is the same as that of the + * target data line, and the length is AudioSystem#NOT_SPECIFIED. + * + * @param line the target data line from which this stream obtains its data * @see AudioSystem#NOT_SPECIFIED */ public AudioInputStream(TargetDataLine line) { @@ -164,29 +159,29 @@ public class AudioInputStream extends InputStream { markpos = 0; } - /** * Obtains the audio format of the sound data in this audio input stream. + * * @return an audio format object describing this stream's format */ public AudioFormat getFormat() { return format; } - /** - * Obtains the length of the stream, expressed in sample frames rather than bytes. + * Obtains the length of the stream, expressed in sample frames rather than + * bytes. + * * @return the length in sample frames */ public long getFrameLength() { return frameLength; } - /** - * Reads the next byte of data from the audio input stream. The audio input - * stream's frame size must be one byte, or an IOException - * will be thrown. + * Reads the next byte of data from the audio input stream. The audio input + * stream's frame size must be one byte, or an {@code IOException} will be + * thrown. * * @return the next byte of data, or -1 if the end of the stream is reached * @throws IOException if an input or output error occurs @@ -194,6 +189,7 @@ public class AudioInputStream extends InputStream { * @see #read(byte[]) * @see #available */ + @Override public int read() throws IOException { if( frameSize != 1 ) { throw new IOException("cannot read a single byte if frame size > 1"); @@ -208,50 +204,50 @@ public class AudioInputStream extends InputStream { return data[0] & 0xFF; } - /** - * Reads some number of bytes from the audio input stream and stores them into - * the buffer array b. The number of bytes actually read is - * returned as an integer. This method blocks until input data is - * available, the end of the stream is detected, or an exception is thrown. - *

    This method will always read an integral number of frames. - * If the length of the array is not an integral number - * of frames, a maximum of b.length - (b.length % frameSize) - * bytes will be read. + * Reads some number of bytes from the audio input stream and stores them + * into the buffer array {@code b}. The number of bytes actually read is + * returned as an integer. This method blocks until input data is available, + * the end of the stream is detected, or an exception is thrown. + *

    + * This method will always read an integral number of frames. If the length + * of the array is not an integral number of frames, a maximum of + * {@code b.length - (b.length % frameSize)} bytes will be read. * - * @param b the buffer into which the data is read - * @return the total number of bytes read into the buffer, or -1 if there - * is no more data because the end of the stream has been reached + * @param b the buffer into which the data is read + * @return the total number of bytes read into the buffer, or -1 if there is + * no more data because the end of the stream has been reached * @throws IOException if an input or output error occurs * @see #read(byte[], int, int) * @see #read() * @see #available */ + @Override public int read(byte[] b) throws IOException { return read(b,0,b.length); } - /** * Reads up to a specified maximum number of bytes of data from the audio * stream, putting them into the given byte array. - *

    This method will always read an integral number of frames. - * If len does not specify an integral number - * of frames, a maximum of len - (len % frameSize) - * bytes will be read. + *

    + * This method will always read an integral number of frames. If {@code len} + * does not specify an integral number of frames, a maximum of + * {@code len - (len % frameSize)} bytes will be read. * - * @param b the buffer into which the data is read - * @param off the offset, from the beginning of array b, at which - * the data will be written - * @param len the maximum number of bytes to read - * @return the total number of bytes read into the buffer, or -1 if there - * is no more data because the end of the stream has been reached + * @param b the buffer into which the data is read + * @param off the offset, from the beginning of array {@code b}, at which + * the data will be written + * @param len the maximum number of bytes to read + * @return the total number of bytes read into the buffer, or -1 if there is + * no more data because the end of the stream has been reached * @throws IOException if an input or output error occurs * @see #read(byte[]) * @see #read() * @see #skip * @see #available */ + @Override public int read(byte[] b, int off, int len) throws IOException { // make sure we don't read fractions of a frame. @@ -313,16 +309,17 @@ public class AudioInputStream extends InputStream { return bytesRead; } - /** - * Skips over and discards a specified number of bytes from this - * audio input stream. - * @param n the requested number of bytes to be skipped + * Skips over and discards a specified number of bytes from this audio input + * stream. + * + * @param n the requested number of bytes to be skipped * @return the actual number of bytes skipped * @throws IOException if an input or output error occurs * @see #read * @see #available */ + @Override public long skip(long n) throws IOException { // make sure not to skip fractional frames @@ -351,21 +348,23 @@ public class AudioInputStream extends InputStream { } - /** - * Returns the maximum number of bytes that can be read (or skipped over) from this - * audio input stream without blocking. This limit applies only to the next invocation of - * a read or skip method for this audio input stream; the limit - * can vary each time these methods are invoked. - * Depending on the underlying stream,an IOException may be thrown if this - * stream is closed. - * @return the number of bytes that can be read from this audio input stream without blocking + * Returns the maximum number of bytes that can be read (or skipped over) + * from this audio input stream without blocking. This limit applies only + * to the next invocation of a {@code read} or {@code skip} method for this + * audio input stream; the limit can vary each time these methods are + * invoked. Depending on the underlying stream, an IOException may be thrown + * if this stream is closed. + * + * @return the number of bytes that can be read from this audio input stream + * without blocking * @throws IOException if an input or output error occurs * @see #read(byte[], int, int) * @see #read(byte[]) * @see #read() * @see #skip */ + @Override public int available() throws IOException { int temp = stream.available(); @@ -378,25 +377,26 @@ public class AudioInputStream extends InputStream { } } - /** - * Closes this audio input stream and releases any system resources associated - * with the stream. + * Closes this audio input stream and releases any system resources + * associated with the stream. + * * @throws IOException if an input or output error occurs */ + @Override public void close() throws IOException { stream.close(); } - /** * Marks the current position in this audio input stream. - * @param readlimit the maximum number of bytes that can be read before - * the mark position becomes invalid. + * + * @param readlimit the maximum number of bytes that can be read before the + * mark position becomes invalid. * @see #reset * @see #markSupported */ - + @Override public void mark(int readlimit) { stream.mark(readlimit); @@ -413,14 +413,15 @@ public class AudioInputStream extends InputStream { } } - /** - * Repositions this audio input stream to the position it had at the time its - * mark method was last invoked. - * @throws IOException if an input or output error occurs. + * Repositions this audio input stream to the position it had at the time + * its {@code mark} method was last invoked. + * + * @throws IOException if an input or output error occurs * @see #mark * @see #markSupported */ + @Override public void reset() throws IOException { stream.reset(); @@ -435,21 +436,21 @@ public class AudioInputStream extends InputStream { } } - /** - * Tests whether this audio input stream supports the mark and - * reset methods. - * @return true if this stream supports the mark - * and reset methods; false otherwise + * Tests whether this audio input stream supports the {@code mark} and + * {@code reset} methods. + * + * @return {@code true} if this stream supports the {@code mark} and + * {@code reset} methods; {@code false} otherwise * @see #mark * @see #reset */ + @Override public boolean markSupported() { return stream.markSupported(); } - /** * Private inner class that makes a TargetDataLine look like an InputStream. */ @@ -460,19 +461,19 @@ public class AudioInputStream extends InputStream { */ TargetDataLine line; - TargetDataLineInputStream(TargetDataLine line) { super(); this.line = line; } - + @Override public int available() throws IOException { return line.available(); } //$$fb 2001-07-16: added this method to correctly close the underlying TargetDataLine. // fixes bug 4479984 + @Override public void close() throws IOException { // the line needs to be flushed and stopped to avoid a dead lock... // Probably related to bugs 4417527, 4334868, 4383457 @@ -483,6 +484,7 @@ public class AudioInputStream extends InputStream { line.close(); } + @Override public int read() throws IOException { byte[] b = new byte[1]; @@ -502,7 +504,7 @@ public class AudioInputStream extends InputStream { return value; } - + @Override public int read(byte[] b, int off, int len) throws IOException { try { return line.read(b, off, len); diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioPermission.java b/jdk/src/share/classes/javax/sound/sampled/AudioPermission.java index 4e7dcef9602..13655254bf0 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioPermission.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioPermission.java @@ -28,18 +28,18 @@ package javax.sound.sampled; import java.security.BasicPermission; /** - * The AudioPermission class represents access rights to the audio - * system resources. An AudioPermission contains a target name - * but no actions list; you either have the named permission or you don't. + * The {@code AudioPermission} class represents access rights to the audio + * system resources. An {@code AudioPermission} contains a target name but no + * actions list; you either have the named permission or you don't. *

    * The target name is the name of the audio permission (see the table below). - * The names follow the hierarchical property-naming convention. Also, an asterisk - * can be used to represent all the audio permissions. + * The names follow the hierarchical property-naming convention. Also, an + * asterisk can be used to represent all the audio permissions. *

    - * The following table lists the possible AudioPermission target names. - * For each name, the table provides a description of exactly what that permission - * allows, as well as a discussion of the risks of granting code the permission. - * + * The following table lists the possible {@code AudioPermission} target names. + * For each name, the table provides a description of exactly what that + * permission allows, as well as a discussion of the risks of granting code the + * permission. * * * @@ -57,7 +57,7 @@ import java.security.BasicPermission; * applications because the audio from one line may be mixed with other audio * being played on the system, or because manipulation of a mixer affects the * audio for all lines using that mixer. - * + * * * * @@ -68,42 +68,40 @@ import java.security.BasicPermission; * applications because manipulation of a mixer affects the audio for all lines * using that mixer. * This permission can enable an applet or application to eavesdrop on a user. - * - *
    record
    - *

    + * + * * * @author Kara Kytle * @since 1.3 */ public class AudioPermission extends BasicPermission { + private static final long serialVersionUID = -5518053473477801126L; /** - * Creates a new AudioPermission object that has the specified - * symbolic name, such as "play" or "record". An asterisk can be used to indicate - * all audio permissions. - * @param name the name of the new AudioPermission + * Creates a new {@code AudioPermission} object that has the specified + * symbolic name, such as "play" or "record". An asterisk can be used to + * indicate all audio permissions. * - * @throws NullPointerException if name is null. - * @throws IllegalArgumentException if name is empty. + * @param name the name of the new {@code AudioPermission} + * @throws NullPointerException if {@code name} is {@code null} + * @throws IllegalArgumentException if {@code name} is empty */ - public AudioPermission(String name) { - + public AudioPermission(final String name) { super(name); } /** - * Creates a new AudioPermission object that has the specified - * symbolic name, such as "play" or "record". The actions - * parameter is currently unused and should be null. - * @param name the name of the new AudioPermission - * @param actions (unused; should be null) + * Creates a new {@code AudioPermission} object that has the specified + * symbolic name, such as "play" or "record". The {@code actions} parameter + * is currently unused and should be {@code null}. * - * @throws NullPointerException if name is null. - * @throws IllegalArgumentException if name is empty. + * @param name the name of the new {@code AudioPermission} + * @param actions (unused; should be {@code null}) + * @throws NullPointerException if {@code name} is {@code null} + * @throws IllegalArgumentException if {@code name} is empty */ - public AudioPermission(String name, String actions) { - + public AudioPermission(final String name, final String actions) { super(name, actions); } } diff --git a/jdk/src/share/classes/javax/sound/sampled/AudioSystem.java b/jdk/src/share/classes/javax/sound/sampled/AudioSystem.java index 235ed234276..459ef997855 100644 --- a/jdk/src/share/classes/javax/sound/sampled/AudioSystem.java +++ b/jdk/src/share/classes/javax/sound/sampled/AudioSystem.java @@ -50,29 +50,24 @@ import com.sun.media.sound.JDK13Services; /** - * The AudioSystem class acts as the entry point to the - * sampled-audio system resources. This class lets you query and - * access the mixers that are installed on the system. - * AudioSystem includes a number of - * methods for converting audio data between different formats, and for - * translating between audio files and streams. It also provides a method - * for obtaining a {@link Line} directly from the - * AudioSystem without dealing explicitly + * The {@code AudioSystem} class acts as the entry point to the sampled-audio + * system resources. This class lets you query and access the mixers that are + * installed on the system. {@code AudioSystem} includes a number of methods for + * converting audio data between different formats, and for translating between + * audio files and streams. It also provides a method for obtaining a + * {@link Line} directly from the {@code AudioSystem} without dealing explicitly * with mixers. - * - *

    Properties can be used to specify the default mixer - * for specific line types. - * Both system properties and a properties file are considered. - * The sound.properties properties file is read from - * an implementation-specific location (typically it is the lib - * directory in the Java installation directory). - * If a property exists both as a system property and in the - * properties file, the system property takes precedence. If none is - * specified, a suitable default is chosen among the available devices. - * The syntax of the properties file is specified in - * {@link java.util.Properties#load(InputStream) Properties.load}. The - * following table lists the available property keys and which methods - * consider them: + *

    + * Properties can be used to specify the default mixer for specific line types. + * Both system properties and a properties file are considered. The + * {@code sound.properties} properties file is read from an + * implementation-specific location (typically it is the {@code lib} directory + * in the Java installation directory). If a property exists both as a system + * property and in the properties file, the system property takes precedence. + * If none is specified, a suitable default is chosen among the available + * devices. The syntax of the properties file is specified in + * {@link java.util.Properties#load(InputStream) Properties.load}. The following + * table lists the available property keys and which methods consider them: * * * @@ -82,84 +77,68 @@ import com.sun.media.sound.JDK13Services; * * * - * + * * * * * - * + * * * * * - * + * * * * * - * + * * * * *
    Audio System Property Keys
    Affected Method(s)
    javax.sound.sampled.Clip{@code javax.sound.sampled.Clip}{@link Clip}{@link #getLine}, {@link #getClip}
    javax.sound.sampled.Port{@code javax.sound.sampled.Port}{@link Port}{@link #getLine}
    javax.sound.sampled.SourceDataLine{@code javax.sound.sampled.SourceDataLine}{@link SourceDataLine}{@link #getLine}, {@link #getSourceDataLine}
    javax.sound.sampled.TargetDataLine{@code javax.sound.sampled.TargetDataLine}{@link TargetDataLine}{@link #getLine}, {@link #getTargetDataLine}
    * - * The property value consists of the provider class name - * and the mixer name, separated by the hash mark ("#"). - * The provider class name is the fully-qualified - * name of a concrete {@link javax.sound.sampled.spi.MixerProvider - * mixer provider} class. The mixer name is matched against - * the String returned by the getName - * method of Mixer.Info. - * Either the class name, or the mixer name may be omitted. - * If only the class name is specified, the trailing hash mark - * is optional. - * - *

    If the provider class is specified, and it can be - * successfully retrieved from the installed providers, the list of - * Mixer.Info objects is retrieved - * from the provider. Otherwise, or when these mixers - * do not provide a subsequent match, the list is retrieved - * from {@link #getMixerInfo} to contain - * all available Mixer.Info objects. - * - *

    If a mixer name is specified, the resulting list of - * Mixer.Info objects is searched: - * the first one with a matching name, and whose - * Mixer provides the + * The property value consists of the provider class name and the mixer name, + * separated by the hash mark ("#"). The provider class name is the + * fully-qualified name of a concrete + * {@link javax.sound.sampled.spi.MixerProvider mixer provider} class. The mixer + * name is matched against the {@code String} returned by the {@code getName} + * method of {@code Mixer.Info}. Either the class name, or the mixer name may be + * omitted. If only the class name is specified, the trailing hash mark is + * optional. + *

    + * If the provider class is specified, and it can be successfully retrieved from + * the installed providers, the list of {@code Mixer.Info} objects is retrieved + * from the provider. Otherwise, or when these mixers do not provide a + * subsequent match, the list is retrieved from {@link #getMixerInfo} to contain + * all available {@code Mixer.Info} objects. + *

    + * If a mixer name is specified, the resulting list of {@code Mixer.Info} + * objects is searched: the first one with a matching name, and whose + * {@code Mixer} provides the respective line interface, will be returned. If no + * matching {@code Mixer.Info} object is found, or the mixer name is not + * specified, the first mixer from the resulting list, which provides the * respective line interface, will be returned. - * If no matching Mixer.Info object - * is found, or the mixer name is not specified, - * the first mixer from the resulting - * list, which provides the respective line - * interface, will be returned. * - * For example, the property javax.sound.sampled.Clip - * with a value - * "com.sun.media.sound.MixerProvider#SunClip" - * will have the following consequences when - * getLine is called requesting a Clip - * instance: - * if the class com.sun.media.sound.MixerProvider exists - * in the list of installed mixer providers, - * the first Clip from the first mixer with name - * "SunClip" will be returned. If it cannot - * be found, the first Clip from the first mixer - * of the specified provider will be returned, regardless of name. - * If there is none, the first Clip from the first - * Mixer with name - * "SunClip" in the list of all mixers - * (as returned by getMixerInfo) will be returned, - * or, if not found, the first Clip of the first - * Mixerthat can be found in the list of all - * mixers is returned. - * If that fails, too, an IllegalArgumentException - * is thrown. + * For example, the property {@code javax.sound.sampled.Clip} with a value + * {@code "com.sun.media.sound.MixerProvider#SunClip"} + * will have the following consequences when {@code getLine} is called + * requesting a {@code Clip} instance: if the class + * {@code com.sun.media.sound.MixerProvider} exists in the list of installed + * mixer providers, the first {@code Clip} from the first mixer with name + * {@code "SunClip"} will be returned. If it cannot be found, the + * first {@code Clip} from the first mixer of the specified provider will be + * returned, regardless of name. If there is none, the first {@code Clip} from + * the first {@code Mixer} with name {@code "SunClip"} in the list of + * all mixers (as returned by {@code getMixerInfo}) will be returned, or, if not + * found, the first {@code Clip} of the first {@code Mixer} that can be found in + * the list of all mixers is returned. If that fails, too, an + * {@code IllegalArgumentException} is thrown. * * @author Kara Kytle * @author Florian Bomers * @author Matthias Pfisterer * @author Kevin P. Smith - * * @see AudioFormat * @see AudioInputStream * @see Mixer @@ -170,13 +149,12 @@ import com.sun.media.sound.JDK13Services; public class AudioSystem { /** - * An integer that stands for an unknown numeric value. - * This value is appropriate only for signed quantities that do not - * normally take negative values. Examples include file sizes, frame - * sizes, buffer sizes, and sample rates. - * A number of Java Sound constructors accept - * a value of NOT_SPECIFIED for such parameters. Other - * methods may also accept or return this value, as documented. + * An integer that stands for an unknown numeric value. This value is + * appropriate only for signed quantities that do not normally take negative + * values. Examples include file sizes, frame sizes, buffer sizes, and + * sample rates. A number of Java Sound constructors accept a value of + * {@code NOT_SPECIFIED} for such parameters. Other methods may also accept + * or return this value, as documented. */ public static final int NOT_SPECIFIED = -1; @@ -186,42 +164,43 @@ public class AudioSystem { private AudioSystem() { } - /** - * Obtains an array of mixer info objects that represents - * the set of audio mixers that are currently installed on the system. - * @return an array of info objects for the currently installed mixers. If no mixers - * are available on the system, an array of length 0 is returned. + * Obtains an array of mixer info objects that represents the set of audio + * mixers that are currently installed on the system. + * + * @return an array of info objects for the currently installed mixers. If + * no mixers are available on the system, an array of length 0 is + * returned. * @see #getMixer */ public static Mixer.Info[] getMixerInfo() { - List infos = getMixerInfoList(); - Mixer.Info[] allInfos = (Mixer.Info[]) infos.toArray(new Mixer.Info[infos.size()]); + List infos = getMixerInfoList(); + Mixer.Info[] allInfos = infos.toArray(new Mixer.Info[infos.size()]); return allInfos; } - /** * Obtains the requested audio mixer. - * @param info a Mixer.Info object representing the desired - * mixer, or null for the system default mixer + * + * @param info a {@code Mixer.Info} object representing the desired mixer, + * or {@code null} for the system default mixer * @return the requested mixer - * @throws SecurityException if the requested mixer - * is unavailable because of security restrictions - * @throws IllegalArgumentException if the info object does not represent - * a mixer installed on the system + * @throws SecurityException if the requested mixer is unavailable because + * of security restrictions + * @throws IllegalArgumentException if the info object does not represent a + * mixer installed on the system * @see #getMixerInfo */ public static Mixer getMixer(Mixer.Info info) { Mixer mixer = null; - List providers = getMixerProviders(); + List providers = getMixerProviders(); for(int i = 0; i < providers.size(); i++ ) { try { - return ((MixerProvider)providers.get(i)).getMixer(info); + return providers.get(i).getMixer(info); } catch (IllegalArgumentException e) { } catch (NullPointerException e) { @@ -238,7 +217,7 @@ public class AudioSystem { if (info == null) { for(int i = 0; i < providers.size(); i++ ) { try { - MixerProvider provider = (MixerProvider) providers.get(i); + MixerProvider provider = providers.get(i); Mixer.Info[] infos = provider.getMixerInfo(); // start from 0 to last device (do not reverse this order) for (int ii = 0; ii < infos.length; ii++) { @@ -259,22 +238,22 @@ public class AudioSystem { + (info!=null?info.toString():"null")); } - //$$fb 2002-11-26: fix for 4757930: DOC: AudioSystem.getTarget/SourceLineInfo() is ambiguous + /** - * Obtains information about all source lines of a particular type that are supported - * by the installed mixers. - * @param info a Line.Info object that specifies the kind of - * lines about which information is requested - * @return an array of Line.Info objects describing source lines matching - * the type requested. If no matching source lines are supported, an array of length 0 - * is returned. + * Obtains information about all source lines of a particular type that are + * supported by the installed mixers. * + * @param info a {@code Line.Info} object that specifies the kind of lines + * about which information is requested + * @return an array of {@code Line.Info} objects describing source lines + * matching the type requested. If no matching source lines are + * supported, an array of length 0 is returned. * @see Mixer#getSourceLineInfo(Line.Info) */ public static Line.Info[] getSourceLineInfo(Line.Info info) { - Vector vector = new Vector(); + Vector vector = new Vector<>(); Line.Info[] currentInfoArray; Mixer mixer; @@ -294,27 +273,26 @@ public class AudioSystem { Line.Info[] returnedArray = new Line.Info[vector.size()]; for (int i = 0; i < returnedArray.length; i++) { - returnedArray[i] = (Line.Info)vector.get(i); + returnedArray[i] = vector.get(i); } return returnedArray; } - /** - * Obtains information about all target lines of a particular type that are supported - * by the installed mixers. - * @param info a Line.Info object that specifies the kind of - * lines about which information is requested - * @return an array of Line.Info objects describing target lines matching - * the type requested. If no matching target lines are supported, an array of length 0 - * is returned. + * Obtains information about all target lines of a particular type that are + * supported by the installed mixers. * + * @param info a {@code Line.Info} object that specifies the kind of lines + * about which information is requested + * @return an array of {@code Line.Info} objects describing target lines + * matching the type requested. If no matching target lines are + * supported, an array of length 0 is returned. * @see Mixer#getTargetLineInfo(Line.Info) */ public static Line.Info[] getTargetLineInfo(Line.Info info) { - Vector vector = new Vector(); + Vector vector = new Vector<>(); Line.Info[] currentInfoArray; Mixer mixer; @@ -334,21 +312,21 @@ public class AudioSystem { Line.Info[] returnedArray = new Line.Info[vector.size()]; for (int i = 0; i < returnedArray.length; i++) { - returnedArray[i] = (Line.Info)vector.get(i); + returnedArray[i] = vector.get(i); } return returnedArray; } - /** - * Indicates whether the system supports any lines that match - * the specified Line.Info object. A line is supported if - * any installed mixer supports it. - * @param info a Line.Info object describing the line for which support is queried - * @return true if at least one matching line is - * supported, otherwise false + * Indicates whether the system supports any lines that match the specified + * {@code Line.Info} object. A line is supported if any installed mixer + * supports it. * + * @param info a {@code Line.Info} object describing the line for which + * support is queried + * @return {@code true} if at least one matching line is supported, + * otherwise {@code false} * @see Mixer#isLineSupported(Line.Info) */ public static boolean isLineSupported(Line.Info info) { @@ -371,44 +349,40 @@ public class AudioSystem { /** * Obtains a line that matches the description in the specified - * Line.Info object. + * {@code Line.Info} object. + *

    + * If a {@code DataLine} is requested, and {@code info} is an instance of + * {@code DataLine.Info} specifying at least one fully qualified audio + * format, the last one will be used as the default format of the returned + * {@code DataLine}. + *

    + * If system properties + * {@code javax.sound.sampled.Clip}, + * {@code javax.sound.sampled.Port}, + * {@code javax.sound.sampled.SourceDataLine} and + * {@code javax.sound.sampled.TargetDataLine} are defined or they are + * defined in the file "sound.properties", they are used to retrieve default + * lines. For details, refer to the {@link AudioSystem class description}. * - *

    If a DataLine is requested, and info - * is an instance of DataLine.Info specifying at least - * one fully qualified audio format, the last one - * will be used as the default format of the returned - * DataLine. + * If the respective property is not set, or the mixer requested in the + * property is not installed or does not provide the requested line, all + * installed mixers are queried for the requested line type. A Line will be + * returned from the first mixer providing the requested line type. * - *

    If system properties - * javax.sound.sampled.Clip, - * javax.sound.sampled.Port, - * javax.sound.sampled.SourceDataLine and - * javax.sound.sampled.TargetDataLine are defined - * or they are defined in the file "sound.properties", - * they are used to retrieve default lines. - * For details, refer to the {@link AudioSystem class description}. - * - * If the respective property is not set, or the mixer - * requested in the property is not installed or does not provide the - * requested line, all installed mixers are queried for the - * requested line type. A Line will be returned from the first mixer - * providing the requested line type. - * - * @param info a Line.Info object describing the desired kind of line + * @param info a {@code Line.Info} object describing the desired kind of + * line * @return a line of the requested kind - * - * @throws LineUnavailableException if a matching line - * is not available due to resource restrictions - * @throws SecurityException if a matching line - * is not available due to security restrictions - * @throws IllegalArgumentException if the system does not - * support at least one line matching the specified - * Line.Info object - * through any installed mixer + * @throws LineUnavailableException if a matching line is not available due + * to resource restrictions + * @throws SecurityException if a matching line is not available due to + * security restrictions + * @throws IllegalArgumentException if the system does not support at least + * one line matching the specified {@code Line.Info} object through + * any installed mixer */ public static Line getLine(Line.Info info) throws LineUnavailableException { LineUnavailableException lue = null; - List providers = getMixerProviders(); + List providers = getMixerProviders(); // 1: try from default mixer for this line class @@ -427,7 +401,7 @@ public class AudioSystem { // 2: if that doesn't work, try to find any mixing mixer for(int i = 0; i < providers.size(); i++) { - MixerProvider provider = (MixerProvider) providers.get(i); + MixerProvider provider = providers.get(i); Mixer.Info[] infos = provider.getMixerInfo(); for (int j = 0; j < infos.length; j++) { @@ -449,7 +423,7 @@ public class AudioSystem { // 3: if that didn't work, try to find any non-mixing mixer for(int i = 0; i < providers.size(); i++) { - MixerProvider provider = (MixerProvider) providers.get(i); + MixerProvider provider = providers.get(i); Mixer.Info[] infos = provider.getMixerInfo(); for (int j = 0; j < infos.length; j++) { try { @@ -479,37 +453,30 @@ public class AudioSystem { info.toString() + " is supported."); } - /** - * Obtains a clip that can be used for playing back - * an audio file or an audio stream. The returned clip - * will be provided by the default system mixer, or, - * if not possible, by any other mixer installed in the - * system that supports a Clip - * object. - * - *

    The returned clip must be opened with the - * open(AudioFormat) or - * open(AudioInputStream) method. - * - *

    This is a high-level method that uses getMixer - * and getLine internally. - * - *

    If the system property - * javax.sound.sampled.Clip - * is defined or it is defined in the file "sound.properties", - * it is used to retrieve the default clip. - * For details, refer to the {@link AudioSystem class description}. + * Obtains a clip that can be used for playing back an audio file or an + * audio stream. The returned clip will be provided by the default system + * mixer, or, if not possible, by any other mixer installed in the system + * that supports a {@code Clip} object. + *

    + * The returned clip must be opened with the {@code open(AudioFormat)} or + * {@code open(AudioInputStream)} method. + *

    + * This is a high-level method that uses {@code getMixer} and + * {@code getLine} internally. + *

    + * If the system property {@code javax.sound.sampled.Clip} is defined or it + * is defined in the file "sound.properties", it is used to retrieve the + * default clip. For details, refer to the + * {@link AudioSystem class description}. * * @return the desired clip object - * - * @throws LineUnavailableException if a clip object - * is not available due to resource restrictions - * @throws SecurityException if a clip object - * is not available due to security restrictions - * @throws IllegalArgumentException if the system does not - * support at least one clip instance through any installed mixer - * + * @throws LineUnavailableException if a clip object is not available due to + * resource restrictions + * @throws SecurityException if a clip object is not available due to + * security restrictions + * @throws IllegalArgumentException if the system does not support at least + * one clip instance through any installed mixer * @see #getClip(Mixer.Info) * @since 1.5 */ @@ -522,29 +489,26 @@ public class AudioSystem { return (Clip) AudioSystem.getLine(info); } - /** - * Obtains a clip from the specified mixer that can be - * used for playing back an audio file or an audio stream. + * Obtains a clip from the specified mixer that can be used for playing back + * an audio file or an audio stream. + *

    + * The returned clip must be opened with the {@code open(AudioFormat)} or + * {@code open(AudioInputStream)} method. + *

    + * This is a high-level method that uses {@code getMixer} and + * {@code getLine} internally. * - *

    The returned clip must be opened with the - * open(AudioFormat) or - * open(AudioInputStream) method. - * - *

    This is a high-level method that uses getMixer - * and getLine internally. - * - * @param mixerInfo a Mixer.Info object representing the - * desired mixer, or null for the system default mixer + * @param mixerInfo a {@code Mixer.Info} object representing the desired + * mixer, or {@code null} for the system default mixer * @return a clip object from the specified mixer * - * @throws LineUnavailableException if a clip - * is not available from this mixer due to resource restrictions - * @throws SecurityException if a clip - * is not available from this mixer due to security restrictions - * @throws IllegalArgumentException if the system does not - * support at least one clip through the specified mixer - * + * @throws LineUnavailableException if a clip is not available from this + * mixer due to resource restrictions + * @throws SecurityException if a clip is not available from this mixer due + * to security restrictions + * @throws IllegalArgumentException if the system does not support at least + * one clip through the specified mixer * @see #getClip() * @since 1.5 */ @@ -558,45 +522,38 @@ public class AudioSystem { return (Clip) mixer.getLine(info); } - /** - * Obtains a source data line that can be used for playing back - * audio data in the format specified by the - * AudioFormat object. The returned line - * will be provided by the default system mixer, or, - * if not possible, by any other mixer installed in the - * system that supports a matching - * SourceDataLine object. - * - *

    The returned line should be opened with the - * open(AudioFormat) or - * open(AudioFormat, int) method. - * - *

    This is a high-level method that uses getMixer - * and getLine internally. - * - *

    The returned SourceDataLine's default - * audio format will be initialized with format. - * - *

    If the system property - * javax.sound.sampled.SourceDataLine - * is defined or it is defined in the file "sound.properties", - * it is used to retrieve the default source data line. - * For details, refer to the {@link AudioSystem class description}. - * - * @param format an AudioFormat object specifying - * the supported audio format of the returned line, - * or null for any audio format - * @return the desired SourceDataLine object - * - * @throws LineUnavailableException if a matching source data line - * is not available due to resource restrictions - * @throws SecurityException if a matching source data line - * is not available due to security restrictions - * @throws IllegalArgumentException if the system does not - * support at least one source data line supporting the - * specified audio format through any installed mixer + * Obtains a source data line that can be used for playing back audio data + * in the format specified by the {@code AudioFormat} object. The returned + * line will be provided by the default system mixer, or, if not possible, + * by any other mixer installed in the system that supports a matching + * {@code SourceDataLine} object. + *

    + * The returned line should be opened with the {@code open(AudioFormat)} or + * {@code open(AudioFormat, int)} method. + *

    + * This is a high-level method that uses {@code getMixer} and + * {@code getLine} internally. + *

    + * The returned {@code SourceDataLine}'s default audio format will be + * initialized with {@code format}. + *

    + * If the system property {@code javax.sound.sampled.SourceDataLine} is + * defined or it is defined in the file "sound.properties", it is used to + * retrieve the default source data line. For details, refer to the + * {@link AudioSystem class description}. * + * @param format an {@code AudioFormat} object specifying the supported + * audio format of the returned line, or {@code null} for any audio + * format + * @return the desired {@code SourceDataLine} object + * @throws LineUnavailableException if a matching source data line is not + * available due to resource restrictions + * @throws SecurityException if a matching source data line is not available + * due to security restrictions + * @throws IllegalArgumentException if the system does not support at least + * one source data line supporting the specified audio format + * through any installed mixer * @see #getSourceDataLine(AudioFormat, Mixer.Info) * @since 1.5 */ @@ -606,41 +563,33 @@ public class AudioSystem { return (SourceDataLine) AudioSystem.getLine(info); } - /** - * Obtains a source data line that can be used for playing back - * audio data in the format specified by the - * AudioFormat object, provided by the mixer - * specified by the Mixer.Info object. - * - *

    The returned line should be opened with the - * open(AudioFormat) or - * open(AudioFormat, int) method. - * - *

    This is a high-level method that uses getMixer - * and getLine internally. - * - *

    The returned SourceDataLine's default - * audio format will be initialized with format. - * - * @param format an AudioFormat object specifying - * the supported audio format of the returned line, - * or null for any audio format - * @param mixerinfo a Mixer.Info object representing - * the desired mixer, or null for the system - * default mixer - * @return the desired SourceDataLine object - * - * @throws LineUnavailableException if a matching source data - * line is not available from the specified mixer due - * to resource restrictions - * @throws SecurityException if a matching source data line - * is not available from the specified mixer due to - * security restrictions - * @throws IllegalArgumentException if the specified mixer does - * not support at least one source data line supporting - * the specified audio format + * Obtains a source data line that can be used for playing back audio data + * in the format specified by the {@code AudioFormat} object, provided by + * the mixer specified by the {@code Mixer.Info} object. + *

    + * The returned line should be opened with the {@code open(AudioFormat)} or + * {@code open(AudioFormat, int)} method. + *

    + * This is a high-level method that uses {@code getMixer} and + * {@code getLine} internally. + *

    + * The returned {@code SourceDataLine}'s default audio format will be + * initialized with {@code format}. * + * @param format an {@code AudioFormat} object specifying the supported + * audio format of the returned line, or {@code null} for any audio + * format + * @param mixerinfo a {@code Mixer.Info} object representing the desired + * mixer, or {@code null} for the system default mixer + * @return the desired {@code SourceDataLine} object + * @throws LineUnavailableException if a matching source data line is not + * available from the specified mixer due to resource restrictions + * @throws SecurityException if a matching source data line is not available + * from the specified mixer due to security restrictions + * @throws IllegalArgumentException if the specified mixer does not support + * at least one source data line supporting the specified audio + * format * @see #getSourceDataLine(AudioFormat) * @since 1.5 */ @@ -650,47 +599,40 @@ public class AudioSystem { DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); Mixer mixer = AudioSystem.getMixer(mixerinfo); return (SourceDataLine) mixer.getLine(info); - } - + } /** - * Obtains a target data line that can be used for recording - * audio data in the format specified by the - * AudioFormat object. The returned line - * will be provided by the default system mixer, or, - * if not possible, by any other mixer installed in the - * system that supports a matching - * TargetDataLine object. - * - *

    The returned line should be opened with the - * open(AudioFormat) or - * open(AudioFormat, int) method. - * - *

    This is a high-level method that uses getMixer - * and getLine internally. - * - *

    The returned TargetDataLine's default - * audio format will be initialized with format. - * - *

    If the system property - * {@code javax.sound.sampled.TargetDataLine} - * is defined or it is defined in the file "sound.properties", - * it is used to retrieve the default target data line. - * For details, refer to the {@link AudioSystem class description}. - * - * @param format an AudioFormat object specifying - * the supported audio format of the returned line, - * or null for any audio format - * @return the desired TargetDataLine object - * - * @throws LineUnavailableException if a matching target data line - * is not available due to resource restrictions - * @throws SecurityException if a matching target data line - * is not available due to security restrictions - * @throws IllegalArgumentException if the system does not - * support at least one target data line supporting the - * specified audio format through any installed mixer + * Obtains a target data line that can be used for recording audio data in + * the format specified by the {@code AudioFormat} object. The returned line + * will be provided by the default system mixer, or, if not possible, by any + * other mixer installed in the system that supports a matching + * {@code TargetDataLine} object. + *

    + * The returned line should be opened with the {@code open(AudioFormat)} or + * {@code open(AudioFormat, int)} method. + *

    + * This is a high-level method that uses {@code getMixer} and + * {@code getLine} internally. + *

    + * The returned {@code TargetDataLine}'s default audio format will be + * initialized with {@code format}. + *

    + * If the system property {@code javax.sound.sampled.TargetDataLine} is + * defined or it is defined in the file "sound.properties", it is used to + * retrieve the default target data line. For details, refer to the + * {@link AudioSystem class description}. * + * @param format an {@code AudioFormat} object specifying the supported + * audio format of the returned line, or {@code null} for any audio + * format + * @return the desired {@code TargetDataLine} object + * @throws LineUnavailableException if a matching target data line is not + * available due to resource restrictions + * @throws SecurityException if a matching target data line is not available + * due to security restrictions + * @throws IllegalArgumentException if the system does not support at least + * one target data line supporting the specified audio format + * through any installed mixer * @see #getTargetDataLine(AudioFormat, Mixer.Info) * @see AudioPermission * @since 1.5 @@ -702,41 +644,33 @@ public class AudioSystem { return (TargetDataLine) AudioSystem.getLine(info); } - - /** - * Obtains a target data line that can be used for recording - * audio data in the format specified by the - * AudioFormat object, provided by the mixer - * specified by the Mixer.Info object. - * - *

    The returned line should be opened with the - * open(AudioFormat) or - * open(AudioFormat, int) method. - * - *

    This is a high-level method that uses getMixer - * and getLine internally. - * - *

    The returned TargetDataLine's default - * audio format will be initialized with format. - * - * @param format an AudioFormat object specifying - * the supported audio format of the returned line, - * or null for any audio format - * @param mixerinfo a Mixer.Info object representing the - * desired mixer, or null for the system default mixer - * @return the desired TargetDataLine object - * - * @throws LineUnavailableException if a matching target data - * line is not available from the specified mixer due - * to resource restrictions - * @throws SecurityException if a matching target data line - * is not available from the specified mixer due to - * security restrictions - * @throws IllegalArgumentException if the specified mixer does - * not support at least one target data line supporting - * the specified audio format + * Obtains a target data line that can be used for recording audio data in + * the format specified by the {@code AudioFormat} object, provided by the + * mixer specified by the {@code Mixer.Info} object. + *

    + * The returned line should be opened with the {@code open(AudioFormat)} or + * {@code open(AudioFormat, int)} method. + *

    + * This is a high-level method that uses {@code getMixer} and + * {@code getLine} internally. + *

    + * The returned {@code TargetDataLine}'s default audio format will be + * initialized with {@code format}. * + * @param format an {@code AudioFormat} object specifying the supported + * audio format of the returned line, or {@code null} for any audio + * format + * @param mixerinfo a {@code Mixer.Info} object representing the desired + * mixer, or {@code null} for the system default mixer + * @return the desired {@code TargetDataLine} object + * @throws LineUnavailableException if a matching target data line is not + * available from the specified mixer due to resource restrictions + * @throws SecurityException if a matching target data line is not available + * from the specified mixer due to security restrictions + * @throws IllegalArgumentException if the specified mixer does not support + * at least one target data line supporting the specified audio + * format * @see #getTargetDataLine(AudioFormat) * @see AudioPermission * @since 1.5 @@ -750,28 +684,30 @@ public class AudioSystem { return (TargetDataLine) mixer.getLine(info); } - // $$fb 2002-04-12: fix for 4662082: behavior of AudioSystem.getTargetEncodings() methods doesn't match the spec + /** - * Obtains the encodings that the system can obtain from an - * audio input stream with the specified encoding using the set - * of installed format converters. - * @param sourceEncoding the encoding for which conversion support - * is queried - * @return array of encodings. If sourceEncodingis not supported, - * an array of length 0 is returned. Otherwise, the array will have a length - * of at least 1, representing sourceEncoding (no conversion). + * Obtains the encodings that the system can obtain from an audio input + * stream with the specified encoding using the set of installed format + * converters. + * + * @param sourceEncoding the encoding for which conversion support is + * queried + * @return array of encodings. If {@code sourceEncoding}is not supported, an + * array of length 0 is returned. Otherwise, the array will have a + * length of at least 1, representing {@code sourceEncoding} + * (no conversion). */ public static AudioFormat.Encoding[] getTargetEncodings(AudioFormat.Encoding sourceEncoding) { - List codecs = getFormatConversionProviders(); - Vector encodings = new Vector(); + List codecs = getFormatConversionProviders(); + Vector encodings = new Vector<>(); AudioFormat.Encoding encs[] = null; // gather from all the codecs for(int i=0; isourceFormatis not supported, - * an array of length 0 is returned. Otherwise, the array will have a length - * of at least 1, representing the encoding of sourceFormat (no conversion). + * Obtains the encodings that the system can obtain from an audio input + * stream with the specified format using the set of installed format + * converters. + * + * @param sourceFormat the audio format for which conversion is queried + * @return array of encodings. If {@code sourceFormat}is not supported, an + * array of length 0 is returned. Otherwise, the array will have a + * length of at least 1, representing the encoding of + * {@code sourceFormat} (no conversion). */ public static AudioFormat.Encoding[] getTargetEncodings(AudioFormat sourceFormat) { - List codecs = getFormatConversionProviders(); - Vector encodings = new Vector(); + List codecs = getFormatConversionProviders(); + Vector encodings = new Vector<>(); int size = 0; int index = 0; @@ -809,7 +745,7 @@ public class AudioSystem { // gather from all the codecs for(int i=0; itrue if the conversion is supported, - * otherwise false + * Indicates whether an audio input stream of the specified encoding can be + * obtained from an audio input stream that has the specified format. + * + * @param targetEncoding the desired encoding after conversion + * @param sourceFormat the audio format before conversion + * @return {@code true} if the conversion is supported, otherwise + * {@code false} */ public static boolean isConversionSupported(AudioFormat.Encoding targetEncoding, AudioFormat sourceFormat) { - List codecs = getFormatConversionProviders(); + List codecs = getFormatConversionProviders(); for(int i=0; i codecs = getFormatConversionProviders(); for(int i = 0; i < codecs.size(); i++) { - FormatConversionProvider codec = (FormatConversionProvider) codecs.get(i); + FormatConversionProvider codec = codecs.get(i); if( codec.isConversionSupported( targetEncoding, sourceStream.getFormat() ) ) { return codec.getAudioInputStream( targetEncoding, sourceStream ); } @@ -878,20 +813,20 @@ public class AudioSystem { throw new IllegalArgumentException("Unsupported conversion: " + targetEncoding + " from " + sourceStream.getFormat()); } - /** - * Obtains the formats that have a particular encoding and that the system can - * obtain from a stream of the specified format using the set of + * Obtains the formats that have a particular encoding and that the system + * can obtain from a stream of the specified format using the set of * installed format converters. - * @param targetEncoding the desired encoding after conversion - * @param sourceFormat the audio format before conversion - * @return array of formats. If no formats of the specified - * encoding are supported, an array of length 0 is returned. + * + * @param targetEncoding the desired encoding after conversion + * @param sourceFormat the audio format before conversion + * @return array of formats. If no formats of the specified encoding are + * supported, an array of length 0 is returned. */ public static AudioFormat[] getTargetFormats(AudioFormat.Encoding targetEncoding, AudioFormat sourceFormat) { - List codecs = getFormatConversionProviders(); - Vector formats = new Vector(); + List codecs = getFormatConversionProviders(); + Vector formats = new Vector<>(); int size = 0; int index = 0; @@ -900,7 +835,7 @@ public class AudioSystem { // gather from all the codecs for(int i=0; itrue if the conversion is supported, - * otherwise false + * Indicates whether an audio input stream of a specified format can be + * obtained from an audio input stream of another specified format. + * + * @param targetFormat the desired audio format after conversion + * @param sourceFormat the audio format before conversion + * @return {@code true} if the conversion is supported, otherwise + * {@code false} */ - public static boolean isConversionSupported(AudioFormat targetFormat, AudioFormat sourceFormat) { - List codecs = getFormatConversionProviders(); + List codecs = getFormatConversionProviders(); for(int i=0; i codecs = getFormatConversionProviders(); for(int i = 0; i < codecs.size(); i++) { - FormatConversionProvider codec = (FormatConversionProvider) codecs.get(i); + FormatConversionProvider codec = codecs.get(i); if(codec.isConversionSupported(targetFormat,sourceStream.getFormat()) ) { return codec.getAudioInputStream(targetFormat,sourceStream); } @@ -974,20 +908,22 @@ public class AudioSystem { throw new IllegalArgumentException("Unsupported conversion: " + targetFormat + " from " + sourceStream.getFormat()); } - /** - * Obtains the audio file format of the provided input stream. The stream must - * point to valid audio file data. The implementation of this method may require - * multiple parsers to examine the stream to determine whether they support it. - * These parsers must be able to mark the stream, read enough data to determine whether they - * support the stream, and, if not, reset the stream's read pointer to its original - * position. If the input stream does not support these operations, this method may fail - * with an IOException. - * @param stream the input stream from which file format information should be - * extracted - * @return an AudioFileFormat object describing the stream's audio file format - * @throws UnsupportedAudioFileException if the stream does not point to valid audio - * file data recognized by the system + * Obtains the audio file format of the provided input stream. The stream + * must point to valid audio file data. The implementation of this method + * may require multiple parsers to examine the stream to determine whether + * they support it. These parsers must be able to mark the stream, read + * enough data to determine whether they support the stream, and, if not, + * reset the stream's read pointer to its original position. If the input + * stream does not support these operations, this method may fail with an + * {@code IOException}. + * + * @param stream the input stream from which file format information should + * be extracted + * @return an {@code AudioFileFormat} object describing the stream's audio + * file format + * @throws UnsupportedAudioFileException if the stream does not point to + * valid audio file data recognized by the system * @throws IOException if an input/output exception occurs * @see InputStream#markSupported * @see InputStream#mark @@ -995,11 +931,11 @@ public class AudioSystem { public static AudioFileFormat getAudioFileFormat(InputStream stream) throws UnsupportedAudioFileException, IOException { - List providers = getAudioFileReaders(); + List providers = getAudioFileReaders(); AudioFileFormat format = null; for(int i = 0; i < providers.size(); i++ ) { - AudioFileReader reader = (AudioFileReader) providers.get(i); + AudioFileReader reader = providers.get(i); try { format = reader.getAudioFileFormat( stream ); // throws IOException break; @@ -1016,23 +952,25 @@ public class AudioSystem { } /** - * Obtains the audio file format of the specified URL. The URL must - * point to valid audio file data. - * @param url the URL from which file format information should be - * extracted - * @return an AudioFileFormat object describing the audio file format - * @throws UnsupportedAudioFileException if the URL does not point to valid audio - * file data recognized by the system + * Obtains the audio file format of the specified URL. The URL must point to + * valid audio file data. + * + * @param url the URL from which file format information should be + * extracted + * @return an {@code AudioFileFormat} object describing the audio file + * format + * @throws UnsupportedAudioFileException if the URL does not point to valid + * audio file data recognized by the system * @throws IOException if an input/output exception occurs */ public static AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { - List providers = getAudioFileReaders(); + List providers = getAudioFileReaders(); AudioFileFormat format = null; for(int i = 0; i < providers.size(); i++ ) { - AudioFileReader reader = (AudioFileReader) providers.get(i); + AudioFileReader reader = providers.get(i); try { format = reader.getAudioFileFormat( url ); // throws IOException break; @@ -1049,23 +987,25 @@ public class AudioSystem { } /** - * Obtains the audio file format of the specified File. The File must - * point to valid audio file data. - * @param file the File from which file format information should be - * extracted - * @return an AudioFileFormat object describing the audio file format - * @throws UnsupportedAudioFileException if the File does not point to valid audio - * file data recognized by the system + * Obtains the audio file format of the specified {@code File}. The + * {@code File} must point to valid audio file data. + * + * @param file the {@code File} from which file format information should + * be extracted + * @return an {@code AudioFileFormat} object describing the audio file + * format + * @throws UnsupportedAudioFileException if the {@code File} does not point + * to valid audio file data recognized by the system * @throws IOException if an I/O exception occurs */ public static AudioFileFormat getAudioFileFormat(File file) throws UnsupportedAudioFileException, IOException { - List providers = getAudioFileReaders(); + List providers = getAudioFileReaders(); AudioFileFormat format = null; for(int i = 0; i < providers.size(); i++ ) { - AudioFileReader reader = (AudioFileReader) providers.get(i); + AudioFileReader reader = providers.get(i); try { format = reader.getAudioFileFormat( file ); // throws IOException break; @@ -1081,22 +1021,22 @@ public class AudioSystem { } } - /** - * Obtains an audio input stream from the provided input stream. The stream must - * point to valid audio file data. The implementation of this method may - * require multiple parsers to - * examine the stream to determine whether they support it. These parsers must - * be able to mark the stream, read enough data to determine whether they - * support the stream, and, if not, reset the stream's read pointer to its original - * position. If the input stream does not support these operation, this method may fail - * with an IOException. - * @param stream the input stream from which the AudioInputStream should be - * constructed - * @return an AudioInputStream object based on the audio file data contained - * in the input stream. - * @throws UnsupportedAudioFileException if the stream does not point to valid audio - * file data recognized by the system + * Obtains an audio input stream from the provided input stream. The stream + * must point to valid audio file data. The implementation of this method + * may require multiple parsers to examine the stream to determine whether + * they support it. These parsers must be able to mark the stream, read + * enough data to determine whether they support the stream, and, if not, + * reset the stream's read pointer to its original position. If the input + * stream does not support these operation, this method may fail with an + * {@code IOException}. + * + * @param stream the input stream from which the {@code AudioInputStream} + * should be constructed + * @return an {@code AudioInputStream} object based on the audio file data + * contained in the input stream + * @throws UnsupportedAudioFileException if the stream does not point to + * valid audio file data recognized by the system * @throws IOException if an I/O exception occurs * @see InputStream#markSupported * @see InputStream#mark @@ -1104,11 +1044,11 @@ public class AudioSystem { public static AudioInputStream getAudioInputStream(InputStream stream) throws UnsupportedAudioFileException, IOException { - List providers = getAudioFileReaders(); + List providers = getAudioFileReaders(); AudioInputStream audioStream = null; for(int i = 0; i < providers.size(); i++ ) { - AudioFileReader reader = (AudioFileReader) providers.get(i); + AudioFileReader reader = providers.get(i); try { audioStream = reader.getAudioInputStream( stream ); // throws IOException break; @@ -1125,24 +1065,25 @@ public class AudioSystem { } /** - * Obtains an audio input stream from the URL provided. The URL must - * point to valid audio file data. - * @param url the URL for which the AudioInputStream should be - * constructed - * @return an AudioInputStream object based on the audio file data pointed - * to by the URL - * @throws UnsupportedAudioFileException if the URL does not point to valid audio - * file data recognized by the system + * Obtains an audio input stream from the URL provided. The URL must point + * to valid audio file data. + * + * @param url the URL for which the {@code AudioInputStream} should be + * constructed + * @return an {@code AudioInputStream} object based on the audio file data + * pointed to by the URL + * @throws UnsupportedAudioFileException if the URL does not point to valid + * audio file data recognized by the system * @throws IOException if an I/O exception occurs */ public static AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { - List providers = getAudioFileReaders(); + List providers = getAudioFileReaders(); AudioInputStream audioStream = null; for(int i = 0; i < providers.size(); i++ ) { - AudioFileReader reader = (AudioFileReader) providers.get(i); + AudioFileReader reader = providers.get(i); try { audioStream = reader.getAudioInputStream( url ); // throws IOException break; @@ -1159,24 +1100,25 @@ public class AudioSystem { } /** - * Obtains an audio input stream from the provided File. The File must - * point to valid audio file data. - * @param file the File for which the AudioInputStream should be - * constructed - * @return an AudioInputStream object based on the audio file data pointed - * to by the File - * @throws UnsupportedAudioFileException if the File does not point to valid audio - * file data recognized by the system + * Obtains an audio input stream from the provided {@code File}. The + * {@code File} must point to valid audio file data. + * + * @param file the {@code File} for which the {@code AudioInputStream} + * should be constructed + * @return an {@code AudioInputStream} object based on the audio file data + * pointed to by the {@code File} + * @throws UnsupportedAudioFileException if the {@code File} does not point + * to valid audio file data recognized by the system * @throws IOException if an I/O exception occurs */ public static AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException { - List providers = getAudioFileReaders(); + List providers = getAudioFileReaders(); AudioInputStream audioStream = null; for(int i = 0; i < providers.size(); i++ ) { - AudioFileReader reader = (AudioFileReader) providers.get(i); + AudioFileReader reader = providers.get(i); try { audioStream = reader.getAudioInputStream( file ); // throws IOException break; @@ -1192,42 +1134,43 @@ public class AudioSystem { } } - /** - * Obtains the file types for which file writing support is provided by the system. - * @return array of unique file types. If no file types are supported, - * an array of length 0 is returned. + * Obtains the file types for which file writing support is provided by the + * system. + * + * @return array of unique file types. If no file types are supported, an + * array of length 0 is returned. */ public static AudioFileFormat.Type[] getAudioFileTypes() { - List providers = getAudioFileWriters(); - Set returnTypesSet = new HashSet(); + List providers = getAudioFileWriters(); + Set returnTypesSet = new HashSet<>(); for(int i=0; i < providers.size(); i++) { - AudioFileWriter writer = (AudioFileWriter) providers.get(i); + AudioFileWriter writer = providers.get(i); AudioFileFormat.Type[] fileTypes = writer.getAudioFileTypes(); for(int j=0; j < fileTypes.length; j++) { returnTypesSet.add(fileTypes[j]); } } - AudioFileFormat.Type returnTypes[] = (AudioFileFormat.Type[]) + AudioFileFormat.Type returnTypes[] = returnTypesSet.toArray(new AudioFileFormat.Type[0]); return returnTypes; } - /** - * Indicates whether file writing support for the specified file type is provided - * by the system. - * @param fileType the file type for which write capabilities are queried - * @return true if the file type is supported, - * otherwise false + * Indicates whether file writing support for the specified file type is + * provided by the system. + * + * @param fileType the file type for which write capabilities are queried + * @return {@code true} if the file type is supported, otherwise + * {@code false} */ public static boolean isFileTypeSupported(AudioFileFormat.Type fileType) { - List providers = getAudioFileWriters(); + List providers = getAudioFileWriters(); for(int i=0; i < providers.size(); i++) { - AudioFileWriter writer = (AudioFileWriter) providers.get(i); + AudioFileWriter writer = providers.get(i); if (writer.isFileTypeSupported(fileType)) { return true; } @@ -1235,47 +1178,47 @@ public class AudioSystem { return false; } - /** - * Obtains the file types that the system can write from the - * audio input stream specified. - * @param stream the audio input stream for which audio file type support - * is queried - * @return array of file types. If no file types are supported, - * an array of length 0 is returned. + * Obtains the file types that the system can write from the audio input + * stream specified. + * + * @param stream the audio input stream for which audio file type + * support is queried + * @return array of file types. If no file types are supported, an array of + * length 0 is returned. */ public static AudioFileFormat.Type[] getAudioFileTypes(AudioInputStream stream) { - List providers = getAudioFileWriters(); - Set returnTypesSet = new HashSet(); + List providers = getAudioFileWriters(); + Set returnTypesSet = new HashSet<>(); for(int i=0; i < providers.size(); i++) { - AudioFileWriter writer = (AudioFileWriter) providers.get(i); + AudioFileWriter writer = providers.get(i); AudioFileFormat.Type[] fileTypes = writer.getAudioFileTypes(stream); for(int j=0; j < fileTypes.length; j++) { returnTypesSet.add(fileTypes[j]); } } - AudioFileFormat.Type returnTypes[] = (AudioFileFormat.Type[]) + AudioFileFormat.Type returnTypes[] = returnTypesSet.toArray(new AudioFileFormat.Type[0]); return returnTypes; } - /** * Indicates whether an audio file of the specified file type can be written * from the indicated audio input stream. - * @param fileType the file type for which write capabilities are queried - * @param stream the stream for which file-writing support is queried - * @return true if the file type is supported for this audio input stream, - * otherwise false + * + * @param fileType the file type for which write capabilities are queried + * @param stream the stream for which file-writing support is queried + * @return {@code true} if the file type is supported for this audio input + * stream, otherwise {@code false} */ public static boolean isFileTypeSupported(AudioFileFormat.Type fileType, AudioInputStream stream) { - List providers = getAudioFileWriters(); + List providers = getAudioFileWriters(); for(int i=0; i < providers.size(); i++) { - AudioFileWriter writer = (AudioFileWriter) providers.get(i); + AudioFileWriter writer = providers.get(i); if(writer.isFileTypeSupported(fileType, stream)) { return true; } @@ -1283,35 +1226,34 @@ public class AudioSystem { return false; } - /** - * Writes a stream of bytes representing an audio file of the specified file type - * to the output stream provided. Some file types require that - * the length be written into the file header; such files cannot be written from - * start to finish unless the length is known in advance. An attempt - * to write a file of such a type will fail with an IOException if the length in - * the audio file type is AudioSystem.NOT_SPECIFIED. + * Writes a stream of bytes representing an audio file of the specified file + * type to the output stream provided. Some file types require that the + * length be written into the file header; such files cannot be written from + * start to finish unless the length is known in advance. An attempt to + * write a file of such a type will fail with an IOException if the length + * in the audio file type is {@code AudioSystem.NOT_SPECIFIED}. * - * @param stream the audio input stream containing audio data to be - * written to the file - * @param fileType the kind of audio file to write - * @param out the stream to which the file data should be written + * @param stream the audio input stream containing audio data to be written + * to the file + * @param fileType the kind of audio file to write + * @param out the stream to which the file data should be written * @return the number of bytes written to the output stream * @throws IOException if an input/output exception occurs - * @throws IllegalArgumentException if the file type is not supported by - * the system + * @throws IllegalArgumentException if the file type is not supported by the + * system * @see #isFileTypeSupported - * @see #getAudioFileTypes + * @see #getAudioFileTypes */ public static int write(AudioInputStream stream, AudioFileFormat.Type fileType, OutputStream out) throws IOException { - List providers = getAudioFileWriters(); + List providers = getAudioFileWriters(); int bytesWritten = 0; boolean flag = false; for(int i=0; i < providers.size(); i++) { - AudioFileWriter writer = (AudioFileWriter) providers.get(i); + AudioFileWriter writer = providers.get(i); try { bytesWritten = writer.write( stream, fileType, out ); // throws IOException flag = true; @@ -1328,30 +1270,30 @@ public class AudioSystem { } } - /** - * Writes a stream of bytes representing an audio file of the specified file type - * to the external file provided. - * @param stream the audio input stream containing audio data to be - * written to the file - * @param fileType the kind of audio file to write - * @param out the external file to which the file data should be written + * Writes a stream of bytes representing an audio file of the specified file + * type to the external file provided. + * + * @param stream the audio input stream containing audio data to be written + * to the file + * @param fileType the kind of audio file to write + * @param out the external file to which the file data should be written * @return the number of bytes written to the file * @throws IOException if an I/O exception occurs - * @throws IllegalArgumentException if the file type is not supported by - * the system + * @throws IllegalArgumentException if the file type is not supported by the + * system * @see #isFileTypeSupported - * @see #getAudioFileTypes + * @see #getAudioFileTypes */ public static int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException { - List providers = getAudioFileWriters(); + List providers = getAudioFileWriters(); int bytesWritten = 0; boolean flag = false; for(int i=0; i < providers.size(); i++) { - AudioFileWriter writer = (AudioFileWriter) providers.get(i); + AudioFileWriter writer = providers.get(i); try { bytesWritten = writer.write( stream, fileType, out ); // throws IOException flag = true; @@ -1368,68 +1310,70 @@ public class AudioSystem { } } - // METHODS FOR INTERNAL IMPLEMENTATION USE /** * Obtains the set of MixerProviders on the system. */ - private static List getMixerProviders() { - return getProviders(MixerProvider.class); + @SuppressWarnings("unchecked") + private static List getMixerProviders() { + return (List) getProviders(MixerProvider.class); } - /** - * Obtains the set of format converters (codecs, transcoders, etc.) - * that are currently installed on the system. - * @return an array of - * {@link javax.sound.sampled.spi.FormatConversionProvider - * FormatConversionProvider} - * objects representing the available format converters. If no format - * converters readers are available on the system, an array of length 0 is - * returned. - */ - private static List getFormatConversionProviders() { - return getProviders(FormatConversionProvider.class); - } - - - /** - * Obtains the set of audio file readers that are currently installed on the system. - * @return a List of - * {@link javax.sound.sampled.spi.AudioFileReader - * AudioFileReader} - * objects representing the installed audio file readers. If no audio file - * readers are available on the system, an empty List is returned. - */ - private static List getAudioFileReaders() { - return getProviders(AudioFileReader.class); - } - - - /** - * Obtains the set of audio file writers that are currently installed on the system. - * @return a List of - * {@link javax.sound.samples.spi.AudioFileWriter AudioFileWriter} - * objects representing the available audio file writers. If no audio file - * writers are available on the system, an empty List is returned. - */ - private static List getAudioFileWriters() { - return getProviders(AudioFileWriter.class); - } - - - - /** Attempts to locate and return a default Mixer that provides lines - * of the specified type. + * Obtains the set of format converters (codecs, transcoders, etc.) that are + * currently installed on the system. * - * @param providers the installed mixer providers - * @param info The requested line type - * TargetDataLine.class, Clip.class or Port.class. - * @return a Mixer that matches the requirements, or null if no default mixer found + * @return an array of {@link javax.sound.sampled.spi.FormatConversionProvider + * FormatConversionProvider} objects representing the available + * format converters. If no format converters readers are available + * on the system, an array of length 0 is returned. */ - private static Mixer getDefaultMixer(List providers, Line.Info info) { - Class lineClass = info.getLineClass(); + @SuppressWarnings("unchecked") + private static List getFormatConversionProviders() { + return (List) getProviders(FormatConversionProvider.class); + } + + /** + * Obtains the set of audio file readers that are currently installed on the + * system. + * + * @return a List of {@link javax.sound.sampled.spi.AudioFileReader + * AudioFileReader} objects representing the installed audio file + * readers. If no audio file readers are available on the system, an + * empty List is returned. + */ + @SuppressWarnings("unchecked") + private static List getAudioFileReaders() { + return (List)getProviders(AudioFileReader.class); + } + + /** + * Obtains the set of audio file writers that are currently installed on the + * system. + * + * @return a List of {@link javax.sound.sampled.spi.AudioFileWriter + * AudioFileWriter} objects representing the available audio file + * writers. If no audio file writers are available on the system, an + * empty List is returned. + */ + @SuppressWarnings("unchecked") + private static List getAudioFileWriters() { + return (List)getProviders(AudioFileWriter.class); + } + + /** + * Attempts to locate and return a default Mixer that provides lines of the + * specified type. + * + * @param providers the installed mixer providers + * @param info The requested line type TargetDataLine.class, Clip.class or + * Port.class + * @return a Mixer that matches the requirements, or null if no default + * mixer found + */ + private static Mixer getDefaultMixer(List providers, Line.Info info) { + Class lineClass = info.getLineClass(); String providerClassName = JDK13Services.getDefaultProviderClassName(lineClass); String instanceName = JDK13Services.getDefaultInstanceName(lineClass); Mixer mixer; @@ -1469,21 +1413,18 @@ public class AudioSystem { return null; } - - - /** Return a MixerProvider of a given class from the list of - MixerProviders. - - This method never requires the returned Mixer to do mixing. - @param providerClassName The class name of the provider to be returned. - @param providers The list of MixerProviders that is searched. - @return A MixerProvider of the requested class, or null if none is - found. + /** + * Return a MixerProvider of a given class from the list of MixerProviders. + * This method never requires the returned Mixer to do mixing. + * + * @param providerClassName The class name of the provider to be returned + * @param providers The list of MixerProviders that is searched + * @return A MixerProvider of the requested class, or null if none is found */ private static MixerProvider getNamedProvider(String providerClassName, - List providers) { + List providers) { for(int i = 0; i < providers.size(); i++) { - MixerProvider provider = (MixerProvider) providers.get(i); + MixerProvider provider = providers.get(i); if (provider.getClass().getName().equals(providerClassName)) { return provider; } @@ -1491,15 +1432,14 @@ public class AudioSystem { return null; } - - /** Return a Mixer with a given name from a given MixerProvider. - This method never requires the returned Mixer to do mixing. - @param mixerName The name of the Mixer to be returned. - @param provider The MixerProvider to check for Mixers. - @param info The type of line the returned Mixer is required to - support. - - @return A Mixer matching the requirements, or null if none is found. + /** + * Return a Mixer with a given name from a given MixerProvider. This method + * never requires the returned Mixer to do mixing. + * + * @param mixerName The name of the Mixer to be returned + * @param provider The MixerProvider to check for Mixers + * @param info The type of line the returned Mixer is required to support + * @return A Mixer matching the requirements, or null if none is found */ private static Mixer getNamedMixer(String mixerName, MixerProvider provider, @@ -1516,20 +1456,20 @@ public class AudioSystem { return null; } - - /** From a List of MixerProviders, return a Mixer with a given name. - This method never requires the returned Mixer to do mixing. - @param mixerName The name of the Mixer to be returned. - @param providers The List of MixerProviders to check for Mixers. - @param info The type of line the returned Mixer is required to - support. - @return A Mixer matching the requirements, or null if none is found. + /** + * From a List of MixerProviders, return a Mixer with a given name. This + * method never requires the returned Mixer to do mixing. + * + * @param mixerName The name of the Mixer to be returned + * @param providers The List of MixerProviders to check for Mixers + * @param info The type of line the returned Mixer is required to support + * @return A Mixer matching the requirements, or null if none is found */ private static Mixer getNamedMixer(String mixerName, - List providers, + List providers, Line.Info info) { for(int i = 0; i < providers.size(); i++) { - MixerProvider provider = (MixerProvider) providers.get(i); + MixerProvider provider = providers.get(i); Mixer mixer = getNamedMixer(mixerName, provider, info); if (mixer != null) { return mixer; @@ -1538,16 +1478,14 @@ public class AudioSystem { return null; } - - /** From a given MixerProvider, return the first appropriate Mixer. - @param provider The MixerProvider to check for Mixers. - @param info The type of line the returned Mixer is required to - support. - @param isMixingRequired If true, only Mixers that support mixing are - returned for line types of SourceDataLine and Clip. - - @return A Mixer that is considered appropriate, or null - if none is found. + /** + * From a given MixerProvider, return the first appropriate Mixer. + * + * @param provider The MixerProvider to check for Mixers + * @param info The type of line the returned Mixer is required to support + * @param isMixingRequired If true, only Mixers that support mixing are + * returned for line types of SourceDataLine and Clip + * @return A Mixer that is considered appropriate, or null if none is found */ private static Mixer getFirstMixer(MixerProvider provider, Line.Info info, @@ -1562,15 +1500,14 @@ public class AudioSystem { return null; } - - /** Checks if a Mixer is appropriate. - A Mixer is considered appropriate if it support the given line type. - If isMixingRequired is true and the line type is an output one - (SourceDataLine, Clip), the mixer is appropriate if it supports - at least 2 (concurrent) lines of the given type. - - @return true if the mixer is considered appropriate according to the - rules given above, false otherwise. + /** + * Checks if a Mixer is appropriate. A Mixer is considered appropriate if it + * support the given line type. If isMixingRequired is true and the line + * type is an output one (SourceDataLine, Clip), the mixer is appropriate if + * it supports at least 2 (concurrent) lines of the given type. + * + * @return {@code true} if the mixer is considered appropriate according to + * the rules given above, {@code false} otherwise */ private static boolean isAppropriateMixer(Mixer mixer, Line.Info lineInfo, @@ -1578,7 +1515,7 @@ public class AudioSystem { if (! mixer.isLineSupported(lineInfo)) { return false; } - Class lineClass = lineInfo.getLineClass(); + Class lineClass = lineInfo.getLineClass(); if (isMixingRequired && (SourceDataLine.class.isAssignableFrom(lineClass) || Clip.class.isAssignableFrom(lineClass))) { @@ -1588,28 +1525,25 @@ public class AudioSystem { return true; } - - /** - * Like getMixerInfo, but return List + * Like getMixerInfo, but return List. */ - private static List getMixerInfoList() { - List providers = getMixerProviders(); + private static List getMixerInfoList() { + List providers = getMixerProviders(); return getMixerInfoList(providers); } - /** - * Like getMixerInfo, but return List + * Like getMixerInfo, but return List. */ - private static List getMixerInfoList(List providers) { - List infos = new ArrayList(); + private static List getMixerInfoList(List providers) { + List infos = new ArrayList<>(); Mixer.Info[] someInfos; // per-mixer Mixer.Info[] allInfos; // for all mixers for(int i = 0; i < providers.size(); i++ ) { - someInfos = ((MixerProvider)providers.get(i)).getMixerInfo(); + someInfos = providers.get(i).getMixerInfo(); for (int j = 0; j < someInfos.length; j++) { infos.add(someInfos[j]); @@ -1619,14 +1553,14 @@ public class AudioSystem { return infos; } - /** - * Obtains the set of services currently installed on the system - * using the SPI mechanism in 1.3. - * @return a List of instances of providers for the requested service. - * If no providers are available, a vector of length 0 will be returned. + * Obtains the set of services currently installed on the system using the + * SPI mechanism in 1.3. + * + * @return a List of instances of providers for the requested service. If no + * providers are available, a vector of length 0 will be returned. */ - private static List getProviders(Class providerClass) { + private static List getProviders(Class providerClass) { return JDK13Services.getProviders(providerClass); } } diff --git a/jdk/src/share/classes/javax/sound/sampled/BooleanControl.java b/jdk/src/share/classes/javax/sound/sampled/BooleanControl.java index e48e06c339c..4f81d7c6514 100644 --- a/jdk/src/share/classes/javax/sound/sampled/BooleanControl.java +++ b/jdk/src/share/classes/javax/sound/sampled/BooleanControl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,34 +26,29 @@ package javax.sound.sampled; /** - * A BooleanControl provides the ability to switch between - * two possible settings that affect a line's audio. The settings are boolean - * values (true and false). A graphical user interface - * might represent the control by a two-state button, an on/off switch, two - * mutually exclusive buttons, or a checkbox (among other possibilities). - * For example, depressing a button might activate a - * {@link BooleanControl.Type#MUTE MUTE} control to silence - * the line's audio. + * A {@code BooleanControl} provides the ability to switch between two possible + * settings that affect a line's audio. The settings are boolean values + * ({@code true} and {@code false}). A graphical user interface might represent + * the control by a two-state button, an on/off switch, two mutually exclusive + * buttons, or a checkbox (among other possibilities). For example, depressing a + * button might activate a {@link BooleanControl.Type#MUTE MUTE} control to + * silence the line's audio. *

    - * As with other {@link Control} subclasses, a method is - * provided that returns string labels for the values, suitable for - * display in the user interface. + * As with other {@code Control} subclasses, a method is provided that returns + * string labels for the values, suitable for display in the user interface. * * @author Kara Kytle * @since 1.3 */ public abstract class BooleanControl extends Control { - - // INSTANCE VARIABLES - /** - * The true state label, such as "true" or "on." + * The {@code true} state label, such as "true" or "on". */ private final String trueStateLabel; /** - * The false state label, such as "false" or "off." + * The {@code false} state label, such as "false" or "off". */ private final String falseStateLabel; @@ -62,19 +57,15 @@ public abstract class BooleanControl extends Control { */ private boolean value; - - // CONSTRUCTORS - - /** * Constructs a new boolean control object with the given parameters. * - * @param type the type of control represented this float control object - * @param initialValue the initial control value - * @param trueStateLabel the label for the state represented by true, - * such as "true" or "on." - * @param falseStateLabel the label for the state represented by false, - * such as "false" or "off." + * @param type the type of control represented this float control object + * @param initialValue the initial control value + * @param trueStateLabel the label for the state represented by + * {@code true}, such as "true" or "on" + * @param falseStateLabel the label for the state represented by + * {@code false}, such as "false" or "off" */ protected BooleanControl(Type type, boolean initialValue, String trueStateLabel, String falseStateLabel) { @@ -84,110 +75,88 @@ public abstract class BooleanControl extends Control { this.falseStateLabel = falseStateLabel; } - /** - * Constructs a new boolean control object with the given parameters. - * The labels for the true and false states - * default to "true" and "false." + * Constructs a new boolean control object with the given parameters. The + * labels for the {@code true} and {@code false} states default to "true" + * and "false". * - * @param type the type of control represented by this float control object - * @param initialValue the initial control value + * @param type the type of control represented by this float control object + * @param initialValue the initial control value */ protected BooleanControl(Type type, boolean initialValue) { this(type, initialValue, "true", "false"); } - - // METHODS - - /** - * Sets the current value for the control. The default - * implementation simply sets the value as indicated. - * Some controls require that their line be open before they can be affected - * by setting a value. - * @param value desired new value. + * Sets the current value for the control. The default implementation simply + * sets the value as indicated. Some controls require that their line be + * open before they can be affected by setting a value. + * + * @param value desired new value */ public void setValue(boolean value) { this.value = value; } - - /** * Obtains this control's current value. - * @return current value. + * + * @return current value */ public boolean getValue() { return value; } - /** * Obtains the label for the specified state. - * @param state the state whose label will be returned - * @return the label for the specified state, such as "true" or "on" - * for true, or "false" or "off" for false. + * + * @param state the state whose label will be returned + * @return the label for the specified state, such as "true" or "on" for + * {@code true}, or "false" or "off" for {@code false} */ public String getStateLabel(boolean state) { return ((state == true) ? trueStateLabel : falseStateLabel); } - - - // ABSTRACT METHOD IMPLEMENTATIONS: CONTROL - - /** - * Provides a string representation of the control + * Provides a string representation of the control. + * * @return a string description */ + @Override public String toString() { return new String(super.toString() + " with current value: " + getStateLabel(getValue())); } - - // INNER CLASSES - - /** - * An instance of the BooleanControl.Type class identifies one kind of - * boolean control. Static instances are provided for the - * common types. + * An instance of the {@code BooleanControl.Type} class identifies one kind + * of boolean control. Static instances are provided for the common types. * * @author Kara Kytle * @since 1.3 */ public static class Type extends Control.Type { - - // TYPE DEFINES - - /** - * Represents a control for the mute status of a line. - * Note that mute status does not affect gain. + * Represents a control for the mute status of a line. Note that mute + * status does not affect gain. */ public static final Type MUTE = new Type("Mute"); /** - * Represents a control for whether reverberation is applied - * to a line. Note that the status of this control not affect - * the reverberation settings for a line, but does affect whether - * these settings are used. + * Represents a control for whether reverberation is applied to a line. + * Note that the status of this control not affect the reverberation + * settings for a line, but does affect whether these settings are used. */ public static final Type APPLY_REVERB = new Type("Apply Reverb"); - - // CONSTRUCTOR - - /** * Constructs a new boolean control type. - * @param name the name of the new boolean control type + * + * @param name the name of the new boolean control type */ - protected Type(String name) { + protected Type(final String name) { super(name); } - } // class Type + } } diff --git a/jdk/src/share/classes/javax/sound/sampled/Clip.java b/jdk/src/share/classes/javax/sound/sampled/Clip.java index 03965f35528..5ed01df832c 100644 --- a/jdk/src/share/classes/javax/sound/sampled/Clip.java +++ b/jdk/src/share/classes/javax/sound/sampled/Clip.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,188 +25,184 @@ package javax.sound.sampled; -import java.io.InputStream; import java.io.IOException; /** - * The Clip interface represents a special kind of data line whose - * audio data can be loaded prior to playback, instead of being streamed in - * real time. + * The {@code Clip} interface represents a special kind of data line whose audio + * data can be loaded prior to playback, instead of being streamed in real time. *

    - * Because the data is pre-loaded and has a known length, you can set a clip - * to start playing at any position in its audio data. You can also create a - * loop, so that when the clip is played it will cycle repeatedly. Loops are - * specified with a starting and ending sample frame, along with the number of - * times that the loop should be played. + * Because the data is pre-loaded and has a known length, you can set a clip to + * start playing at any position in its audio data. You can also create a loop, + * so that when the clip is played it will cycle repeatedly. Loops are specified + * with a starting and ending sample frame, along with the number of times that + * the loop should be played. *

    - * Clips may be obtained from a {@link Mixer} that supports lines - * of this type. Data is loaded into a clip when it is opened. + * Clips may be obtained from a {@link Mixer} that supports lines of this type. + * Data is loaded into a clip when it is opened. *

    - * Playback of an audio clip may be started and stopped using the start - * and stop methods. These methods do not reset the media position; - * start causes playback to continue from the position where playback - * was last stopped. To restart playback from the beginning of the clip's audio - * data, simply follow the invocation of {@link DataLine#stop stop} - * with setFramePosition(0), which rewinds the media to the beginning - * of the clip. + * Playback of an audio clip may be started and stopped using the + * {@link #start start} and {@link #stop stop} methods. These methods do not + * reset the media position; {@code start} causes playback to continue from the + * position where playback was last stopped. To restart playback from the + * beginning of the clip's audio data, simply follow the invocation of + * {@code stop} with {@code setFramePosition(0)}, which rewinds the media to the + * beginning of the clip. * * @author Kara Kytle * @since 1.3 */ public interface Clip extends DataLine { - /** * A value indicating that looping should continue indefinitely rather than * complete after a specific number of loops. + * * @see #loop */ - public static final int LOOP_CONTINUOUSLY = -1; + int LOOP_CONTINUOUSLY = -1; /** - * Opens the clip, meaning that it should acquire any required - * system resources and become operational. The clip is opened - * with the format and audio data indicated. - * If this operation succeeds, the line is marked as open and an - * {@link LineEvent.Type#OPEN OPEN} event is dispatched - * to the line's listeners. + * Opens the clip, meaning that it should acquire any required system + * resources and become operational. The clip is opened with the format and + * audio data indicated. If this operation succeeds, the line is marked as + * open and an {@link LineEvent.Type#OPEN OPEN} event is dispatched to the + * line's listeners. *

    - * Invoking this method on a line which is already open is illegal - * and may result in an IllegalStateException. + * Invoking this method on a line which is already open is illegal and may + * result in an {@code IllegalStateException}. *

    - * Note that some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in a - * {@link LineUnavailableException}. + * Note that some lines, once closed, cannot be reopened. Attempts to reopen + * such a line will always result in a {@code LineUnavailableException}. * - * @param format the format of the supplied audio data - * @param data a byte array containing audio data to load into the clip - * @param offset the point at which to start copying, expressed in - * bytes from the beginning of the array - * @param bufferSize the number of bytes - * of data to load into the clip from the array. - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions - * @throws IllegalArgumentException if the buffer size does not represent - * an integral number of sample frames, - * or if format is not fully specified or invalid + * @param format the format of the supplied audio data + * @param data a byte array containing audio data to load into the clip + * @param offset the point at which to start copying, expressed in + * bytes from the beginning of the array + * @param bufferSize the number of bytes of data to load into the + * clip from the array + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws IllegalArgumentException if the buffer size does not represent an + * integral number of sample frames, or if {@code format} is not + * fully specified or invalid * @throws IllegalStateException if the line is already open - * @throws SecurityException if the line cannot be - * opened due to security restrictions - * + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #close * @see #isOpen * @see LineListener */ - public void open(AudioFormat format, byte[] data, int offset, int bufferSize) throws LineUnavailableException; + void open(AudioFormat format, byte[] data, int offset, int bufferSize) + throws LineUnavailableException; /** - * Opens the clip with the format and audio data present in the provided audio - * input stream. Opening a clip means that it should acquire any required - * system resources and become operational. If this operation - * input stream. If this operation - * succeeds, the line is marked open and an - * {@link LineEvent.Type#OPEN OPEN} event is dispatched - * to the line's listeners. + * Opens the clip with the format and audio data present in the provided + * audio input stream. Opening a clip means that it should acquire any + * required system resources and become operational. If this operation input + * stream. If this operation succeeds, the line is marked open and an + * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the line's + * listeners. *

    - * Invoking this method on a line which is already open is illegal - * and may result in an IllegalStateException. + * Invoking this method on a line which is already open is illegal and may + * result in an {@code IllegalStateException}. *

    - * Note that some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in a - * {@link LineUnavailableException}. + * Note that some lines, once closed, cannot be reopened. Attempts to reopen + * such a line will always result in a {@code LineUnavailableException}. * - * @param stream an audio input stream from which audio data will be read into - * the clip - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions - * @throws IOException if an I/O exception occurs during reading of - * the stream - * @throws IllegalArgumentException if the stream's audio format - * is not fully specified or invalid + * @param stream an audio input stream from which audio data will be read + * into the clip + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws IOException if an I/O exception occurs during reading of the + * stream + * @throws IllegalArgumentException if the stream's audio format is not + * fully specified or invalid * @throws IllegalStateException if the line is already open - * @throws SecurityException if the line cannot be - * opened due to security restrictions - * + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #close * @see #isOpen * @see LineListener */ - public void open(AudioInputStream stream) throws LineUnavailableException, IOException; + void open(AudioInputStream stream) + throws LineUnavailableException, IOException; /** * Obtains the media length in sample frames. - * @return the media length, expressed in sample frames, - * or AudioSystem.NOT_SPECIFIED if the line is not open. + * + * @return the media length, expressed in sample frames, or + * {@code AudioSystem.NOT_SPECIFIED} if the line is not open * @see AudioSystem#NOT_SPECIFIED */ - public int getFrameLength(); + int getFrameLength(); /** - * Obtains the media duration in microseconds - * @return the media duration, expressed in microseconds, - * or AudioSystem.NOT_SPECIFIED if the line is not open. + * Obtains the media duration in microseconds. + * + * @return the media duration, expressed in microseconds, or + * {@code AudioSystem.NOT_SPECIFIED} if the line is not open * @see AudioSystem#NOT_SPECIFIED */ - public long getMicrosecondLength(); + long getMicrosecondLength(); /** - * Sets the media position in sample frames. The position is zero-based; - * the first frame is frame number zero. When the clip begins playing the - * next time, it will start by playing the frame at this position. + * Sets the media position in sample frames. The position is zero-based; the + * first frame is frame number zero. When the clip begins playing the next + * time, it will start by playing the frame at this position. *

    * To obtain the current position in sample frames, use the - * {@link DataLine#getFramePosition getFramePosition} - * method of DataLine. + * {@link DataLine#getFramePosition getFramePosition} method of + * {@code DataLine}. * - * @param frames the desired new media position, expressed in sample frames + * @param frames the desired new media position, expressed in sample frames */ - public void setFramePosition(int frames); + void setFramePosition(int frames); /** - * Sets the media position in microseconds. When the clip begins playing the - * next time, it will start at this position. - * The level of precision is not guaranteed. For example, an implementation - * might calculate the microsecond position from the current frame position - * and the audio sample frame rate. The precision in microseconds would - * then be limited to the number of microseconds per sample frame. + * Sets the media position in microseconds. When the clip begins playing the + * next time, it will start at this position. The level of precision is not + * guaranteed. For example, an implementation might calculate the + * microsecond position from the current frame position and the audio sample + * frame rate. The precision in microseconds would then be limited to the + * number of microseconds per sample frame. *

    * To obtain the current position in microseconds, use the - * {@link DataLine#getMicrosecondPosition getMicrosecondPosition} - * method of DataLine. + * {@link DataLine#getMicrosecondPosition getMicrosecondPosition} method of + * {@code DataLine}. * - * @param microseconds the desired new media position, expressed in microseconds + * @param microseconds the desired new media position, expressed in + * microseconds */ - public void setMicrosecondPosition(long microseconds); + void setMicrosecondPosition(long microseconds); /** - * Sets the first and last sample frames that will be played in - * the loop. The ending point must be greater than - * or equal to the starting point, and both must fall within the - * the size of the loaded media. A value of 0 for the starting - * point means the beginning of the loaded media. Similarly, a value of -1 - * for the ending point indicates the last frame of the media. - * @param start the loop's starting position, in sample frames (zero-based) - * @param end the loop's ending position, in sample frames (zero-based), or - * -1 to indicate the final frame - * @throws IllegalArgumentException if the requested - * loop points cannot be set, usually because one or both falls outside - * the media's duration or because the ending point is - * before the starting point + * Sets the first and last sample frames that will be played in the loop. + * The ending point must be greater than or equal to the starting point, and + * both must fall within the the size of the loaded media. A value of 0 for + * the starting point means the beginning of the loaded media. Similarly, a + * value of -1 for the ending point indicates the last frame of the media. + * + * @param start the loop's starting position, in sample frames (zero-based) + * @param end the loop's ending position, in sample frames (zero-based), + * or -1 to indicate the final frame + * @throws IllegalArgumentException if the requested loop points cannot be + * set, usually because one or both falls outside the media's + * duration or because the ending point is before the starting point */ - public void setLoopPoints(int start, int end); + void setLoopPoints(int start, int end); /** - * Starts looping playback from the current position. Playback will - * continue to the loop's end point, then loop back to the loop start point - * count times, and finally continue playback to the end of - * the clip. + * Starts looping playback from the current position. Playback will continue + * to the loop's end point, then loop back to the loop start point + * {@code count} times, and finally continue playback to the end of the + * clip. *

    * If the current position when this method is invoked is greater than the - * loop end point, playback simply continues to the - * end of the clip without looping. + * loop end point, playback simply continues to the end of the clip without + * looping. *

    - * A count value of 0 indicates that any current looping should - * cease and playback should continue to the end of the clip. The behavior + * A {@code count} value of 0 indicates that any current looping should + * cease and playback should continue to the end of the clip. The behavior * is undefined when this method is invoked with any other value during a * loop operation. *

    @@ -214,10 +210,10 @@ public interface Clip extends DataLine { * cleared; the behavior of subsequent loop and start requests is not * affected by an interrupted loop operation. * - * @param count the number of times playback should loop back from the - * loop's end position to the loop's start position, or - * {@link #LOOP_CONTINUOUSLY} to indicate that looping should - * continue until interrupted + * @param count the number of times playback should loop back from the + * loop's end position to the loop's start position, or + * {@link #LOOP_CONTINUOUSLY} to indicate that looping should + * continue until interrupted */ - public void loop(int count); + void loop(int count); } diff --git a/jdk/src/share/classes/javax/sound/sampled/CompoundControl.java b/jdk/src/share/classes/javax/sound/sampled/CompoundControl.java index bb01fbe9f43..8cd400d7ea0 100644 --- a/jdk/src/share/classes/javax/sound/sampled/CompoundControl.java +++ b/jdk/src/share/classes/javax/sound/sampled/CompoundControl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,55 +26,37 @@ package javax.sound.sampled; /** - * A CompoundControl, such as a graphic equalizer, provides control - * over two or more related properties, each of which is itself represented as - * a Control. + * A {@code CompoundControl}, such as a graphic equalizer, provides control over + * two or more related properties, each of which is itself represented as a + * {@code Control}. * * @author Kara Kytle * @since 1.3 */ public abstract class CompoundControl extends Control { - - // TYPE DEFINES - - - // INSTANCE VARIABLES - - /** * The set of member controls. */ private Control[] controls; - - - // CONSTRUCTORS - - /** * Constructs a new compound control object with the given parameters. * - * @param type the type of control represented this compound control object - * @param memberControls the set of member controls + * @param type the type of control represented this compound control object + * @param memberControls the set of member controls */ protected CompoundControl(Type type, Control[] memberControls) { - super(type); this.controls = memberControls; } - - - // METHODS - - /** * Returns the set of member controls that comprise the compound control. - * @return the set of member controls. + * + * @return the set of member controls */ public Control[] getMemberControls() { - Control[] localArray = new Control[controls.length]; for (int i = 0; i < controls.length; i++) { @@ -84,14 +66,12 @@ public abstract class CompoundControl extends Control { return localArray; } - - // ABSTRACT METHOD IMPLEMENTATIONS: CONTROL - - /** - * Provides a string representation of the control + * Provides a string representation of the control. + * * @return a string description */ + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -108,13 +88,9 @@ public abstract class CompoundControl extends Control { return new String(getType() + " Control containing " + sb + " Controls."); } - - // INNER CLASSES - - /** - * An instance of the CompoundControl.Type inner class identifies one kind of - * compound control. Static instances are provided for the + * An instance of the {@code CompoundControl.Type} inner class identifies + * one kind of compound control. Static instances are provided for the * common types. * * @author Kara Kytle @@ -122,19 +98,13 @@ public abstract class CompoundControl extends Control { */ public static class Type extends Control.Type { - - // TYPE DEFINES - - // CONSTRUCTOR - - /** * Constructs a new compound control type. - * @param name the name of the new compound control type + * + * @param name the name of the new compound control type */ - protected Type(String name) { + protected Type(final String name) { super(name); } - } // class Type - -} // class CompoundControl + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/Control.java b/jdk/src/share/classes/javax/sound/sampled/Control.java index 6b8b9c6a5e4..a3257b8539e 100644 --- a/jdk/src/share/classes/javax/sound/sampled/Control.java +++ b/jdk/src/share/classes/javax/sound/sampled/Control.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,121 +26,102 @@ package javax.sound.sampled; /** - * {@link Line Lines} often have a set of controls, such as gain and pan, that affect - * the audio signal passing through the line. Java Sound's Line objects - * let you obtain a particular control object by passing its class as the - * argument to a {@link Line#getControl(Control.Type) getControl} method. + * {@link Line Lines} often have a set of controls, such as gain and pan, that + * affect the audio signal passing through the line. Java Sound's {@code Line} + * objects let you obtain a particular control object by passing its class as + * the argument to a {@link Line#getControl(Control.Type) getControl} method. *

    * Because the various types of controls have different purposes and features, - * all of their functionality is accessed from the subclasses that define - * each kind of control. + * all of their functionality is accessed from the subclasses that define each + * kind of control. * * @author Kara Kytle - * * @see Line#getControls * @see Line#isControlSupported * @since 1.3 */ public abstract class Control { - - // INSTANCE VARIABLES - /** * The control type. */ private final Type type; - - - // CONSTRUCTORS - /** * Constructs a Control with the specified type. - * @param type the kind of control desired + * + * @param type the kind of control desired */ protected Control(Type type) { this.type = type; } - - // METHODS - /** * Obtains the control's type. - * @return the control's type. + * + * @return the control's type */ public Type getType() { return type; } - - // ABSTRACT METHODS - /** * Obtains a String describing the control type and its current state. - * @return a String representation of the Control. + * + * @return a String representation of the Control */ + @Override public String toString() { return new String(getType() + " Control"); } - /** - * An instance of the Type class represents the type of - * the control. Static instances are provided for the - * common types. + * An instance of the {@code Type} class represents the type of the control. + * Static instances are provided for the common types. */ public static class Type { - // CONTROL TYPE DEFINES - - // INSTANCE VARIABLES - /** * Type name. */ private String name; - - // CONSTRUCTOR - /** - * Constructs a new control type with the name specified. - * The name should be a descriptive string appropriate for - * labelling the control in an application, such as "Gain" or "Balance." - * @param name the name of the new control type. + * Constructs a new control type with the name specified. The name + * should be a descriptive string appropriate for labelling the control + * in an application, such as "Gain" or "Balance". + * + * @param name the name of the new control type */ protected Type(String name) { this.name = name; } - - // METHODS - /** - * Finalizes the equals method + * Finalizes the equals method. */ + @Override public final boolean equals(Object obj) { return super.equals(obj); } /** - * Finalizes the hashCode method + * Finalizes the hashCode method. */ + @Override public final int hashCode() { return super.hashCode(); } /** - * Provides the String representation of the control type. This String is - * the same name that was passed to the constructor. + * Provides the {@code String} representation of the control type. This + * {@code String} is the same name that was passed to the constructor. * * @return the control type name */ + @Override public final String toString() { return name; } - } // class Type - -} // class Control + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/DataLine.java b/jdk/src/share/classes/javax/sound/sampled/DataLine.java index d9013560381..9a81a76c5b6 100644 --- a/jdk/src/share/classes/javax/sound/sampled/DataLine.java +++ b/jdk/src/share/classes/javax/sound/sampled/DataLine.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,40 +28,35 @@ package javax.sound.sampled; import java.util.Arrays; /** - * DataLine adds media-related functionality to its - * superinterface, {@link Line}. This functionality includes - * transport-control methods that start, stop, drain, and flush - * the audio data that passes through the line. A data line can also - * report the current position, volume, and audio format of the media. - * Data lines are used for output of audio by means of the - * subinterfaces {@link SourceDataLine} or - * {@link Clip}, which allow an application program to write data. Similarly, - * audio input is handled by the subinterface {@link TargetDataLine}, - * which allows data to be read. + * {@code DataLine} adds media-related functionality to its superinterface, + * {@code Line}. This functionality includes transport-control methods that + * start, stop, drain, and flush the audio data that passes through the line. A + * data line can also report the current position, volume, and audio format of + * the media. Data lines are used for output of audio by means of the + * subinterfaces {@link SourceDataLine} or {@link Clip}, which allow an + * application program to write data. Similarly, audio input is handled by the + * subinterface {@link TargetDataLine}, which allows data to be read. *

    - * A data line has an internal buffer in which - * the incoming or outgoing audio data is queued. The - * {@link #drain()} method blocks until this internal buffer - * becomes empty, usually because all queued data has been processed. The - * {@link #flush()} method discards any available queued data - * from the internal buffer. + * A data line has an internal buffer in which the incoming or outgoing audio + * data is queued. The {@link #drain()} method blocks until this internal buffer + * becomes empty, usually because all queued data has been processed. The + * {@link #flush()} method discards any available queued data from the internal + * buffer. *

    - * A data line produces {@link LineEvent.Type#START START} and - * {@link LineEvent.Type#STOP STOP} events whenever - * it begins or ceases active presentation or capture of data. These events - * can be generated in response to specific requests, or as a result of - * less direct state changes. For example, if {@link #start()} is called - * on an inactive data line, and data is available for capture or playback, a - * START event will be generated shortly, when data playback - * or capture actually begins. Or, if the flow of data to an active data - * line is constricted so that a gap occurs in the presentation of data, - * a STOP event is generated. + * A data line produces {@link LineEvent.Type#START START} and + * {@link LineEvent.Type#STOP STOP} events whenever it begins or ceases active + * presentation or capture of data. These events can be generated in response to + * specific requests, or as a result of less direct state changes. For example, + * if {@link #start()} is called on an inactive data line, and data is available + * for capture or playback, a {@code START} event will be generated shortly, + * when data playback or capture actually begins. Or, if the flow of data to an + * active data line is constricted so that a gap occurs in the presentation of + * data, a {@code STOP} event is generated. *

    * Mixers often support synchronized control of multiple data lines. * Synchronization can be established through the Mixer interface's - * {@link Mixer#synchronize synchronize} method. - * See the description of the {@link Mixer Mixer} interface - * for a more complete description. + * {@link Mixer#synchronize synchronize} method. See the description of the + * {@link Mixer Mixer} interface for a more complete description. * * @author Kara Kytle * @see LineEvent @@ -69,220 +64,217 @@ import java.util.Arrays; */ public interface DataLine extends Line { - /** - * Drains queued data from the line by continuing data I/O until the - * data line's internal buffer has been emptied. - * This method blocks until the draining is complete. Because this is a - * blocking method, it should be used with care. If drain() - * is invoked on a stopped line that has data in its queue, the method will - * block until the line is running and the data queue becomes empty. If - * drain() is invoked by one thread, and another continues to - * fill the data queue, the operation will not complete. - * This method always returns when the data line is closed. + * Drains queued data from the line by continuing data I/O until the data + * line's internal buffer has been emptied. This method blocks until the + * draining is complete. Because this is a blocking method, it should be + * used with care. If {@code drain()} is invoked on a stopped line that has + * data in its queue, the method will block until the line is running and + * the data queue becomes empty. If {@code drain()} is invoked by one + * thread, and another continues to fill the data queue, the operation will + * not complete. This method always returns when the data line is closed. * * @see #flush() */ - public void drain(); + void drain(); /** - * Flushes queued data from the line. The flushed data is discarded. - * In some cases, not all queued data can be discarded. For example, a - * mixer can flush data from the buffer for a specific input line, but any - * unplayed data already in the output buffer (the result of the mix) will - * still be played. You can invoke this method after pausing a line (the - * normal case) if you want to skip the "stale" data when you restart - * playback or capture. (It is legal to flush a line that is not stopped, - * but doing so on an active line is likely to cause a discontinuity in the - * data, resulting in a perceptible click.) + * Flushes queued data from the line. The flushed data is discarded. In some + * cases, not all queued data can be discarded. For example, a mixer can + * flush data from the buffer for a specific input line, but any unplayed + * data already in the output buffer (the result of the mix) will still be + * played. You can invoke this method after pausing a line (the normal case) + * if you want to skip the "stale" data when you restart playback or + * capture. (It is legal to flush a line that is not stopped, but doing so + * on an active line is likely to cause a discontinuity in the data, + * resulting in a perceptible click.) * * @see #stop() * @see #drain() */ - public void flush(); + void flush(); /** - * Allows a line to engage in data I/O. If invoked on a line - * that is already running, this method does nothing. Unless the data in - * the buffer has been flushed, the line resumes I/O starting - * with the first frame that was unprocessed at the time the line was - * stopped. When audio capture or playback starts, a - * {@link LineEvent.Type#START START} event is generated. + * Allows a line to engage in data I/O. If invoked on a line that is already + * running, this method does nothing. Unless the data in the buffer has been + * flushed, the line resumes I/O starting with the first frame that was + * unprocessed at the time the line was stopped. When audio capture or + * playback starts, a {@link LineEvent.Type#START START} event is generated. * * @see #stop() * @see #isRunning() * @see LineEvent */ - public void start(); + void start(); /** - * Stops the line. A stopped line should cease I/O activity. - * If the line is open and running, however, it should retain the resources required - * to resume activity. A stopped line should retain any audio data in its buffer - * instead of discarding it, so that upon resumption the I/O can continue where it left off, - * if possible. (This doesn't guarantee that there will never be discontinuities beyond the - * current buffer, of course; if the stopped condition continues - * for too long, input or output samples might be dropped.) If desired, the retained data can be - * discarded by invoking the flush method. - * When audio capture or playback stops, a {@link LineEvent.Type#STOP STOP} event is generated. + * Stops the line. A stopped line should cease I/O activity. If the line is + * open and running, however, it should retain the resources required to + * resume activity. A stopped line should retain any audio data in its + * buffer instead of discarding it, so that upon resumption the I/O can + * continue where it left off, if possible. (This doesn't guarantee that + * there will never be discontinuities beyond the current buffer, of course; + * if the stopped condition continues for too long, input or output samples + * might be dropped.) If desired, the retained data can be discarded by + * invoking the {@code flush} method. When audio capture or playback stops, + * a {@link LineEvent.Type#STOP STOP} event is generated. * * @see #start() * @see #isRunning() * @see #flush() * @see LineEvent */ - public void stop(); + void stop(); /** - * Indicates whether the line is running. The default is false. - * An open line begins running when the first data is presented in response to an - * invocation of the start method, and continues - * until presentation ceases in response to a call to stop or - * because playback completes. - * @return true if the line is running, otherwise false + * Indicates whether the line is running. The default is {@code false}. An + * open line begins running when the first data is presented in response to + * an invocation of the {@code start} method, and continues until + * presentation ceases in response to a call to {@code stop} or because + * playback completes. + * + * @return {@code true} if the line is running, otherwise {@code false} * @see #start() * @see #stop() */ - public boolean isRunning(); + boolean isRunning(); /** - * Indicates whether the line is engaging in active I/O (such as playback - * or capture). When an inactive line becomes active, it sends a - * {@link LineEvent.Type#START START} event to its listeners. Similarly, when - * an active line becomes inactive, it sends a - * {@link LineEvent.Type#STOP STOP} event. - * @return true if the line is actively capturing or rendering - * sound, otherwise false + * Indicates whether the line is engaging in active I/O (such as playback or + * capture). When an inactive line becomes active, it sends a + * {@link LineEvent.Type#START START} event to its listeners. Similarly, + * when an active line becomes inactive, it sends a + * {@link LineEvent.Type#STOP STOP} event. + * + * @return {@code true} if the line is actively capturing or rendering + * sound, otherwise {@code false} * @see #isOpen * @see #addLineListener * @see #removeLineListener * @see LineEvent * @see LineListener */ - public boolean isActive(); + boolean isActive(); /** * Obtains the current format (encoding, sample rate, number of channels, * etc.) of the data line's audio data. - * - *

    If the line is not open and has never been opened, it returns - * the default format. The default format is an implementation - * specific audio format, or, if the DataLine.Info - * object, which was used to retrieve this DataLine, - * specifies at least one fully qualified audio format, the - * last one will be used as the default format. Opening the - * line with a specific audio format (e.g. - * {@link SourceDataLine#open(AudioFormat)}) will override the - * default format. + *

    + * If the line is not open and has never been opened, it returns the default + * format. The default format is an implementation specific audio format, + * or, if the {@code DataLine.Info} object, which was used to retrieve this + * {@code DataLine}, specifies at least one fully qualified audio format, + * the last one will be used as the default format. Opening the line with a + * specific audio format (e.g. {@link SourceDataLine#open(AudioFormat)}) + * will override the default format. * * @return current audio data format * @see AudioFormat */ - public AudioFormat getFormat(); + AudioFormat getFormat(); /** - * Obtains the maximum number of bytes of data that will fit in the data line's - * internal buffer. For a source data line, this is the size of the buffer to - * which data can be written. For a target data line, it is the size of - * the buffer from which data can be read. Note that - * the units used are bytes, but will always correspond to an integral - * number of sample frames of audio data. + * Obtains the maximum number of bytes of data that will fit in the data + * line's internal buffer. For a source data line, this is the size of the + * buffer to which data can be written. For a target data line, it is the + * size of the buffer from which data can be read. Note that the units used + * are bytes, but will always correspond to an integral number of sample + * frames of audio data. * * @return the size of the buffer in bytes */ - public int getBufferSize(); + int getBufferSize(); /** * Obtains the number of bytes of data currently available to the - * application for processing in the data line's internal buffer. For a + * application for processing in the data line's internal buffer. For a * source data line, this is the amount of data that can be written to the - * buffer without blocking. For a target data line, this is the amount of data - * available to be read by the application. For a clip, this value is always - * 0 because the audio data is loaded into the buffer when the clip is opened, - * and persists without modification until the clip is closed. + * buffer without blocking. For a target data line, this is the amount of + * data available to be read by the application. For a clip, this value is + * always 0 because the audio data is loaded into the buffer when the clip + * is opened, and persists without modification until the clip is closed. *

    - * Note that the units used are bytes, but will always - * correspond to an integral number of sample frames of audio data. + * Note that the units used are bytes, but will always correspond to an + * integral number of sample frames of audio data. *

    - * An application is guaranteed that a read or - * write operation of up to the number of bytes returned from - * available() will not block; however, there is no guarantee - * that attempts to read or write more data will block. + * An application is guaranteed that a read or write operation of up to the + * number of bytes returned from {@code available()} will not block; + * however, there is no guarantee that attempts to read or write more data + * will block. * * @return the amount of data available, in bytes */ - public int available(); + int available(); /** - * Obtains the current position in the audio data, in sample frames. - * The frame position measures the number of sample - * frames captured by, or rendered from, the line since it was opened. - * This return value will wrap around after 2^31 frames. It is recommended - * to use getLongFramePosition instead. + * Obtains the current position in the audio data, in sample frames. The + * frame position measures the number of sample frames captured by, or + * rendered from, the line since it was opened. This return value will wrap + * around after 2^31 frames. It is recommended to use + * {@code getLongFramePosition} instead. * * @return the number of frames already processed since the line was opened * @see #getLongFramePosition() */ - public int getFramePosition(); - + int getFramePosition(); /** - * Obtains the current position in the audio data, in sample frames. - * The frame position measures the number of sample - * frames captured by, or rendered from, the line since it was opened. + * Obtains the current position in the audio data, in sample frames. The + * frame position measures the number of sample frames captured by, or + * rendered from, the line since it was opened. * * @return the number of frames already processed since the line was opened * @since 1.5 */ - public long getLongFramePosition(); - + long getLongFramePosition(); /** - * Obtains the current position in the audio data, in microseconds. - * The microsecond position measures the time corresponding to the number - * of sample frames captured by, or rendered from, the line since it was opened. - * The level of precision is not guaranteed. For example, an implementation - * might calculate the microsecond position from the current frame position - * and the audio sample frame rate. The precision in microseconds would - * then be limited to the number of microseconds per sample frame. + * Obtains the current position in the audio data, in microseconds. The + * microsecond position measures the time corresponding to the number of + * sample frames captured by, or rendered from, the line since it was + * opened. The level of precision is not guaranteed. For example, an + * implementation might calculate the microsecond position from the current + * frame position and the audio sample frame rate. The precision in + * microseconds would then be limited to the number of microseconds per + * sample frame. * - * @return the number of microseconds of data processed since the line was opened + * @return the number of microseconds of data processed since the line was + * opened */ - public long getMicrosecondPosition(); + long getMicrosecondPosition(); /** - * Obtains the current volume level for the line. This level is a measure - * of the signal's current amplitude, and should not be confused with the - * current setting of a gain control. The range is from 0.0 (silence) to - * 1.0 (maximum possible amplitude for the sound waveform). The units - * measure linear amplitude, not decibels. + * Obtains the current volume level for the line. This level is a measure of + * the signal's current amplitude, and should not be confused with the + * current setting of a gain control. The range is from 0.0 (silence) to 1.0 + * (maximum possible amplitude for the sound waveform). The units measure + * linear amplitude, not decibels. * * @return the current amplitude of the signal in this line, or - * {@link AudioSystem#NOT_SPECIFIED} + * {@link AudioSystem#NOT_SPECIFIED} */ - public float getLevel(); + float getLevel(); /** * Besides the class information inherited from its superclass, - * DataLine.Info provides additional information specific to data lines. - * This information includes: + * {@code DataLine.Info} provides additional information specific to data + * lines. This information includes: *

      *
    • the audio formats supported by the data line *
    • the minimum and maximum sizes of its internal buffer *
    - * Because a Line.Info knows the class of the line its describes, a - * DataLine.Info object can describe DataLine - * subinterfaces such as {@link SourceDataLine}, - * {@link TargetDataLine}, and {@link Clip}. - * You can query a mixer for lines of any of these types, passing an appropriate - * instance of DataLine.Info as the argument to a method such as - * {@link Mixer#getLine Mixer.getLine(Line.Info)}. + * Because a {@code Line.Info} knows the class of the line its describes, a + * {@code DataLine.Info} object can describe {@code DataLine} subinterfaces + * such as {@link SourceDataLine}, {@link TargetDataLine}, and {@link Clip}. + * You can query a mixer for lines of any of these types, passing an + * appropriate instance of {@code DataLine.Info} as the argument to a method + * such as {@link Mixer#getLine(Line.Info)}. * * @see Line.Info * @author Kara Kytle * @since 1.3 */ - public static class Info extends Line.Info { + class Info extends Line.Info { private final AudioFormat[] formats; private final int minBufferSize; @@ -290,14 +282,17 @@ public interface DataLine extends Line { /** * Constructs a data line's info object from the specified information, - * which includes a set of supported audio formats and a range for the buffer size. - * This constructor is typically used by mixer implementations - * when returning information about a supported line. + * which includes a set of supported audio formats and a range for the + * buffer size. This constructor is typically used by mixer + * implementations when returning information about a supported line. * - * @param lineClass the class of the data line described by the info object - * @param formats set of formats supported - * @param minBufferSize minimum buffer size supported by the data line, in bytes - * @param maxBufferSize maximum buffer size supported by the data line, in bytes + * @param lineClass the class of the data line described by the info + * object + * @param formats set of formats supported + * @param minBufferSize minimum buffer size supported by the data + * line, in bytes + * @param maxBufferSize maximum buffer size supported by the data + * line, in bytes */ public Info(Class lineClass, AudioFormat[] formats, int minBufferSize, int maxBufferSize) { @@ -313,16 +308,16 @@ public interface DataLine extends Line { this.maxBufferSize = maxBufferSize; } - /** * Constructs a data line's info object from the specified information, - * which includes a single audio format and a desired buffer size. - * This constructor is typically used by an application to - * describe a desired line. + * which includes a single audio format and a desired buffer size. This + * constructor is typically used by an application to describe a desired + * line. * - * @param lineClass the class of the data line described by the info object - * @param format desired format - * @param bufferSize desired buffer size in bytes + * @param lineClass the class of the data line described by the info + * object + * @param format desired format + * @param bufferSize desired buffer size in bytes */ public Info(Class lineClass, AudioFormat format, int bufferSize) { @@ -338,39 +333,36 @@ public interface DataLine extends Line { this.maxBufferSize = bufferSize; } - /** * Constructs a data line's info object from the specified information, - * which includes a single audio format. - * This constructor is typically used by an application to - * describe a desired line. + * which includes a single audio format. This constructor is typically + * used by an application to describe a desired line. * - * @param lineClass the class of the data line described by the info object - * @param format desired format + * @param lineClass the class of the data line described by the info + * object + * @param format desired format */ public Info(Class lineClass, AudioFormat format) { this(lineClass, format, AudioSystem.NOT_SPECIFIED); } - /** - * Obtains a set of audio formats supported by the data line. - * Note that isFormatSupported(AudioFormat) might return - * true for certain additional formats that are missing from - * the set returned by getFormats(). The reverse is not - * the case: isFormatSupported(AudioFormat) is guaranteed to return - * true for all formats returned by getFormats(). - * + * Obtains a set of audio formats supported by the data line. Note that + * {@code isFormatSupported(AudioFormat)} might return {@code true} for + * certain additional formats that are missing from the set returned by + * {@code getFormats()}. The reverse is not the case: + * {@code isFormatSupported(AudioFormat)} is guaranteed to return + * {@code true} for all formats returned by {@code getFormats()}. + *

    * Some fields in the AudioFormat instances can be set to * {@link javax.sound.sampled.AudioSystem#NOT_SPECIFIED NOT_SPECIFIED} - * if that field does not apply to the format, - * or if the format supports a wide range of values for that field. - * For example, a multi-channel device supporting up to - * 64 channels, could set the channel field in the - * AudioFormat instances returned by this - * method to NOT_SPECIFIED. + * if that field does not apply to the format, or if the format supports + * a wide range of values for that field. For example, a multi-channel + * device supporting up to 64 channels, could set the channel field in + * the {@code AudioFormat} instances returned by this method to + * {@code NOT_SPECIFIED}. * - * @return a set of supported audio formats. + * @return a set of supported audio formats * @see #isFormatSupported(AudioFormat) */ public AudioFormat[] getFormats() { @@ -379,11 +371,12 @@ public interface DataLine extends Line { /** * Indicates whether this data line supports a particular audio format. - * The default implementation of this method simply returns true if - * the specified format matches any of the supported formats. + * The default implementation of this method simply returns {@code true} + * if the specified format matches any of the supported formats. * - * @param format the audio format for which support is queried. - * @return true if the format is supported, otherwise false + * @param format the audio format for which support is queried + * @return {@code true} if the format is supported, otherwise + * {@code false} * @see #getFormats * @see AudioFormat#matches */ @@ -400,32 +393,36 @@ public interface DataLine extends Line { /** * Obtains the minimum buffer size supported by the data line. - * @return minimum buffer size in bytes, or AudioSystem.NOT_SPECIFIED + * + * @return minimum buffer size in bytes, or + * {@code AudioSystem.NOT_SPECIFIED} */ public int getMinBufferSize() { return minBufferSize; } - /** * Obtains the maximum buffer size supported by the data line. - * @return maximum buffer size in bytes, or AudioSystem.NOT_SPECIFIED + * + * @return maximum buffer size in bytes, or + * {@code AudioSystem.NOT_SPECIFIED} */ public int getMaxBufferSize() { return maxBufferSize; } - /** - * Determines whether the specified info object matches this one. - * To match, the superclass match requirements must be met. In - * addition, this object's minimum buffer size must be at least as - * large as that of the object specified, its maximum buffer size must - * be at most as large as that of the object specified, and all of its - * formats must match formats supported by the object specified. - * @return true if this object matches the one specified, - * otherwise false. + * Determines whether the specified info object matches this one. To + * match, the superclass match requirements must be met. In addition, + * this object's minimum buffer size must be at least as large as that + * of the object specified, its maximum buffer size must be at most as + * large as that of the object specified, and all of its formats must + * match formats supported by the object specified. + * + * @return {@code true} if this object matches the one specified, + * otherwise {@code false} */ + @Override public boolean matches(Line.Info info) { if (! (super.matches(info)) ) { @@ -467,8 +464,10 @@ public interface DataLine extends Line { /** * Obtains a textual description of the data line info. + * * @return a string description */ + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -489,6 +488,5 @@ public interface DataLine extends Line { return new String(super.toString() + sb); } - } // class Info - -} // interface DataLine + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/EnumControl.java b/jdk/src/share/classes/javax/sound/sampled/EnumControl.java index d9f4baccbda..c029f224ebc 100644 --- a/jdk/src/share/classes/javax/sound/sampled/EnumControl.java +++ b/jdk/src/share/classes/javax/sound/sampled/EnumControl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,83 +26,63 @@ package javax.sound.sampled; /** - * A EnumControl provides control over a set of - * discrete possible values, each represented by an object. In a - * graphical user interface, such a control might be represented - * by a set of buttons, each of which chooses one value or setting. For - * example, a reverb control might provide several preset reverberation - * settings, instead of providing continuously adjustable parameters - * of the sort that would be represented by {@link FloatControl} + * A {@code EnumControl} provides control over a set of discrete possible values + * , each represented by an object. In a graphical user interface, such a + * control might be represented by a set of buttons, each of which chooses one + * value or setting. For example, a reverb control might provide several preset + * reverberation settings, instead of providing continuously adjustable + * parameters of the sort that would be represented by {@link FloatControl} * objects. *

    - * Controls that provide a choice between only two settings can often be implemented - * instead as a {@link BooleanControl}, and controls that provide - * a set of values along some quantifiable dimension might be implemented - * instead as a FloatControl with a coarse resolution. - * However, a key feature of EnumControl is that the returned values - * are arbitrary objects, rather than numerical or boolean values. This means that each - * returned object can provide further information. As an example, the settings - * of a {@link EnumControl.Type#REVERB REVERB} control are instances of - * {@link ReverbType} that can be queried for the parameter values - * used for each setting. + * Controls that provide a choice between only two settings can often be + * implemented instead as a {@link BooleanControl}, and controls that provide a + * set of values along some quantifiable dimension might be implemented instead + * as a {@code FloatControl} with a coarse resolution. However, a key feature of + * {@code EnumControl} is that the returned values are arbitrary objects, rather + * than numerical or boolean values. This means that each returned object can + * provide further information. As an example, the settings of a + * {@link EnumControl.Type#REVERB REVERB} control are instances of + * {@link ReverbType} that can be queried for the parameter values used for each + * setting. * * @author Kara Kytle * @since 1.3 */ public abstract class EnumControl extends Control { - - // TYPE DEFINES - - - // INSTANCE VARIABLES - - /** * The set of possible values. */ private Object[] values; - /** * The current value. */ private Object value; - - - // CONSTRUCTORS - - /** * Constructs a new enumerated control object with the given parameters. * - * @param type the type of control represented this enumerated control object - * @param values the set of possible values for the control - * @param value the initial control value + * @param type the type of control represented this enumerated control + * object + * @param values the set of possible values for the control + * @param value the initial control value */ protected EnumControl(Type type, Object[] values, Object value) { - super(type); - this.values = values; this.value = value; } - - - // METHODS - - /** - * Sets the current value for the control. The default implementation - * simply sets the value as indicated. If the value indicated is not - * supported, an IllegalArgumentException is thrown. - * Some controls require that their line be open before they can be affected - * by setting a value. - * @param value the desired new value + * Sets the current value for the control. The default implementation simply + * sets the value as indicated. If the value indicated is not supported, an + * {@code IllegalArgumentException} is thrown. Some controls require that + * their line be open before they can be affected by setting a value. + * + * @param value the desired new value * @throws IllegalArgumentException if the value indicated does not fall - * within the allowable range + * within the allowable range */ public void setValue(Object value) { if (!isValueSupported(value)) { @@ -112,18 +92,18 @@ public abstract class EnumControl extends Control { this.value = value; } - /** * Obtains this control's current value. + * * @return the current value */ public Object getValue() { return value; } - /** * Returns the set of possible values for this control. + * * @return the set of possible values */ public Object[] getValues() { @@ -137,12 +117,11 @@ public abstract class EnumControl extends Control { return localArray; } - /** * Indicates whether the value specified is supported. - * @param value the value for which support is queried - * @return true if the value is supported, - * otherwise false + * + * @param value the value for which support is queried + * @return {@code true} if the value is supported, otherwise {@code false} */ private boolean isValueSupported(Object value) { @@ -157,58 +136,43 @@ public abstract class EnumControl extends Control { return false; } - - - // ABSTRACT METHOD IMPLEMENTATIONS: CONTROL - - /** * Provides a string representation of the control. + * * @return a string description */ + @Override public String toString() { return new String(getType() + " with current value: " + getValue()); } - - // INNER CLASSES - - /** - * An instance of the EnumControl.Type inner class identifies one kind of - * enumerated control. Static instances are provided for the - * common types. - * - * @see EnumControl + * An instance of the {@code EnumControl.Type} inner class identifies one + * kind of enumerated control. Static instances are provided for the common + * types. * * @author Kara Kytle + * @see EnumControl * @since 1.3 */ public static class Type extends Control.Type { - - // TYPE DEFINES - /** * Represents a control over a set of possible reverberation settings. * Each reverberation setting is described by an instance of the - * {@link ReverbType} class. (To access these settings, - * invoke {@link EnumControl#getValues} on an - * enumerated control of type REVERB.) + * {@link ReverbType} class. (To access these settings, invoke + * {@link EnumControl#getValues} on an enumerated control of type + * {@code REVERB}.) */ public static final Type REVERB = new Type("Reverb"); - - // CONSTRUCTOR - - /** * Constructs a new enumerated control type. - * @param name the name of the new enumerated control type + * + * @param name the name of the new enumerated control type */ - protected Type(String name) { + protected Type(final String name) { super(name); } - } // class Type - -} // class EnumControl + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/FloatControl.java b/jdk/src/share/classes/javax/sound/sampled/FloatControl.java index b2678d11428..27d59fefe1f 100644 --- a/jdk/src/share/classes/javax/sound/sampled/FloatControl.java +++ b/jdk/src/share/classes/javax/sound/sampled/FloatControl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,39 +26,31 @@ package javax.sound.sampled; /** - * A FloatControl object provides control over a range of - * floating-point values. Float controls are often - * represented in graphical user interfaces by continuously - * adjustable objects such as sliders or rotary knobs. Concrete subclasses - * of FloatControl implement controls, such as gain and pan, that - * affect a line's audio signal in some way that an application can manipulate. - * The {@link FloatControl.Type} - * inner class provides static instances of types that are used to - * identify some common kinds of float control. + * A {@code FloatControl} object provides control over a range of floating-point + * values. Float controls are often represented in graphical user interfaces by + * continuously adjustable objects such as sliders or rotary knobs. Concrete + * subclasses of {@code FloatControl} implement controls, such as gain and pan, + * that affect a line's audio signal in some way that an application can + * manipulate. The {@link FloatControl.Type} inner class provides static + * instances of types that are used to identify some common kinds of float + * control. *

    - * The FloatControl abstract class provides methods to set and get - * the control's current floating-point value. Other methods obtain the possible + * The {@code FloatControl} abstract class provides methods to set and get the + * control's current floating-point value. Other methods obtain the possible * range of values and the control's resolution (the smallest increment between - * returned values). Some float controls allow ramping to a - * new value over a specified period of time. FloatControl also - * includes methods that return string labels for the minimum, maximum, and midpoint - * positions of the control. - * - * @see Line#getControls - * @see Line#isControlSupported + * returned values). Some float controls allow ramping to a new value over a + * specified period of time. {@code FloatControl} also includes methods that + * return string labels for the minimum, maximum, and midpoint positions of the + * control. * * @author David Rivas * @author Kara Kytle + * @see Line#getControls + * @see Line#isControlSupported * @since 1.3 */ public abstract class FloatControl extends Control { - - // INSTANCE VARIABLES - - - // FINAL VARIABLES - /** * The minimum supported value. */ @@ -75,66 +67,60 @@ public abstract class FloatControl extends Control { private float precision; /** - * The smallest time increment in which a value change - * can be effected during a value shift, in microseconds. + * The smallest time increment in which a value change can be effected + * during a value shift, in microseconds. */ private int updatePeriod; - /** - * A label for the units in which the control values are expressed, - * such as "dB" for decibels. + * A label for the units in which the control values are expressed, such as + * "dB" for decibels. */ private final String units; /** - * A label for the minimum value, such as "Left." + * A label for the minimum value, such as "Left". */ private final String minLabel; /** - * A label for the maximum value, such as "Right." + * A label for the maximum value, such as "Right". */ private final String maxLabel; /** - * A label for the mid-point value, such as "Center." + * A label for the mid-point value, such as "Center". */ private final String midLabel; - - // STATE VARIABLES - /** * The current value. */ private float value; - - - // CONSTRUCTORS - - /** - * Constructs a new float control object with the given parameters + * Constructs a new float control object with the given parameters. * - * @param type the kind of control represented by this float control object - * @param minimum the smallest value permitted for the control - * @param maximum the largest value permitted for the control - * @param precision the resolution or granularity of the control. - * This is the size of the increment between discrete valid values. - * @param updatePeriod the smallest time interval, in microseconds, over which the control - * can change from one discrete value to the next during a {@link #shift(float,float,int) shift} - * @param initialValue the value that the control starts with when constructed - * @param units the label for the units in which the control's values are expressed, - * such as "dB" or "frames per second" - * @param minLabel the label for the minimum value, such as "Left" or "Off" - * @param midLabel the label for the midpoint value, such as "Center" or "Default" - * @param maxLabel the label for the maximum value, such as "Right" or "Full" - * - * @throws IllegalArgumentException if {@code minimum} is greater - * than {@code maximum} or {@code initialValue} does not fall - * within the allowable range + * @param type the kind of control represented by this float control object + * @param minimum the smallest value permitted for the control + * @param maximum the largest value permitted for the control + * @param precision the resolution or granularity of the control. This is + * the size of the increment between discrete valid values. + * @param updatePeriod the smallest time interval, in microseconds, over + * which the control can change from one discrete value to the next + * during a {@link #shift(float,float,int) shift} + * @param initialValue the value that the control starts with when + * constructed + * @param units the label for the units in which the control's values are + * expressed, such as "dB" or "frames per second" + * @param minLabel the label for the minimum value, such as "Left" or "Off" + * @param midLabel the label for the midpoint value, such as "Center" or + * "Default" + * @param maxLabel the label for the maximum value, such as "Right" or + * "Full" + * @throws IllegalArgumentException if {@code minimum} is greater than + * {@code maximum} or {@code initialValue} does not fall within the + * allowable range */ protected FloatControl(Type type, float minimum, float maximum, float precision, int updatePeriod, float initialValue, @@ -169,26 +155,26 @@ public abstract class FloatControl extends Control { this.maxLabel = ( (maxLabel == null) ? "" : maxLabel); } - /** - * Constructs a new float control object with the given parameters. - * The labels for the minimum, maximum, and mid-point values are set - * to zero-length strings. + * Constructs a new float control object with the given parameters. The + * labels for the minimum, maximum, and mid-point values are set to + * zero-length strings. * - * @param type the kind of control represented by this float control object - * @param minimum the smallest value permitted for the control - * @param maximum the largest value permitted for the control - * @param precision the resolution or granularity of the control. - * This is the size of the increment between discrete valid values. - * @param updatePeriod the smallest time interval, in microseconds, over which the control - * can change from one discrete value to the next during a {@link #shift(float,float,int) shift} - * @param initialValue the value that the control starts with when constructed - * @param units the label for the units in which the control's values are expressed, - * such as "dB" or "frames per second" - * - * @throws IllegalArgumentException if {@code minimum} is greater - * than {@code maximum} or {@code initialValue} does not fall - * within the allowable range + * @param type the kind of control represented by this float control object + * @param minimum the smallest value permitted for the control + * @param maximum the largest value permitted for the control + * @param precision the resolution or granularity of the control. This is + * the size of the increment between discrete valid values. + * @param updatePeriod the smallest time interval, in microseconds, over + * which the control can change from one discrete value to the next + * during a {@link #shift(float,float,int) shift} + * @param initialValue the value that the control starts with when + * constructed + * @param units the label for the units in which the control's values are + * expressed, such as "dB" or "frames per second" + * @throws IllegalArgumentException if {@code minimum} is greater than + * {@code maximum} or {@code initialValue} does not fall within the + * allowable range */ protected FloatControl(Type type, float minimum, float maximum, float precision, int updatePeriod, float initialValue, String units) { @@ -196,21 +182,16 @@ public abstract class FloatControl extends Control { initialValue, units, "", "", ""); } - - - // METHODS - - /** - * Sets the current value for the control. The default implementation - * simply sets the value as indicated. If the value indicated is greater - * than the maximum value, or smaller than the minimum value, an - * IllegalArgumentException is thrown. - * Some controls require that their line be open before they can be affected - * by setting a value. - * @param newValue desired new value + * Sets the current value for the control. The default implementation simply + * sets the value as indicated. If the value indicated is greater than the + * maximum value, or smaller than the minimum value, an + * {@code IllegalArgumentException} is thrown. Some controls require that + * their line be open before they can be affected by setting a value. + * + * @param newValue desired new value * @throws IllegalArgumentException if the value indicated does not fall - * within the allowable range + * within the allowable range */ public void setValue(float newValue) { @@ -225,113 +206,114 @@ public abstract class FloatControl extends Control { value = newValue; } - /** * Obtains this control's current value. + * * @return the current value */ public float getValue() { return value; } - /** * Obtains the maximum value permitted. + * * @return the maximum allowable value */ public float getMaximum() { return maximum; } - /** * Obtains the minimum value permitted. + * * @return the minimum allowable value */ public float getMinimum() { return minimum; } - /** - * Obtains the label for the units in which the control's values are expressed, - * such as "dB" or "frames per second." + * Obtains the label for the units in which the control's values are + * expressed, such as "dB" or "frames per second." + * * @return the units label, or a zero-length string if no label */ public String getUnits() { return units; } - /** - * Obtains the label for the minimum value, such as "Left" or "Off." - * @return the minimum value label, or a zero-length string if no label * has been set + * Obtains the label for the minimum value, such as "Left" or "Off". + * + * @return the minimum value label, or a zero-length string if no label has + * been set */ public String getMinLabel() { return minLabel; } - /** - * Obtains the label for the mid-point value, such as "Center" or "Default." - * @return the mid-point value label, or a zero-length string if no label * has been set + * Obtains the label for the mid-point value, such as "Center" or "Default". + * + * @return the mid-point value label, or a zero-length string if no label + * has been set */ public String getMidLabel() { return midLabel; } - /** - * Obtains the label for the maximum value, such as "Right" or "Full." - * @return the maximum value label, or a zero-length string if no label * has been set + * Obtains the label for the maximum value, such as "Right" or "Full". + * + * @return the maximum value label, or a zero-length string if no label has + * been set */ public String getMaxLabel() { return maxLabel; } - /** - * Obtains the resolution or granularity of the control, in the units - * that the control measures. - * The precision is the size of the increment between discrete valid values - * for this control, over the set of supported floating-point values. + * Obtains the resolution or granularity of the control, in the units that + * the control measures. The precision is the size of the increment between + * discrete valid values for this control, over the set of supported + * floating-point values. + * * @return the control's precision */ public float getPrecision() { return precision; } - /** - * Obtains the smallest time interval, in microseconds, over which the control's value can - * change during a shift. The update period is the inverse of the frequency with which - * the control updates its value during a shift. If the implementation does not support value shifting over - * time, it should set the control's value to the final value immediately - * and return -1 from this method. + * Obtains the smallest time interval, in microseconds, over which the + * control's value can change during a shift. The update period is the + * inverse of the frequency with which the control updates its value during + * a shift. If the implementation does not support value shifting over time, + * it should set the control's value to the final value immediately and + * return -1 from this method. * - * @return update period in microseconds, or -1 if shifting over time is unsupported + * @return update period in microseconds, or -1 if shifting over time is + * unsupported * @see #shift */ public int getUpdatePeriod() { return updatePeriod; } - /** - * Changes the control value from the initial value to the final - * value linearly over the specified time period, specified in microseconds. - * This method returns without blocking; it does not wait for the shift - * to complete. An implementation should complete the operation within the time - * specified. The default implementation simply changes the value - * to the final value immediately. - * - * @param from initial value at the beginning of the shift - * @param to final value after the shift - * @param microseconds maximum duration of the shift in microseconds + * Changes the control value from the initial value to the final value + * linearly over the specified time period, specified in microseconds. This + * method returns without blocking; it does not wait for the shift to + * complete. An implementation should complete the operation within the time + * specified. The default implementation simply changes the value to the + * final value immediately. * + * @param from initial value at the beginning of the shift + * @param to final value after the shift + * @param microseconds maximum duration of the shift in microseconds * @throws IllegalArgumentException if either {@code from} or {@code to} - * value does not fall within the allowable range - * + * value does not fall within the allowable range * @see #getUpdatePeriod */ public void shift(float from, float to, int microseconds) { @@ -347,12 +329,9 @@ public abstract class FloatControl extends Control { setValue(to); } - - // ABSTRACT METHOD IMPLEMENTATIONS: CONTROL - - /** - * Provides a string representation of the control + * Provides a string representation of the control. + * * @return a string description */ public String toString() { @@ -360,55 +339,45 @@ public abstract class FloatControl extends Control { " (range: " + minimum + " - " + maximum + ")"); } - - // INNER CLASSES - - /** - * An instance of the FloatControl.Type inner class identifies one kind of - * float control. Static instances are provided for the - * common types. + * An instance of the {@code FloatControl.Type} inner class identifies one + * kind of float control. Static instances are provided for the common + * types. * * @author Kara Kytle * @since 1.3 */ public static class Type extends Control.Type { - - // TYPE DEFINES - - - // GAIN TYPES - /** * Represents a control for the overall gain on a line. *

    * Gain is a quantity in decibels (dB) that is added to the intrinsic - * decibel level of the audio signal--that is, the level of - * the signal before it is altered by the gain control. A positive - * gain amplifies (boosts) the signal's volume, and a negative gain - * attenuates (cuts) it. + * decibel level of the audio signal--that is, the level of the signal + * before it is altered by the gain control. A positive gain amplifies + * (boosts) the signal's volume, and a negative gain attenuates(cuts)it. * The gain setting defaults to a value of 0.0 dB, meaning the signal's - * loudness is unaffected. Note that gain measures dB, not amplitude. + * loudness is unaffected. Note that gain measures dB, not amplitude. * The relationship between a gain in decibels and the corresponding * linear amplitude multiplier is: * - *

    linearScalar = pow(10.0, gainDB/20.0)
    + *
    {@code linearScalar = pow(10.0, gainDB/20.0)}
    *

    - * The FloatControl class has methods to impose a maximum and - * minimum allowable value for gain. However, because an audio signal might - * already be at a high amplitude, the maximum setting does not guarantee - * that the signal will be undistorted when the gain is applied to it (unless - * the maximum is zero or negative). To avoid numeric overflow from excessively - * large gain settings, a gain control can implement - * clipping, meaning that the signal's amplitude will be limited to the maximum - * value representable by its audio format, instead of wrapping around. + * The {@code FloatControl} class has methods to impose a maximum and + * minimum allowable value for gain. However, because an audio signal + * might already be at a high amplitude, the maximum setting does not + * guarantee that the signal will be undistorted when the gain is + * applied to it (unless the maximum is zero or negative). To avoid + * numeric overflow from excessively large gain settings, a gain control + * can implement clipping, meaning that the signal's amplitude will be + * limited to the maximum value representable by its audio format, + * instead of wrapping around. *

    - * These comments apply to gain controls in general, not just master gain controls. - * A line can have more than one gain control. For example, a mixer (which is - * itself a line) might have a master gain control, an auxiliary return control, - * a reverb return control, and, on each of its source lines, an individual aux - * send and reverb send. + * These comments apply to gain controls in general, not just master + * gain controls. A line can have more than one gain control. For + * example, a mixer (which is itself a line) might have a master gain + * control, an auxiliary return control, a reverb return control, and, + * on each of its source lines, an individual aux send and reverb send. * * @see #AUX_SEND * @see #AUX_RETURN @@ -435,9 +404,9 @@ public abstract class FloatControl extends Control { public static final Type AUX_RETURN = new Type("AUX Return"); /** - * Represents a control for the pre-reverb gain on a line. - * This control may be used to affect how much - * of a line's signal is directed to a mixer's internal reverberation unit. + * Represents a control for the pre-reverb gain on a line. This control + * may be used to affect how much of a line's signal is directed to a + * mixer's internal reverberation unit. * * @see #MASTER_GAIN * @see #REVERB_RETURN @@ -446,18 +415,15 @@ public abstract class FloatControl extends Control { public static final Type REVERB_SEND = new Type("Reverb Send"); /** - * Represents a control for the post-reverb gain on a line. - * This control may be used to control the relative amplitude - * of the signal returned from an internal reverberation unit. + * Represents a control for the post-reverb gain on a line. This control + * may be used to control the relative amplitude of the signal returned + * from an internal reverberation unit. * * @see #MASTER_GAIN * @see #REVERB_SEND */ public static final Type REVERB_RETURN = new Type("Reverb Return"); - - // VOLUME - /** * Represents a control for the volume on a line. */ @@ -466,64 +432,52 @@ public abstract class FloatControl extends Control { */ public static final Type VOLUME = new Type("Volume"); - - // PAN - /** - * Represents a control for the relative pan (left-right positioning) - * of the signal. The signal may be mono; the pan setting affects how - * it is distributed by the mixer in a stereo mix. The valid range of values is -1.0 - * (left channel only) to 1.0 (right channel - * only). The default is 0.0 (centered). + * Represents a control for the relative pan (left-right positioning) of + * the signal. The signal may be mono; the pan setting affects how it is + * distributed by the mixer in a stereo mix. The valid range of values + * is -1.0 (left channel only) to 1.0 (right channel only). The default + * is 0.0 (centered). * * @see #BALANCE */ public static final Type PAN = new Type("Pan"); - - // BALANCE - /** * Represents a control for the relative balance of a stereo signal - * between two stereo speakers. The valid range of values is -1.0 (left channel only) to 1.0 (right channel - * only). The default is 0.0 (centered). + * between two stereo speakers. The valid range of values is -1.0 (left + * channel only) to 1.0 (right channel only). The default is 0.0 + * (centered). * * @see #PAN */ public static final Type BALANCE = new Type("Balance"); - - // SAMPLE RATE - /** - * Represents a control that changes the sample rate of audio playback. The net effect - * of changing the sample rate depends on the relationship between - * the media's natural rate and the rate that is set via this control. - * The natural rate is the sample rate that is specified in the data line's - * AudioFormat object. For example, if the natural rate - * of the media is 11025 samples per second and the sample rate is set - * to 22050 samples per second, the media will play back at twice the - * normal speed. + * Represents a control that changes the sample rate of audio playback. + * The net effect of changing the sample rate depends on the + * relationship between the media's natural rate and the rate that is + * set via this control. The natural rate is the sample rate that is + * specified in the data line's {@code AudioFormat} object. For example, + * if the natural rate of the media is 11025 samples per second and the + * sample rate is set to 22050 samples per second, the media will play + * back at twice the normal speed. *

    - * Changing the sample rate with this control does not affect the data line's - * audio format. Also note that whenever you change a sound's sample rate, a - * change in the sound's pitch results. For example, doubling the sample - * rate has the effect of doubling the frequencies in the sound's spectrum, - * which raises the pitch by an octave. + * Changing the sample rate with this control does not affect the data + * line's audio format. Also note that whenever you change a sound's + * sample rate, a change in the sound's pitch results. For example, + * doubling the sample rate has the effect of doubling the frequencies + * in the sound's spectrum, which raises the pitch by an octave. */ public static final Type SAMPLE_RATE = new Type("Sample Rate"); - - // CONSTRUCTOR - /** * Constructs a new float control type. - * @param name the name of the new float control type + * + * @param name the name of the new float control type */ - protected Type(String name) { + protected Type(final String name) { super(name); } - - } // class Type - -} // class FloatControl + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/Line.java b/jdk/src/share/classes/javax/sound/sampled/Line.java index dfab63470cc..feb69fde185 100644 --- a/jdk/src/share/classes/javax/sound/sampled/Line.java +++ b/jdk/src/share/classes/javax/sound/sampled/Line.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,96 +26,90 @@ package javax.sound.sampled; /** - * The Line interface represents a mono or multi-channel - * audio feed. A line is an element of the digital audio - * "pipeline," such as a mixer, an input or output port, - * or a data path into or out of a mixer. + * The {@code Line} interface represents a mono or multi-channel audio feed. A + * line is an element of the digital audio "pipeline," such as a mixer, an input + * or output port, or a data path into or out of a mixer. *

    - * A line can have controls, such as gain, pan, and reverb. - * The controls themselves are instances of classes that extend the - * base {@link Control} class. - * The Line interface provides two accessor methods for - * obtaining the line's controls: {@link #getControls getControls} returns the - * entire set, and {@link #getControl getControl} returns a single control of - * specified type. + * A line can have controls, such as gain, pan, and reverb. The controls + * themselves are instances of classes that extend the base {@link Control} + * class. The {@code Line} interface provides two accessor methods for obtaining + * the line's controls: {@link #getControls getControls} returns the entire set, + * and {@link #getControl getControl} returns a single control of specified + * type. *

    - * Lines exist in various states at different times. When a line opens, it reserves system - * resources for itself, and when it closes, these resources are freed for - * other objects or applications. The {@link #isOpen()} method lets - * you discover whether a line is open or closed. - * An open line need not be processing data, however. Such processing is - * typically initiated by subinterface methods such as - * {@link SourceDataLine#write SourceDataLine.write} and - * {@link TargetDataLine#read TargetDataLine.read}. - *

    - * You can register an object to receive notifications whenever the line's - * state changes. The object must implement the {@link LineListener} - * interface, which consists of the single method - * {@link LineListener#update update}. - * This method will be invoked when a line opens and closes (and, if it's a - * {@link DataLine}, when it starts and stops). - *

    - * An object can be registered to listen to multiple lines. The event it - * receives in its update method will specify which line created - * the event, what type of event it was - * (OPEN, CLOSE, START, or STOP), - * and how many sample frames the line had processed at the time the event occurred. + * Lines exist in various states at different times. When a line opens, it + * reserves system resources for itself, and when it closes, these resources are + * freed for other objects or applications. The {@link #isOpen()} method lets + * you discover whether a line is open or closed. An open line need not be + * processing data, however. Such processing is typically initiated by + * subinterface methods such as + * {@link SourceDataLine#write SourceDataLine.write} and + * {@link TargetDataLine#read TargetDataLine.read}. + *

    + * You can register an object to receive notifications whenever the line's state + * changes. The object must implement the {@link LineListener} interface, which + * consists of the single method {@link LineListener#update update}. This method + * will be invoked when a line opens and closes (and, if it's a {@link DataLine} + * , when it starts and stops). + *

    + * An object can be registered to listen to multiple lines. The event it + * receives in its {@code update} method will specify which line created the + * event, what type of event it was ({@code OPEN}, {@code CLOSE}, {@code START}, + * or {@code STOP}), and how many sample frames the line had processed at the + * time the event occurred. *

    * Certain line operations, such as open and close, can generate security * exceptions if invoked by unprivileged code when the line is a shared audio * resource. * * @author Kara Kytle - * * @see LineEvent * @since 1.3 */ public interface Line extends AutoCloseable { /** - * Obtains the Line.Info object describing this - * line. + * Obtains the {@code Line.Info} object describing this line. + * * @return description of the line */ - public Line.Info getLineInfo(); + Line.Info getLineInfo(); /** - * Opens the line, indicating that it should acquire any required - * system resources and become operational. - * If this operation - * succeeds, the line is marked as open, and an OPEN event is dispatched - * to the line's listeners. + * Opens the line, indicating that it should acquire any required system + * resources and become operational. If this operation succeeds, the line is + * marked as open, and an {@code OPEN} event is dispatched to the line's + * listeners. *

    - * Note that some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in an LineUnavailableException. + * Note that some lines, once closed, cannot be reopened. Attempts to reopen + * such a line will always result in an {@code LineUnavailableException}. *

    - * Some types of lines have configurable properties that may affect - * resource allocation. For example, a DataLine must - * be opened with a particular format and buffer size. Such lines - * should provide a mechanism for configuring these properties, such - * as an additional open method or methods which allow - * an application to specify the desired settings. + * Some types of lines have configurable properties that may affect resource + * allocation. For example, a {@code DataLine} must be opened with a + * particular format and buffer size. Such lines should provide a mechanism + * for configuring these properties, such as an additional {@code open} + * method or methods which allow an application to specify the desired + * settings. *

    * This method takes no arguments, and opens the line with the current - * settings. For {@link SourceDataLine} and - * {@link TargetDataLine} objects, this means that the line is - * opened with default settings. For a {@link Clip}, however, - * the buffer size is determined when data is loaded. Since this method does not - * allow the application to specify any data to load, an IllegalArgumentException - * is thrown. Therefore, you should instead use one of the open methods - * provided in the Clip interface to load data into the Clip. + * settings. For {@link SourceDataLine} and {@link TargetDataLine} objects, + * this means that the line is opened with default settings. For a + * {@link Clip}, however, the buffer size is determined when data is loaded. + * Since this method does not allow the application to specify any data to + * load, an {@code IllegalArgumentException} is thrown. Therefore, you + * should instead use one of the {@code open} methods provided in the + * {@code Clip} interface to load data into the {@code Clip}. *

    - * For DataLine's, if the DataLine.Info - * object which was used to retrieve the line, specifies at least - * one fully qualified audio format, the last one will be used - * as the default format. - * - * @throws IllegalArgumentException if this method is called on a Clip instance. - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions. - * @throws SecurityException if the line cannot be - * opened due to security restrictions. + * For {@code DataLine}'s, if the {@code DataLine.Info} object which was + * used to retrieve the line, specifies at least one fully qualified audio + * format, the last one will be used as the default format. * + * @throws IllegalArgumentException if this method is called on a Clip + * instance + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #close * @see #isOpen * @see LineEvent @@ -123,133 +117,128 @@ public interface Line extends AutoCloseable { * @see Clip#open(AudioFormat, byte[], int, int) * @see Clip#open(AudioInputStream) */ - public void open() throws LineUnavailableException; - + void open() throws LineUnavailableException; /** - * Closes the line, indicating that any system resources - * in use by the line can be released. If this operation - * succeeds, the line is marked closed and a CLOSE event is dispatched - * to the line's listeners. - * @throws SecurityException if the line cannot be - * closed due to security restrictions. + * Closes the line, indicating that any system resources in use by the line + * can be released. If this operation succeeds, the line is marked closed + * and a {@code CLOSE} event is dispatched to the line's listeners. * + * @throws SecurityException if the line cannot be closed due to security + * restrictions * @see #open * @see #isOpen * @see LineEvent */ - public void close(); - - + @Override + void close(); /** - * Indicates whether the line is open, meaning that it has reserved - * system resources and is operational, although it might not currently be - * playing or capturing sound. - * @return true if the line is open, otherwise false + * Indicates whether the line is open, meaning that it has reserved system + * resources and is operational, although it might not currently be playing + * or capturing sound. * + * @return {@code true} if the line is open, otherwise {@code false} * @see #open() * @see #close() */ - public boolean isOpen(); - + boolean isOpen(); /** - * Obtains the set of controls associated with this line. - * Some controls may only be available when the line is open. - * If there are no controls, this method returns an array of length 0. + * Obtains the set of controls associated with this line. Some controls may + * only be available when the line is open. If there are no controls, this + * method returns an array of length 0. + * * @return the array of controls * @see #getControl */ - public Control[] getControls(); + Control[] getControls(); /** - * Indicates whether the line supports a control of the specified type. - * Some controls may only be available when the line is open. - * @param control the type of the control for which support is queried - * @return true if at least one control of the specified type is - * supported, otherwise false. + * Indicates whether the line supports a control of the specified type. Some + * controls may only be available when the line is open. + * + * @param control the type of the control for which support is queried + * @return {@code true} if at least one control of the specified type is + * supported, otherwise {@code false} */ - public boolean isControlSupported(Control.Type control); - + boolean isControlSupported(Control.Type control); /** - * Obtains a control of the specified type, - * if there is any. - * Some controls may only be available when the line is open. - * @param control the type of the requested control + * Obtains a control of the specified type, if there is any. Some controls + * may only be available when the line is open. + * + * @param control the type of the requested control * @return a control of the specified type - * @throws IllegalArgumentException if a control of the specified type - * is not supported + * @throws IllegalArgumentException if a control of the specified type is + * not supported * @see #getControls * @see #isControlSupported(Control.Type control) */ - public Control getControl(Control.Type control); - + Control getControl(Control.Type control); /** - * Adds a listener to this line. Whenever the line's status changes, the - * listener's update() method is called with a LineEvent object - * that describes the change. - * @param listener the object to add as a listener to this line + * Adds a listener to this line. Whenever the line's status changes, the + * listener's {@code update()} method is called with a {@code LineEvent} + * object that describes the change. + * + * @param listener the object to add as a listener to this line * @see #removeLineListener * @see LineListener#update * @see LineEvent */ - public void addLineListener(LineListener listener); - + void addLineListener(LineListener listener); /** * Removes the specified listener from this line's list of listeners. - * @param listener listener to remove + * + * @param listener listener to remove * @see #addLineListener */ - public void removeLineListener(LineListener listener); - + void removeLineListener(LineListener listener); /** - * A Line.Info object contains information about a line. - * The only information provided by Line.Info itself - * is the Java class of the line. - * A subclass of Line.Info adds other kinds of information - * about the line. This additional information depends on which Line - * subinterface is implemented by the kind of line that the Line.Info - * subclass describes. + * A {@code Line.Info} object contains information about a line. The only + * information provided by {@code Line.Info} itself is the Java class of the + * line. A subclass of {@code Line.Info} adds other kinds of information + * about the line. This additional information depends on which {@code Line} + * subinterface is implemented by the kind of line that the + * {@code Line.Info} subclass describes. *

    - * A Line.Info can be retrieved using various methods of - * the Line, Mixer, and AudioSystem - * interfaces. Other such methods let you pass a Line.Info as - * an argument, to learn whether lines matching the specified configuration - * are available and to obtain them. + * A {@code Line.Info} can be retrieved using various methods of the + * {@code Line}, {@code Mixer}, and {@code AudioSystem} interfaces. Other + * such methods let you pass a {@code Line.Info} as an argument, to learn + * whether lines matching the specified configuration are available and to + * obtain them. * * @author Kara Kytle - * - * @see Line#getLineInfo - * @see Mixer#getSourceLineInfo - * @see Mixer#getTargetLineInfo - * @see Mixer#getLine Mixer.getLine(Line.Info) - * @see Mixer#getSourceLineInfo(Line.Info) Mixer.getSourceLineInfo(Line.Info) - * @see Mixer#getSourceLineInfo(Line.Info) Mixer.getTargetLineInfo(Line.Info) - * @see Mixer#isLineSupported Mixer.isLineSupported(Line.Info) - * @see AudioSystem#getLine AudioSystem.getLine(Line.Info) - * @see AudioSystem#getSourceLineInfo AudioSystem.getSourceLineInfo(Line.Info) - * @see AudioSystem#getTargetLineInfo AudioSystem.getTargetLineInfo(Line.Info) - * @see AudioSystem#isLineSupported AudioSystem.isLineSupported(Line.Info) + * @see Line#getLineInfo() + * @see Mixer#getSourceLineInfo() + * @see Mixer#getTargetLineInfo() + * @see Mixer#getLine(Line.Info) + * @see Mixer#getSourceLineInfo(Line.Info) + * @see Mixer#getTargetLineInfo(Line.Info) + * @see Mixer#isLineSupported(Line.Info) + * @see AudioSystem#getLine(Line.Info) + * @see AudioSystem#getSourceLineInfo(Line.Info) + * @see AudioSystem#getTargetLineInfo(Line.Info) + * @see AudioSystem#isLineSupported(Line.Info) * @since 1.3 */ - public static class Info { + class Info { /** * The class of the line described by the info object. */ - private final Class lineClass; - + private final Class lineClass; /** - * Constructs an info object that describes a line of the specified class. - * This constructor is typically used by an application to + * Constructs an info object that describes a line of the specified + * class. This constructor is typically used by an application to * describe a desired line. - * @param lineClass the class of the line that the new Line.Info object describes + * + * @param lineClass the class of the line that the new Line.Info object + * describes */ public Info(Class lineClass) { @@ -260,33 +249,29 @@ public interface Line extends AutoCloseable { } } - - /** * Obtains the class of the line that this Line.Info object describes. + * * @return the described line's class */ public Class getLineClass() { return lineClass; } - /** - * Indicates whether the specified info object matches this one. - * To match, the specified object must be identical to or - * a special case of this one. The specified info object - * must be either an instance of the same class as this one, - * or an instance of a sub-type of this one. In addition, the - * attributes of the specified object must be compatible with the - * capabilities of this one. Specifically, the routing configuration - * for the specified info object must be compatible with that of this - * one. - * Subclasses may add other criteria to determine whether the two objects - * match. + * Indicates whether the specified info object matches this one. To + * match, the specified object must be identical to or a special case of + * this one. The specified info object must be either an instance of + * the same class as this one, or an instance of a sub-type of this one. + * In addition, the attributes of the specified object must be + * compatible with the capabilities of this one. Specifically, the + * routing configuration for the specified info object must be + * compatible with that of this one. Subclasses may add other criteria + * to determine whether the two objects match. * - * @param info the info object which is being compared to this one - * @return true if the specified object matches this one, - * false otherwise + * @param info the info object which is being compared to this one + * @return {@code true} if the specified object matches this one, + * {@code false} otherwise */ public boolean matches(Info info) { @@ -320,7 +305,6 @@ public interface Line extends AutoCloseable { return false; } - // this.isAssignableFrom(that) => this is same or super to that // => this is at least as general as that // => that may be subtype of this @@ -332,11 +316,12 @@ public interface Line extends AutoCloseable { return true; } - /** * Obtains a textual description of the line info. + * * @return a string description */ + @Override public String toString() { String fullPackagePath = "javax.sound.sampled."; @@ -353,7 +338,5 @@ public interface Line extends AutoCloseable { return finalString; } - - } // class Info - -} // interface Line + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/LineEvent.java b/jdk/src/share/classes/javax/sound/sampled/LineEvent.java index ff5b90f1ba1..035c38f74f5 100644 --- a/jdk/src/share/classes/javax/sound/sampled/LineEvent.java +++ b/jdk/src/share/classes/javax/sound/sampled/LineEvent.java @@ -25,61 +25,64 @@ package javax.sound.sampled; +import java.util.EventObject; + /** - * The LineEvent class encapsulates information that a line - * sends its listeners whenever the line opens, closes, starts, or stops. - * Each of these four state changes is represented by a corresponding - * type of event. A listener receives the event as a parameter to its - * {@link LineListener#update update} method. By querying the event, - * the listener can learn the type of event, the line responsible for - * the event, and how much data the line had processed when the event occurred. - * - *

    Although this class implements Serializable, attempts to - * serialize a LineEvent object will fail. + * The {@code LineEvent} class encapsulates information that a line sends its + * listeners whenever the line opens, closes, starts, or stops. Each of these + * four state changes is represented by a corresponding type of event. A + * listener receives the event as a parameter to its + * {@link LineListener#update update} method. By querying the event, the + * listener can learn the type of event, the line responsible for the event, and + * how much data the line had processed when the event occurred. + *

    + * Although this class implements Serializable, attempts to serialize a + * {@code LineEvent} object will fail. * * @author Kara Kytle - * * @see Line * @see LineListener#update * @since 1.3 * * @serial exclude */ -public class LineEvent extends java.util.EventObject { +public class LineEvent extends EventObject { + private static final long serialVersionUID = -1274246333383880410L; - // INSTANCE VARIABLES - /** - * The kind of line event (OPEN, CLOSE, - * START, or STOP). - * @see #getType + * The kind of line event ({@code OPEN}, {@code CLOSE}, {@code START}, or + * {@code STOP}). + * * @serial + * @see #getType */ private final Type type; /** * The media position when the event occurred, expressed in sample frames. - * Note that this field is only relevant to certain events generated by - * data lines, such as START and STOP. For - * events generated by lines that do not count sample frames, and for any - * other events for which this value is not known, the position value - * should be {@link AudioSystem#NOT_SPECIFIED}. + * Note that this field is only relevant to certain events generated by data + * lines, such as {@code START} and {@code STOP}. For events generated by + * lines that do not count sample frames, and for any other events for which + * this value is not known, the position value should be + * {@link AudioSystem#NOT_SPECIFIED}. + * * @serial * @see #getFramePosition */ private final long position; - /** - * Constructs a new event of the specified type, originating from the specified line. - * @param line the source of this event - * @param type the event type (OPEN, CLOSE, START, or STOP) - * @param position the number of sample frames that the line had already processed when the event occurred, - * or {@link AudioSystem#NOT_SPECIFIED} + * Constructs a new event of the specified type, originating from the + * specified line. * - * @throws IllegalArgumentException if line is - * null. + * @param line the source of this event + * @param type the event type ({@code OPEN}, {@code CLOSE}, {@code START}, + * or {@code STOP}) + * @param position the number of sample frames that the line had already + * processed when the event occurred, or + * {@link AudioSystem#NOT_SPECIFIED} + * @throws IllegalArgumentException if {@code line} is {@code null}. */ public LineEvent(Line line, Type type, long position) { @@ -90,6 +93,7 @@ public class LineEvent extends java.util.EventObject { /** * Obtains the audio line that is the source of this event. + * * @return the line responsible for this event */ public final Line getLine() { @@ -97,11 +101,11 @@ public class LineEvent extends java.util.EventObject { return (Line)getSource(); } - /** * Obtains the event's type. + * * @return this event's type ({@link Type#OPEN}, {@link Type#CLOSE}, - * {@link Type#START}, or {@link Type#STOP}) + * {@link Type#START}, or {@link Type#STOP}) */ public final Type getType() { @@ -109,21 +113,24 @@ public class LineEvent extends java.util.EventObject { } /** - * Obtains the position in the line's audio data when the event occurred, expressed in sample frames. - * For example, if a source line had already played back 14 sample frames at the time it was - * paused, the pause event would report the line's position as 14. The next frame to be processed - * would be frame number 14 using zero-based numbering, or 15 using one-based numbering. + * Obtains the position in the line's audio data when the event occurred, + * expressed in sample frames. For example, if a source line had already + * played back 14 sample frames at the time it was paused, the pause event + * would report the line's position as 14. The next frame to be processed + * would be frame number 14 using zero-based numbering, or 15 using + * one-based numbering. *

    - * Note that this field is relevant only to certain events generated by - * data lines, such as START and STOP. For - * events generated by lines that do not count sample frames, and for any - * other events for which this value is not known, the position value - * should be {@link AudioSystem#NOT_SPECIFIED}. + * Note that this field is relevant only to certain events generated by data + * lines, such as {@code START} and {@code STOP}. For events generated by + * lines that do not count sample frames, and for any other events for which + * this value is not known, the position value should be + * {@link AudioSystem#NOT_SPECIFIED}. * * @return the line's position as a sample frame number */ /* - * $$kk: 04.20.99: note to myself: should make sure our implementation is consistent with this. + * $$kk: 04.20.99: note to myself: should make sure our implementation is + * consistent with this. * which is a reasonable definition.... */ public final long getFramePosition() { @@ -132,10 +139,12 @@ public class LineEvent extends java.util.EventObject { } /** - * Obtains a string representation of the event. The contents of the string may vary - * between implementations of Java Sound. - * @return a string describing the event. + * Obtains a string representation of the event. The contents of the string + * may vary between implementations of Java Sound. + * + * @return a string describing the event */ + @Override public String toString() { String sType = ""; if (type != null) sType = type.toString()+" "; @@ -148,16 +157,15 @@ public class LineEvent extends java.util.EventObject { return new String(sType + "event from line " + sLine); } - /** - * The LineEvent.Type inner class identifies what kind of event occurred on a line. - * Static instances are provided for the common types (OPEN, CLOSE, START, and STOP). + * The LineEvent.Type inner class identifies what kind of event occurred on + * a line. Static instances are provided for the common types (OPEN, CLOSE, + * START, and STOP). * * @see LineEvent#getType() */ public static class Type { - /** * Type name. */ @@ -166,82 +174,84 @@ public class LineEvent extends java.util.EventObject { /** * Constructs a new event type. - * @param name name of the type + * + * @param name name of the type */ protected Type(String name) { this.name = name; } - //$$fb 2002-11-26: fix for 4695001: SPEC: description of equals() method contains typo + /** * Indicates whether the specified object is equal to this event type, - * returning true if the objects are identical. - * @param obj the reference object with which to compare - * @return true if this event type is the same as - * obj; false otherwise + * returning {@code true} if the objects are identical. + * + * @param obj the reference object with which to compare + * @return {@code true} if this event type is the same as {@code obj}; + * {@code false} otherwise */ + @Override public final boolean equals(Object obj) { return super.equals(obj); } - /** * Finalizes the hashcode method. */ + @Override public final int hashCode() { return super.hashCode(); } - /** * Returns the type name as the string representation. */ + @Override public String toString() { return name; } - // LINE EVENT TYPE DEFINES /** * A type of event that is sent when a line opens, reserving system * resources for itself. + * * @see #CLOSE * @see Line#open */ public static final Type OPEN = new Type("Open"); - /** * A type of event that is sent when a line closes, freeing the system * resources it had obtained when it was opened. + * * @see #OPEN * @see Line#close */ public static final Type CLOSE = new Type("Close"); - /** * A type of event that is sent when a line begins to engage in active * input or output of audio data in response to a * {@link DataLine#start start} request. + * * @see #STOP * @see DataLine#start */ public static final Type START = new Type("Start"); - /** - * A type of event that is sent when a line ceases active input or output - * of audio data in response to a {@link DataLine#stop stop} request, - * or because the end of media has been reached. + * A type of event that is sent when a line ceases active input or + * output of audio data in response to a {@link DataLine#stop stop} + * request, or because the end of media has been reached. + * * @see #START * @see DataLine#stop */ public static final Type STOP = new Type("Stop"); - /** * A type of event that is sent when a line ceases to engage in active * input or output of audio data because the end of media has been reached. @@ -255,7 +265,6 @@ public class LineEvent extends java.util.EventObject { */ //public static final Type EOM = new Type("EOM"); - /** * A type of event that is sent when a line begins to engage in active * input or output of audio data. Examples of when this happens are @@ -268,7 +277,6 @@ public class LineEvent extends java.util.EventObject { */ //public static final Type ACTIVE = new Type("ACTIVE"); - /** * A type of event that is sent when a line ceases active input or output * of audio data. @@ -276,7 +284,5 @@ public class LineEvent extends java.util.EventObject { * @see DataLine#stop */ //public static final Type INACTIVE = new Type("INACTIVE"); - - } // class Type - -} // class LineEvent + } +} diff --git a/jdk/src/share/classes/javax/sound/sampled/LineListener.java b/jdk/src/share/classes/javax/sound/sampled/LineListener.java index 57d6468007d..5d0434d6d86 100644 --- a/jdk/src/share/classes/javax/sound/sampled/LineListener.java +++ b/jdk/src/share/classes/javax/sound/sampled/LineListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,44 +25,27 @@ package javax.sound.sampled; - +import java.util.EventListener; /** - * Instances of classes that implement the LineListener interface can register to - * receive events when a line's status changes. + * Instances of classes that implement the {@code LineListener} interface can + * register to receive events when a line's status changes. * * @author Kara Kytle - * * @see Line * @see Line#addLineListener * @see Line#removeLineListener * @see LineEvent - * * @since 1.3 */ -/* - * Instances of classes that implement the LineListener interface can register to - * receive events when a line's status changes. - * - * @see Line - * @see Line#addLineListener - * @see Line#removeLineListener - * @see LineEvent - * - * @author Kara Kytle - */ -public interface LineListener extends java.util.EventListener { +public interface LineListener extends EventListener { /** - * Informs the listener that a line's state has changed. The listener can then invoke - * LineEvent methods to obtain information about the event. - * @param event a line event that describes the change + * Informs the listener that a line's state has changed. The listener can + * then invoke {@code LineEvent} methods to obtain information about the + * event. + * + * @param event a line event that describes the change */ - /* - * Informs the listener that a line's state has changed. The listener can then invoke - * LineEvent methods to obtain information about the event. - * @param event a line event that describes the change - */ - public void update(LineEvent event); - -} // interface LineListener + void update(LineEvent event); +} diff --git a/jdk/src/share/classes/javax/sound/sampled/LineUnavailableException.java b/jdk/src/share/classes/javax/sound/sampled/LineUnavailableException.java index 1e72f75061e..701d8ee499a 100644 --- a/jdk/src/share/classes/javax/sound/sampled/LineUnavailableException.java +++ b/jdk/src/share/classes/javax/sound/sampled/LineUnavailableException.java @@ -26,43 +26,32 @@ package javax.sound.sampled; /** - * A LineUnavailableException is an exception indicating that a - * line cannot be opened because it is unavailable. This situation - * arises most commonly when a requested line is already in use - * by another application. + * A {@code LineUnavailableException} is an exception indicating that a line + * cannot be opened because it is unavailable. This situation arises most + * commonly when a requested line is already in use by another application. * * @author Kara Kytle * @since 1.3 */ -/* - * A LinenavailableException is an exception indicating that a - * line annot be opened because it is unavailable. This situation - * arises most commonly when a line is requested when it is already in use - * by another application. - * - * @author Kara Kytle - */ - public class LineUnavailableException extends Exception { + private static final long serialVersionUID = -2046718279487432130L; /** - * Constructs a LineUnavailableException that has - * null as its error detail message. + * Constructs a {@code LineUnavailableException} that has {@code null} as + * its error detail message. */ public LineUnavailableException() { - super(); } /** - * Constructs a LineUnavailableException that has - * the specified detail message. + * Constructs a {@code LineUnavailableException} that has the specified + * detail message. * - * @param message a string containing the error detail message + * @param message a string containing the error detail message */ - public LineUnavailableException(String message) { - + public LineUnavailableException(final String message) { super(message); } } diff --git a/jdk/src/share/classes/javax/sound/sampled/Mixer.java b/jdk/src/share/classes/javax/sound/sampled/Mixer.java index 755ab913342..87784ec62f1 100644 --- a/jdk/src/share/classes/javax/sound/sampled/Mixer.java +++ b/jdk/src/share/classes/javax/sound/sampled/Mixer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,30 +25,27 @@ package javax.sound.sampled; - /** - * A mixer is an audio device with one or more lines. It need not be - * designed for mixing audio signals. A mixer that actually mixes audio - * has multiple input (source) lines and at least one output (target) line. - * The former are often instances of classes that implement - * {@link SourceDataLine}, - * and the latter, {@link TargetDataLine}. {@link Port} - * objects, too, are either source lines or target lines. - * A mixer can accept prerecorded, loopable sound as input, by having - * some of its source lines be instances of objects that implement the - * {@link Clip} interface. + * A mixer is an audio device with one or more lines. It need not be designed + * for mixing audio signals. A mixer that actually mixes audio has multiple + * input (source) lines and at least one output (target) line. The former are + * often instances of classes that implement {@link SourceDataLine}, and the + * latter, {@link TargetDataLine}. {@link Port} objects, too, are either source + * lines or target lines. A mixer can accept prerecorded, loopable sound as + * input, by having some of its source lines be instances of objects that + * implement the {@link Clip} interface. *

    - * Through methods of the Line interface, which Mixer extends, - * a mixer might provide a set of controls that are global to the mixer. For example, - * the mixer can have a master gain control. These global controls are distinct - * from the controls belonging to each of the mixer's individual lines. + * Through methods of the {@code Line} interface, which {@code Mixer} extends, a + * mixer might provide a set of controls that are global to the mixer. For + * example, the mixer can have a master gain control. These global controls are + * distinct from the controls belonging to each of the mixer's individual lines. *

    - * Some mixers, especially - * those with internal digital mixing capabilities, may provide - * additional capabilities by implementing the DataLine interface. + * Some mixers, especially those with internal digital mixing capabilities, may + * provide additional capabilities by implementing the {@code DataLine} + * interface. *

    - * A mixer can support synchronization of its lines. When one line in - * a synchronized group is started or stopped, the other lines in the group + * A mixer can support synchronization of its lines. When one line in a + * synchronized group is started or stopped, the other lines in the group * automatically start or stop simultaneously with the explicitly affected one. * * @author Kara Kytle @@ -59,198 +56,201 @@ public interface Mixer extends Line { /** * Obtains information about this mixer, including the product's name, * version, vendor, etc. + * * @return a mixer info object that describes this mixer * @see Mixer.Info */ - public Info getMixerInfo(); - + Info getMixerInfo(); /** - * Obtains information about the set of source lines supported - * by this mixer. - * Some source lines may only be available when this mixer is open. - * @return array of Line.Info objects representing source lines - * for this mixer. If no source lines are supported, - * an array of length 0 is returned. + * Obtains information about the set of source lines supported by this + * mixer. Some source lines may only be available when this mixer is open. + * + * @return array of {@code Line.Info} objects representing source lines for + * this mixer. If no source lines are supported, an array of length + * 0 is returned. */ - public Line.Info[] getSourceLineInfo(); + Line.Info[] getSourceLineInfo(); /** - * Obtains information about the set of target lines supported - * by this mixer. - * Some target lines may only be available when this mixer is open. - * @return array of Line.Info objects representing target lines - * for this mixer. If no target lines are supported, - * an array of length 0 is returned. + * Obtains information about the set of target lines supported by this + * mixer. Some target lines may only be available when this mixer is open. + * + * @return array of {@code Line.Info} objects representing target lines for + * this mixer. If no target lines are supported, an array of length + * 0 is returned. */ - public Line.Info[] getTargetLineInfo(); - + Line.Info[] getTargetLineInfo(); /** - * Obtains information about source lines of a particular type supported - * by the mixer. - * Some source lines may only be available when this mixer is open. - * @param info a Line.Info object describing lines about which information - * is queried - * @return an array of Line.Info objects describing source lines matching - * the type requested. If no matching source lines are supported, an array of length 0 - * is returned. + * Obtains information about source lines of a particular type supported by + * the mixer. Some source lines may only be available when this mixer is + * open. + * + * @param info a {@code Line.Info} object describing lines about which + * information is queried + * @return an array of {@code Line.Info} objects describing source lines + * matching the type requested. If no matching source lines are + * supported, an array of length 0 is returned. */ - public Line.Info[] getSourceLineInfo(Line.Info info); - + Line.Info[] getSourceLineInfo(Line.Info info); /** - * Obtains information about target lines of a particular type supported - * by the mixer. - * Some target lines may only be available when this mixer is open. - * @param info a Line.Info object describing lines about which information - * is queried - * @return an array of Line.Info objects describing target lines matching - * the type requested. If no matching target lines are supported, an array of length 0 - * is returned. + * Obtains information about target lines of a particular type supported by + * the mixer. Some target lines may only be available when this mixer is + * open. + * + * @param info a {@code Line.Info} object describing lines about which + * information is queried + * @return an array of {@code Line.Info} objects describing target lines + * matching the type requested. If no matching target lines are + * supported, an array of length 0 is returned. */ - public Line.Info[] getTargetLineInfo(Line.Info info); - + Line.Info[] getTargetLineInfo(Line.Info info); /** - * Indicates whether the mixer supports a line (or lines) that match - * the specified Line.Info object. - * Some lines may only be supported when this mixer is open. - * @param info describes the line for which support is queried - * @return true if at least one matching line is - * supported, false otherwise + * Indicates whether the mixer supports a line (or lines) that match the + * specified {@code Line.Info} object. Some lines may only be supported when + * this mixer is open. + * + * @param info describes the line for which support is queried + * @return {@code true} if at least one matching line is supported, + * {@code false} otherwise */ - public boolean isLineSupported(Line.Info info); + boolean isLineSupported(Line.Info info); /** * Obtains a line that is available for use and that matches the description - * in the specified Line.Info object. + * in the specified {@code Line.Info} object. + *

    + * If a {@code DataLine} is requested, and {@code info} is an instance of + * {@code DataLine.Info} specifying at least one fully qualified audio + * format, the last one will be used as the default format of the returned + * {@code DataLine}. * - *

    If a DataLine is requested, and info - * is an instance of DataLine.Info specifying at - * least one fully qualified audio format, the last one - * will be used as the default format of the returned - * DataLine. - * - * @param info describes the desired line + * @param info describes the desired line * @return a line that is available for use and that matches the description - * in the specified {@code Line.Info} object - * @throws LineUnavailableException if a matching line - * is not available due to resource restrictions - * @throws IllegalArgumentException if this mixer does - * not support any lines matching the description - * @throws SecurityException if a matching line - * is not available due to security restrictions + * in the specified {@code Line.Info} object + * @throws LineUnavailableException if a matching line is not available due + * to resource restrictions + * @throws IllegalArgumentException if this mixer does not support any lines + * matching the description + * @throws SecurityException if a matching line is not available due to + * security restrictions */ - public Line getLine(Line.Info info) throws LineUnavailableException; + Line getLine(Line.Info info) throws LineUnavailableException; //$$fb 2002-04-12: fix for 4667258: behavior of Mixer.getMaxLines(Line.Info) method doesn't match the spec /** - * Obtains the approximate maximum number of lines of the requested type that can be open - * simultaneously on the mixer. + * Obtains the approximate maximum number of lines of the requested type + * that can be open simultaneously on the mixer. * - * Certain types of mixers do not have a hard bound and may allow opening more lines. - * Since certain lines are a shared resource, a mixer may not be able to open the maximum - * number of lines if another process has opened lines of this mixer. + * Certain types of mixers do not have a hard bound and may allow opening + * more lines. Since certain lines are a shared resource, a mixer may not be + * able to open the maximum number of lines if another process has opened + * lines of this mixer. * - * The requested type is any line that matches the description in - * the provided Line.Info object. For example, if the info - * object represents a speaker - * port, and the mixer supports exactly one speaker port, this method - * should return 1. If the info object represents a source data line - * and the mixer supports the use of 32 source data lines simultaneously, - * the return value should be 32. - * If there is no limit, this function returns AudioSystem.NOT_SPECIFIED. - * @param info a Line.Info that describes the line for which - * the number of supported instances is queried - * @return the maximum number of matching lines supported, or AudioSystem.NOT_SPECIFIED + * The requested type is any line that matches the description in the + * provided {@code Line.Info} object. For example, if the info object + * represents a speaker port, and the mixer supports exactly one speaker + * port, this method should return 1. If the info object represents a + * source data line and the mixer supports the use of 32 source data lines + * simultaneously, the return value should be 32. If there is no limit, this + * function returns {@code AudioSystem.NOT_SPECIFIED}. + * + * @param info a {@code Line.Info} that describes the line for which the + * number of supported instances is queried + * @return the maximum number of matching lines supported, or + * {@code AudioSystem.NOT_SPECIFIED} */ - public int getMaxLines(Line.Info info); - + int getMaxLines(Line.Info info); /** * Obtains the set of all source lines currently open to this mixer. * - * @return the source lines currently open to the mixer. - * If no source lines are currently open to this mixer, an - * array of length 0 is returned. - * @throws SecurityException if the matching lines - * are not available due to security restrictions + * @return the source lines currently open to the mixer. If no source lines + * are currently open to this mixer, an array of length 0 is + * returned. + * @throws SecurityException if the matching lines are not available due to + * security restrictions */ - public Line[] getSourceLines(); + Line[] getSourceLines(); /** * Obtains the set of all target lines currently open from this mixer. * - * @return target lines currently open from the mixer. - * If no target lines are currently open from this mixer, an - * array of length 0 is returned. - * @throws SecurityException if the matching lines - * are not available due to security restrictions + * @return target lines currently open from the mixer. If no target lines + * are currently open from this mixer, an array of length 0 is + * returned. + * @throws SecurityException if the matching lines are not available due to + * security restrictions */ - public Line[] getTargetLines(); + Line[] getTargetLines(); /** - * Synchronizes two or more lines. Any subsequent command that starts or stops - * audio playback or capture for one of these lines will exert the - * same effect on the other lines in the group, so that they start or stop playing or - * capturing data simultaneously. - * - * @param lines the lines that should be synchronized - * @param maintainSync true if the synchronization - * must be precisely maintained (i.e., the synchronization must be sample-accurate) - * at all times during operation of the lines , or false - * if precise synchronization is required only during start and stop operations + * Synchronizes two or more lines. Any subsequent command that starts or + * stops audio playback or capture for one of these lines will exert the + * same effect on the other lines in the group, so that they start or stop + * playing or capturing data simultaneously. * + * @param lines the lines that should be synchronized + * @param maintainSync {@code true} if the synchronization must be + * precisely maintained (i.e., the synchronization must be + * sample-accurate) at all times during operation of the lines, or + * {@code false} if precise synchronization is required only during + * start and stop operations * @throws IllegalArgumentException if the lines cannot be synchronized. - * This may occur if the lines are of different types or have different - * formats for which this mixer does not support synchronization, or if - * all lines specified do not belong to this mixer. + * This may occur if the lines are of different types or have + * different formats for which this mixer does not support + * synchronization, or if all lines specified do not belong to this + * mixer. */ - public void synchronize(Line[] lines, boolean maintainSync); + void synchronize(Line[] lines, boolean maintainSync); /** - * Releases synchronization for the specified lines. The array must - * be identical to one for which synchronization has already been - * established; otherwise an exception may be thrown. However, null - * may be specified, in which case all currently synchronized lines that belong - * to this mixer are unsynchronized. - * @param lines the synchronized lines for which synchronization should be - * released, or null for all this mixer's synchronized lines + * Releases synchronization for the specified lines. The array must be + * identical to one for which synchronization has already been established; + * otherwise an exception may be thrown. However, {@code null} may be + * specified, in which case all currently synchronized lines that belong to + * this mixer are unsynchronized. * + * @param lines the synchronized lines for which synchronization should be + * released, or {@code null} for all this mixer's synchronized + * lines * @throws IllegalArgumentException if the lines cannot be unsynchronized. - * This may occur if the argument specified does not exactly match a set - * of lines for which synchronization has already been established. + * This may occur if the argument specified does not exactly match + * a set of lines for which synchronization has already been + * established. */ - public void unsynchronize(Line[] lines); - + void unsynchronize(Line[] lines); /** - * Reports whether this mixer supports synchronization of the specified set of lines. + * Reports whether this mixer supports synchronization of the specified set + * of lines. * - * @param lines the set of lines for which synchronization support is queried - * @param maintainSync true if the synchronization - * must be precisely maintained (i.e., the synchronization must be sample-accurate) - * at all times during operation of the lines , or false - * if precise synchronization is required only during start and stop operations - * - * @return true if the lines can be synchronized, false - * otherwise + * @param lines the set of lines for which synchronization support is + * queried + * @param maintainSync {@code true} if the synchronization must be + * precisely maintained (i.e., the synchronization must be + * sample-accurate) at all times during operation of the lines, or + * {@code false} if precise synchronization is required only during + * start and stop operations + * @return {@code true} if the lines can be synchronized, {@code false} + * otherwise */ - public boolean isSynchronizationSupported(Line[] lines, boolean maintainSync); - + boolean isSynchronizationSupported(Line[] lines, boolean maintainSync); /** - * The Mixer.Info class represents information about an audio mixer, + * The {@code Mixer.Info} class represents information about an audio mixer, * including the product's name, version, and vendor, along with a textual - * description. This information may be retrieved through the - * {@link Mixer#getMixerInfo() getMixerInfo} - * method of the Mixer interface. + * description. This information may be retrieved through the + * {@link Mixer#getMixerInfo() getMixerInfo} method of the {@code Mixer} + * interface. * * @author Kara Kytle * @since 1.3 */ - public static class Info { + class Info { /** * Mixer name. @@ -273,13 +273,14 @@ public interface Mixer extends Line { private final String version; /** - * Constructs a mixer's info object, passing it the given - * textual information. - * @param name the name of the mixer - * @param vendor the company who manufactures or creates the hardware - * or software mixer - * @param description descriptive text about the mixer - * @param version version information for the mixer + * Constructs a mixer's info object, passing it the given textual + * information. + * + * @param name the name of the mixer + * @param vendor the company who manufactures or creates the + * hardware or software mixer + * @param description descriptive text about the mixer + * @param version version information for the mixer */ protected Info(String name, String vendor, String description, String version) { @@ -289,15 +290,16 @@ public interface Mixer extends Line { this.version = version; } - /** - * Indicates whether two info objects are equal, returning true if - * they are identical. - * @param obj the reference object with which to compare this info - * object - * @return true if this info object is the same as the - * obj argument; false otherwise + * Indicates whether two info objects are equal, returning {@code true} + * if they are identical. + * + * @param obj the reference object with which to compare this info + * object + * @return {@code true} if this info object is the same as the + * {@code obj} argument; {@code false} otherwise */ + @Override public final boolean equals(Object obj) { return super.equals(obj); } @@ -307,12 +309,14 @@ public interface Mixer extends Line { * * @return the hashcode for this object */ + @Override public final int hashCode() { return super.hashCode(); } /** * Obtains the name of the mixer. + * * @return a string that names the mixer */ public final String getName() { @@ -321,6 +325,7 @@ public interface Mixer extends Line { /** * Obtains the vendor of the mixer. + * * @return a string that names the mixer's vendor */ public final String getVendor() { @@ -329,6 +334,7 @@ public interface Mixer extends Line { /** * Obtains the description of the mixer. + * * @return a textual description of the mixer */ public final String getDescription() { @@ -337,6 +343,7 @@ public interface Mixer extends Line { /** * Obtains the version of the mixer. + * * @return textual version information for the mixer */ public final String getVersion() { @@ -345,10 +352,12 @@ public interface Mixer extends Line { /** * Provides a string representation of the mixer info. + * * @return a string describing the info object */ + @Override public final String toString() { return (name + ", version " + version); } - } // class Info + } } diff --git a/jdk/src/share/classes/javax/sound/sampled/Port.java b/jdk/src/share/classes/javax/sound/sampled/Port.java index 04b67a8fa3e..61f40c761a5 100644 --- a/jdk/src/share/classes/javax/sound/sampled/Port.java +++ b/jdk/src/share/classes/javax/sound/sampled/Port.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,41 +25,36 @@ package javax.sound.sampled; - /** * Ports are simple lines for input or output of audio to or from audio devices. - * Common examples of ports that act as source lines (mixer inputs) include the microphone, - * line input, and CD-ROM drive. Ports that act as target lines (mixer outputs) include the - * speaker, headphone, and line output. You can access port using a {@link Port.Info} - * object. + * Common examples of ports that act as source lines (mixer inputs) include the + * microphone, line input, and CD-ROM drive. Ports that act as target lines + * (mixer outputs) include the speaker, headphone, and line output. You can + * access port using a {@link Port.Info} object. * * @author Kara Kytle * @since 1.3 */ public interface Port extends Line { - - // INNER CLASSES - - /** - * The Port.Info class extends {@link Line.Info} - * with additional information specific to ports, including the port's name - * and whether it is a source or a target for its mixer. - * By definition, a port acts as either a source or a target to its mixer, - * but not both. (Audio input ports are sources; audio output ports are targets.) + * The {@code Port.Info} class extends {@code Line.Info} with additional + * information specific to ports, including the port's name and whether it + * is a source or a target for its mixer. By definition, a port acts as + * either a source or a target to its mixer, but not both. (Audio input + * ports are sources; audio output ports are targets.) *

    - * To learn what ports are available, you can retrieve port info objects through the - * {@link Mixer#getSourceLineInfo getSourceLineInfo} and - * {@link Mixer#getTargetLineInfo getTargetLineInfo} - * methods of the Mixer interface. Instances of the - * Port.Info class may also be constructed and used to obtain - * lines matching the parameters specified in the Port.Info object. + * To learn what ports are available, you can retrieve port info objects + * through the {@link Mixer#getSourceLineInfo getSourceLineInfo} and + * {@link Mixer#getTargetLineInfo getTargetLineInfo} methods of the + * {@code Mixer} interface. Instances of the {@code Port.Info} class may + * also be constructed and used to obtain lines matching the parameters + * specified in the {@code Port.Info} object. * * @author Kara Kytle * @since 1.3 */ - public static class Info extends Line.Info { + class Info extends Line.Info { // AUDIO PORT TYPE DEFINES @@ -68,7 +63,8 @@ public interface Port extends Line { // SOURCE PORTS /** - * A type of port that gets audio from a built-in microphone or a microphone jack. + * A type of port that gets audio from a built-in microphone or a + * microphone jack. */ public static final Info MICROPHONE = new Info(Port.class,"MICROPHONE", true); @@ -86,7 +82,8 @@ public interface Port extends Line { // TARGET PORTS /** - * A type of port that sends audio to a built-in speaker or a speaker jack. + * A type of port that sends audio to a built-in speaker or a speaker + * jack. */ public static final Info SPEAKER = new Info(Port.class,"SPEAKER", false); @@ -113,19 +110,16 @@ public interface Port extends Line { private String name; private boolean isSource; - - // CONSTRUCTOR - /** - * Constructs a port's info object from the information given. - * This constructor is typically used by an implementation - * of Java Sound to describe a supported line. + * Constructs a port's info object from the information given. This + * constructor is typically used by an implementation of Java Sound to + * describe a supported line. * - * @param lineClass the class of the port described by the info object. - * @param name the string that names the port - * @param isSource true if the port is a source port (such - * as a microphone), false if the port is a target port - * (such as a speaker). + * @param lineClass the class of the port described by the info object + * @param name the string that names the port + * @param isSource {@code true} if the port is a source port (such as a + * microphone), {@code false} if the port is a target port + * (such as a speaker) */ public Info(Class lineClass, String name, boolean isSource) { @@ -134,11 +128,9 @@ public interface Port extends Line { this.isSource = isSource; } - - // METHODS - /** * Obtains the name of the port. + * * @return the string that names the port */ public String getName() { @@ -147,20 +139,23 @@ public interface Port extends Line { /** * Indicates whether the port is a source or a target for its mixer. - * @return true if the port is a source port (such - * as a microphone), false if the port is a target port - * (such as a speaker). + * + * @return {@code true} if the port is a source port (such as a + * microphone), {@code false} if the port is a target port + * (such as a speaker) */ public boolean isSource() { return isSource; } /** - * Indicates whether this info object specified matches this one. - * To match, the match requirements of the superclass must be - * met and the types must be equal. - * @param info the info object for which the match is queried + * Indicates whether this info object specified matches this one. To + * match, the match requirements of the superclass must be met and the + * types must be equal. + * + * @param info the info object for which the match is queried */ + @Override public boolean matches(Line.Info info) { if (! (super.matches(info)) ) { @@ -178,31 +173,30 @@ public interface Port extends Line { return true; } - /** - * Finalizes the equals method + * Finalizes the equals method. */ + @Override public final boolean equals(Object obj) { return super.equals(obj); } /** - * Finalizes the hashCode method + * Finalizes the hashCode method. */ + @Override public final int hashCode() { return super.hashCode(); } - - /** - * Provides a String representation - * of the port. - * @return a string that describes the port + * Provides a {@code String} representation of the port. + * + * @return a string that describes the port */ + @Override public final String toString() { return (name + ((isSource == true) ? " source" : " target") + " port"); } - - } // class Info + } } diff --git a/jdk/src/share/classes/javax/sound/sampled/ReverbType.java b/jdk/src/share/classes/javax/sound/sampled/ReverbType.java index 7afd7aefe56..e308b0f9402 100644 --- a/jdk/src/share/classes/javax/sound/sampled/ReverbType.java +++ b/jdk/src/share/classes/javax/sound/sampled/ReverbType.java @@ -25,46 +25,41 @@ package javax.sound.sampled; - /** - * The ReverbType class provides methods for - * accessing various reverberation settings to be applied to - * an audio signal. + * The {@code ReverbType} class provides methods for accessing various + * reverberation settings to be applied to an audio signal. *

    - * Reverberation simulates the reflection of sound off of - * the walls, ceiling, and floor of a room. Depending on - * the size of the room, and how absorbent or reflective the materials in the - * room's surfaces are, the sound might bounce around for a - * long time before dying away. + * Reverberation simulates the reflection of sound off of the walls, ceiling, + * and floor of a room. Depending on the size of the room, and how absorbent or + * reflective the materials in the room's surfaces are, the sound might bounce + * around for a long time before dying away. *

    - * The reverberation parameters provided by ReverbType consist - * of the delay time and intensity of early reflections, the delay time and - * intensity of late reflections, and an overall decay time. - * Early reflections are the initial individual low-order reflections of the - * direct signal off the surfaces in the room. - * The late Reflections are the dense, high-order reflections that characterize - * the room's reverberation. - * The delay times for the start of these two reflection types give the listener - * a sense of the overall size and complexity of the room's shape and contents. - * The larger the room, the longer the reflection delay times. - * The early and late reflections' intensities define the gain (in decibels) of the reflected - * signals as compared to the direct signal. These intensities give the - * listener an impression of the absorptive nature of the surfaces and objects - * in the room. + * The reverberation parameters provided by {@code ReverbType} consist of the + * delay time and intensity of early reflections, the delay time and intensity + * of late reflections, and an overall decay time. Early reflections are the + * initial individual low-order reflections of the direct signal off the + * surfaces in the room. The late Reflections are the dense, high-order + * reflections that characterize the room's reverberation. The delay times for + * the start of these two reflection types give the listener a sense of the + * overall size and complexity of the room's shape and contents. The larger the + * room, the longer the reflection delay times. The early and late reflections' + * intensities define the gain (in decibels) of the reflected signals as + * compared to the direct signal. These intensities give the listener an + * impression of the absorptive nature of the surfaces and objects in the room. * The decay time defines how long the reverberation takes to exponentially - * decay until it is no longer perceptible ("effective zero"). - * The larger and less absorbent the surfaces, the longer the decay time. + * decay until it is no longer perceptible ("effective zero"). The larger and + * less absorbent the surfaces, the longer the decay time. *

    - * The set of parameters defined here may not include all aspects of reverberation - * as specified by some systems. For example, the Midi Manufacturer's Association - * (MMA) has an Interactive Audio Special Interest Group (IASIG), which has a - * 3-D Working Group that has defined a Level 2 Spec (I3DL2). I3DL2 - * supports filtering of reverberation and - * control of reverb density. These properties are not included in the JavaSound 1.0 - * definition of a reverb control. In such a case, the implementing system - * should either extend the defined reverb control to include additional - * parameters, or else interpret the system's additional capabilities in a way that fits - * the model described here. + * The set of parameters defined here may not include all aspects of + * reverberation as specified by some systems. For example, the Midi + * Manufacturer's Association (MMA) has an Interactive Audio Special Interest + * Group (IASIG), which has a 3-D Working Group that has defined a Level 2 Spec + * (I3DL2). I3DL2 supports filtering of reverberation and control of reverb + * density. These properties are not included in the JavaSound 1.0 definition of + * a reverb control. In such a case, the implementing system should either + * extend the defined reverb control to include additional parameters, or else + * interpret the system's additional capabilities in a way that fits the model + * described here. *

    * If implementing JavaSound on a I3DL2-compliant device: *

      @@ -72,8 +67,8 @@ package javax.sound.sampled; *
    • Density parameters are set to midway between minimum and maximum *
    *

    - * The following table shows what parameter values an implementation might use for a - * representative set of reverberation settings. + * The following table shows what parameter values an implementation might use + * for a representative set of reverberation settings. *

    * * Reverberation Types and Parameters @@ -142,7 +137,7 @@ package javax.sound.sampled; public class ReverbType { /** - * Descriptive name of the reverb type.. + * Descriptive name of the reverb type. */ private String name; @@ -167,20 +162,25 @@ public class ReverbType { private float lateReflectionIntensity; /** - * Total decay time + * Total decay time. */ private int decayTime; - /** * Constructs a new reverb type that has the specified reverberation * parameter values. - * @param name the name of the new reverb type, or a zero-length String - * @param earlyReflectionDelay the new type's early reflection delay time in microseconds - * @param earlyReflectionIntensity the new type's early reflection intensity in dB - * @param lateReflectionDelay the new type's late reflection delay time in microseconds - * @param lateReflectionIntensity the new type's late reflection intensity in dB - * @param decayTime the new type's decay time in microseconds + * + * @param name the name of the new reverb type, or a zero-length + * {@code String} + * @param earlyReflectionDelay the new type's early reflection delay time + * in microseconds + * @param earlyReflectionIntensity the new type's early reflection + * intensity in dB + * @param lateReflectionDelay the new type's late reflection delay time in + * microseconds + * @param lateReflectionIntensity the new type's late reflection intensity + * in dB + * @param decayTime the new type's decay time in microseconds */ protected ReverbType(String name, int earlyReflectionDelay, float earlyReflectionIntensity, int lateReflectionDelay, float lateReflectionIntensity, int decayTime) { @@ -192,9 +192,9 @@ public class ReverbType { this.decayTime = decayTime; } - /** * Obtains the name of this reverb type. + * * @return the name of this reverb type * @since 1.5 */ @@ -202,89 +202,88 @@ public class ReverbType { return name; } - /** - * Returns the early reflection delay time in microseconds. - * This is the amount of time between when the direct signal is - * heard and when the first early reflections are heard. - * @return early reflection delay time for this reverb type, in microseconds + * Returns the early reflection delay time in microseconds. This is the + * amount of time between when the direct signal is heard and when the first + * early reflections are heard. + * + * @return early reflection delay time for this reverb type, in microseconds */ public final int getEarlyReflectionDelay() { return earlyReflectionDelay; } - /** - * Returns the early reflection intensity in decibels. - * This is the amplitude attenuation of the first early reflections - * relative to the direct signal. - * @return early reflection intensity for this reverb type, in dB + * Returns the early reflection intensity in decibels. This is the amplitude + * attenuation of the first early reflections relative to the direct signal. + * + * @return early reflection intensity for this reverb type, in dB */ public final float getEarlyReflectionIntensity() { return earlyReflectionIntensity; } - /** - * Returns the late reflection delay time in microseconds. - * This is the amount of time between when the first early reflections - * are heard and when the first late reflections are heard. - * @return late reflection delay time for this reverb type, in microseconds + * Returns the late reflection delay time in microseconds. This is the + * amount of time between when the first early reflections are heard and + * when the first late reflections are heard. + * + * @return late reflection delay time for this reverb type, in microseconds */ public final int getLateReflectionDelay() { return lateReflectionDelay; } - /** - * Returns the late reflection intensity in decibels. - * This is the amplitude attenuation of the first late reflections - * relative to the direct signal. - * @return late reflection intensity for this reverb type, in dB + * Returns the late reflection intensity in decibels. This is the amplitude + * attenuation of the first late reflections relative to the direct signal. + * + * @return late reflection intensity for this reverb type, in dB */ public final float getLateReflectionIntensity() { return lateReflectionIntensity; } - /** - * Obtains the decay time, which is the amount of time over which the - * late reflections attenuate to effective zero. The effective zero - * value is implementation-dependent. - * @return the decay time of the late reflections, in microseconds + * Obtains the decay time, which is the amount of time over which the late + * reflections attenuate to effective zero. The effective zero value is + * implementation-dependent. + * + * @return the decay time of the late reflections, in microseconds */ public final int getDecayTime() { return decayTime; } - /** * Indicates whether the specified object is equal to this reverb type, - * returning true if the objects are identical. - * @param obj the reference object with which to compare - * @return true if this reverb type is the same as - * obj; false otherwise + * returning {@code true} if the objects are identical. + * + * @param obj the reference object with which to compare + * @return {@code true} if this reverb type is the same as {@code obj}; + * {@code false} otherwise */ + @Override public final boolean equals(Object obj) { return super.equals(obj); } - /** * Finalizes the hashcode method. */ + @Override public final int hashCode() { return super.hashCode(); } - /** - * Provides a String representation of the reverb type, - * including its name and its parameter settings. - * The exact contents of the string may vary between implementations of - * Java Sound. + * Provides a {@code String} representation of the reverb type, including + * its name and its parameter settings. The exact contents of the string may + * vary between implementations of Java Sound. + * * @return reverberation type name and description */ + @Override public final String toString() { //$$fb2001-07-20: fix for bug 4385060: The "name" attribute of class "ReverbType" is not accessible. @@ -295,5 +294,4 @@ public class ReverbType { " ns, late reflection intensity " + lateReflectionIntensity + " dB, decay time " + decayTime); } - -} // class ReverbType +} diff --git a/jdk/src/share/classes/javax/sound/sampled/SourceDataLine.java b/jdk/src/share/classes/javax/sound/sampled/SourceDataLine.java index 5cfbccf2ccd..7749b3a86fc 100644 --- a/jdk/src/share/classes/javax/sound/sampled/SourceDataLine.java +++ b/jdk/src/share/classes/javax/sound/sampled/SourceDataLine.java @@ -25,36 +25,35 @@ package javax.sound.sampled; - /** - * A source data line is a data line to which data may be written. It acts as - * a source to its mixer. An application writes audio bytes to a source data line, - * which handles the buffering of the bytes and delivers them to the mixer. - * The mixer may mix the samples with those from other sources and then deliver - * the mix to a target such as an output port (which may represent an audio output + * A source data line is a data line to which data may be written. It acts as a + * source to its mixer. An application writes audio bytes to a source data line, + * which handles the buffering of the bytes and delivers them to the mixer. The + * mixer may mix the samples with those from other sources and then deliver the + * mix to a target such as an output port (which may represent an audio output * device on a sound card). *

    * Note that the naming convention for this interface reflects the relationship - * between the line and its mixer. From the perspective of an application, - * a source data line may act as a target for audio data. + * between the line and its mixer. From the perspective of an application, a + * source data line may act as a target for audio data. *

    * A source data line can be obtained from a mixer by invoking the - * {@link Mixer#getLine getLine} method of Mixer with - * an appropriate {@link DataLine.Info} object. + * {@link Mixer#getLine getLine} method of {@code Mixer} with an appropriate + * {@link DataLine.Info} object. *

    - * The SourceDataLine interface provides a method for writing - * audio data to the data line's buffer. Applications that play or mix - * audio should write data to the source data line quickly enough to keep the - * buffer from underflowing (emptying), which could cause discontinuities in - * the audio that are perceived as clicks. Applications can use the - * {@link DataLine#available available} method defined in the - * DataLine interface to determine the amount of data currently - * queued in the data line's buffer. The amount of data which can be written - * to the buffer without blocking is the difference between the buffer size - * and the amount of queued data. If the delivery of audio output - * stops due to underflow, a {@link LineEvent.Type#STOP STOP} event is - * generated. A {@link LineEvent.Type#START START} event is generated - * when the audio output resumes. + * The {@code SourceDataLine} interface provides a method for writing audio data + * to the data line's buffer. Applications that play or mix audio should write + * data to the source data line quickly enough to keep the buffer from + * underflowing (emptying), which could cause discontinuities in the audio that + * are perceived as clicks. Applications can use the + * {@link DataLine#available available} method defined in the {@code DataLine} + * interface to determine the amount of data currently queued in the data line's + * buffer. The amount of data which can be written to the buffer without + * blocking is the difference between the buffer size and the amount of queued + * data. If the delivery of audio output stops due to underflow, a + * {@link LineEvent.Type#STOP STOP} event is generated. A + * {@link LineEvent.Type#START START} event is generated when the audio output + * resumes. * * @author Kara Kytle * @see Mixer @@ -64,138 +63,130 @@ package javax.sound.sampled; */ public interface SourceDataLine extends DataLine { - /** * Opens the line with the specified format and suggested buffer size, - * causing the line to acquire any required - * system resources and become operational. + * causing the line to acquire any required system resources and become + * operational. *

    * The buffer size is specified in bytes, but must represent an integral - * number of sample frames. Invoking this method with a requested buffer + * number of sample frames. Invoking this method with a requested buffer * size that does not meet this requirement may result in an - * IllegalArgumentException. The actual buffer size for the open line may - * differ from the requested buffer size. The value actually set may be - * queried by subsequently calling {@link DataLine#getBufferSize}. + * {@code IllegalArgumentException}. The actual buffer size for the open + * line may differ from the requested buffer size. The value actually set + * may be queried by subsequently calling {@link DataLine#getBufferSize}. *

    * If this operation succeeds, the line is marked as open, and an - * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the - * line's listeners. + * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the line's + * listeners. *

    - * Invoking this method on a line which is already open is illegal - * and may result in an IllegalStateException. + * Invoking this method on a line which is already open is illegal and may + * result in an {@code IllegalStateException}. *

    - * Note that some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in a - * LineUnavailableException. + * Note that some lines, once closed, cannot be reopened. Attempts to reopen + * such a line will always result in a {@code LineUnavailableException}. * - * @param format the desired audio format - * @param bufferSize the desired buffer size - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions - * @throws IllegalArgumentException if the buffer size does not represent - * an integral number of sample frames, - * or if format is not fully specified or invalid + * @param format the desired audio format + * @param bufferSize the desired buffer size + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws IllegalArgumentException if the buffer size does not represent an + * integral number of sample frames, or if {@code format} is not + * fully specified or invalid * @throws IllegalStateException if the line is already open - * @throws SecurityException if the line cannot be - * opened due to security restrictions - * + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #open(AudioFormat) * @see Line#open * @see Line#close * @see Line#isOpen * @see LineEvent */ - public void open(AudioFormat format, int bufferSize) throws LineUnavailableException; - + void open(AudioFormat format, int bufferSize) + throws LineUnavailableException; /** * Opens the line with the specified format, causing the line to acquire any * required system resources and become operational. - * *

    * The implementation chooses a buffer size, which is measured in bytes but - * which encompasses an integral number of sample frames. The buffer size + * which encompasses an integral number of sample frames. The buffer size * that the system has chosen may be queried by subsequently calling - * {@link DataLine#getBufferSize}. + * {@link DataLine#getBufferSize}. *

    * If this operation succeeds, the line is marked as open, and an - * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the - * line's listeners. + * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the line's + * listeners. *

    - * Invoking this method on a line which is already open is illegal - * and may result in an IllegalStateException. + * Invoking this method on a line which is already open is illegal and may + * result in an {@code IllegalStateException}. *

    - * Note that some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in a - * LineUnavailableException. + * Note that some lines, once closed, cannot be reopened. Attempts to reopen + * such a line will always result in a {@code LineUnavailableException}. * - * @param format the desired audio format - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions - * @throws IllegalArgumentException if format - * is not fully specified or invalid + * @param format the desired audio format + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws IllegalArgumentException if {@code format} is not fully specified + * or invalid * @throws IllegalStateException if the line is already open - * @throws SecurityException if the line cannot be - * opened due to security restrictions - * + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #open(AudioFormat, int) * @see Line#open * @see Line#close * @see Line#isOpen * @see LineEvent */ - public void open(AudioFormat format) throws LineUnavailableException; - + void open(AudioFormat format) throws LineUnavailableException; /** - * Writes audio data to the mixer via this source data line. The requested - * number of bytes of data are read from the specified array, - * starting at the given offset into the array, and written to the data - * line's buffer. If the caller attempts to write more data than can - * currently be written (see {@link DataLine#available available}), - * this method blocks until the requested amount of data has been written. - * This applies even if the requested amount of data to write is greater - * than the data line's buffer size. However, if the data line is closed, - * stopped, or flushed before the requested amount has been written, - * the method no longer blocks, but returns the number of bytes - * written thus far. + * Writes audio data to the mixer via this source data line. The requested + * number of bytes of data are read from the specified array, starting at + * the given offset into the array, and written to the data line's buffer. + * If the caller attempts to write more data than can currently be written + * (see {@link DataLine#available available}), this method blocks until the + * requested amount of data has been written. This applies even if the + * requested amount of data to write is greater than the data line's buffer + * size. However, if the data line is closed, stopped, or flushed before the + * requested amount has been written, the method no longer blocks, but + * returns the number of bytes written thus far. *

    - * The number of bytes that can be written without blocking can be ascertained - * using the {@link DataLine#available available} method of the - * DataLine interface. (While it is guaranteed that - * this number of bytes can be written without blocking, there is no guarantee - * that attempts to write additional data will block.) + * The number of bytes that can be written without blocking can be + * ascertained using the {@link DataLine#available available} method of the + * {@code DataLine} interface. (While it is guaranteed that this number of + * bytes can be written without blocking, there is no guarantee that + * attempts to write additional data will block.) *

    - * The number of bytes to write must represent an integral number of - * sample frames, such that: + * The number of bytes to write must represent an integral number of sample + * frames, such that: *
    - *

    [ bytes written ] % [frame size in bytes ] == 0
    + *
    {@code [ bytes written ] % [frame size in bytes ] == 0}
    *
    - * The return value will always meet this requirement. A request to write a - * number of bytes representing a non-integral number of sample frames cannot - * be fulfilled and may result in an IllegalArgumentException. + * The return value will always meet this requirement. A request to write a + * number of bytes representing a non-integral number of sample frames + * cannot be fulfilled and may result in an + * {@code IllegalArgumentException}. * - * @param b a byte array containing data to be written to the data line - * @param len the length, in bytes, of the valid data in the array - * (in other words, the requested amount of data to write, in bytes) - * @param off the offset from the beginning of the array, in bytes + * @param b a byte array containing data to be written to the data line + * @param len the length, in bytes, of the valid data in the array (in + * other words, the requested amount of data to write, in bytes) + * @param off the offset from the beginning of the array, in bytes * @return the number of bytes actually written * @throws IllegalArgumentException if the requested number of bytes does - * not represent an integral number of sample frames, - * or if len is negative - * @throws ArrayIndexOutOfBoundsException if off is negative, - * or off+len is greater than the length of the array - * b. - * + * not represent an integral number of sample frames, or if + * {@code len} is negative + * @throws ArrayIndexOutOfBoundsException if {@code off} is negative, or + * {@code off+len} is greater than the length of the array {@code b} * @see TargetDataLine#read * @see DataLine#available */ - public int write(byte[] b, int off, int len); + int write(byte[] b, int off, int len); /** * Obtains the number of sample frames of audio data that can be written to - * the mixer, via this data line, without blocking. Note that the return + * the mixer, via this data line, without blocking. Note that the return * value measures sample frames, not bytes. + * * @return the number of sample frames currently available for writing * @see TargetDataLine#availableRead */ diff --git a/jdk/src/share/classes/javax/sound/sampled/TargetDataLine.java b/jdk/src/share/classes/javax/sound/sampled/TargetDataLine.java index a6f14269240..acacdbcccae 100644 --- a/jdk/src/share/classes/javax/sound/sampled/TargetDataLine.java +++ b/jdk/src/share/classes/javax/sound/sampled/TargetDataLine.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,29 +26,28 @@ package javax.sound.sampled; /** - * A target data line is a type of {@link DataLine} from which - * audio data can be read. The most common example is a data line that gets - * its data from an audio capture device. (The device is implemented as a - * mixer that writes to the target data line.) + * A target data line is a type of {@link DataLine} from which audio data can be + * read. The most common example is a data line that gets its data from an audio + * capture device. (The device is implemented as a mixer that writes to the + * target data line.) *

    * Note that the naming convention for this interface reflects the relationship - * between the line and its mixer. From the perspective of an application, - * a target data line may act as a source for audio data. + * between the line and its mixer. From the perspective of an application, a + * target data line may act as a source for audio data. *

    * The target data line can be obtained from a mixer by invoking the - * {@link Mixer#getLine getLine} - * method of Mixer with an appropriate - * {@link DataLine.Info} object. + * {@link Mixer#getLine getLine} method of {@code Mixer} with an appropriate + * {@link DataLine.Info} object. *

    - * The TargetDataLine interface provides a method for reading the - * captured data from the target data line's buffer.Applications - * that record audio should read data from the target data line quickly enough - * to keep the buffer from overflowing, which could cause discontinuities in - * the captured data that are perceived as clicks. Applications can use the - * {@link DataLine#available available} method defined in the - * DataLine interface to determine the amount of data currently - * queued in the data line's buffer. If the buffer does overflow, - * the oldest queued data is discarded and replaced by new data. + * The {@code TargetDataLine} interface provides a method for reading the + * captured data from the target data line's buffer. Applications that record + * audio should read data from the target data line quickly enough to keep the + * buffer from overflowing, which could cause discontinuities in the captured + * data that are perceived as clicks. Applications can use the + * {@link DataLine#available available} method defined in the {@code DataLine} + * interface to determine the amount of data currently queued in the data line's + * buffer. If the buffer does overflow, the oldest queued data is discarded and + * replaced by new data. * * @author Kara Kytle * @see Mixer @@ -58,133 +57,126 @@ package javax.sound.sampled; */ public interface TargetDataLine extends DataLine { - /** * Opens the line with the specified format and requested buffer size, * causing the line to acquire any required system resources and become * operational. *

    * The buffer size is specified in bytes, but must represent an integral - * number of sample frames. Invoking this method with a requested buffer + * number of sample frames. Invoking this method with a requested buffer * size that does not meet this requirement may result in an - * IllegalArgumentException. The actual buffer size for the open line may - * differ from the requested buffer size. The value actually set may be - * queried by subsequently calling {@link DataLine#getBufferSize} + * {@code IllegalArgumentException}. The actual buffer size for the open + * line may differ from the requested buffer size. The value actually set + * may be queried by subsequently calling {@link DataLine#getBufferSize} *

    * If this operation succeeds, the line is marked as open, and an - * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the - * line's listeners. + * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the line's + * listeners. *

    - * Invoking this method on a line that is already open is illegal - * and may result in an IllegalStateException. + * Invoking this method on a line that is already open is illegal and may + * result in an {@code IllegalStateException}. *

    - * Some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in a - * LineUnavailableException. + * Some lines, once closed, cannot be reopened. Attempts to reopen such a + * line will always result in a {@code LineUnavailableException}. * - * @param format the desired audio format - * @param bufferSize the desired buffer size, in bytes. - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions - * @throws IllegalArgumentException if the buffer size does not represent - * an integral number of sample frames, - * or if format is not fully specified or invalid + * @param format the desired audio format + * @param bufferSize the desired buffer size, in bytes + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws IllegalArgumentException if the buffer size does not represent an + * integral number of sample frames, or if {@code format} is not + * fully specified or invalid * @throws IllegalStateException if the line is already open - * @throws SecurityException if the line cannot be - * opened due to security restrictions - * + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #open(AudioFormat) * @see Line#open * @see Line#close * @see Line#isOpen * @see LineEvent */ - public void open(AudioFormat format, int bufferSize) throws LineUnavailableException; - + void open(AudioFormat format, int bufferSize) throws LineUnavailableException; /** * Opens the line with the specified format, causing the line to acquire any * required system resources and become operational. - * *

    * The implementation chooses a buffer size, which is measured in bytes but - * which encompasses an integral number of sample frames. The buffer size - * that the system has chosen may be queried by subsequently calling {@link DataLine#getBufferSize} + * which encompasses an integral number of sample frames. The buffer size + * that the system has chosen may be queried by subsequently calling + * {@link DataLine#getBufferSize} *

    * If this operation succeeds, the line is marked as open, and an - * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the - * line's listeners. + * {@link LineEvent.Type#OPEN OPEN} event is dispatched to the line's + * listeners. *

    - * Invoking this method on a line that is already open is illegal - * and may result in an IllegalStateException. + * Invoking this method on a line that is already open is illegal and may + * result in an {@code IllegalStateException}. *

    - * Some lines, once closed, cannot be reopened. Attempts - * to reopen such a line will always result in a - * LineUnavailableException. + * Some lines, once closed, cannot be reopened. Attempts to reopen such a + * line will always result in a {@code LineUnavailableException}. * - * @param format the desired audio format - * @throws LineUnavailableException if the line cannot be - * opened due to resource restrictions - * @throws IllegalArgumentException if format - * is not fully specified or invalid + * @param format the desired audio format + * @throws LineUnavailableException if the line cannot be opened due to + * resource restrictions + * @throws IllegalArgumentException if {@code format} is not fully specified + * or invalid * @throws IllegalStateException if the line is already open - * @throws SecurityException if the line cannot be - * opened due to security restrictions - * + * @throws SecurityException if the line cannot be opened due to security + * restrictions * @see #open(AudioFormat, int) * @see Line#open * @see Line#close * @see Line#isOpen * @see LineEvent */ - public void open(AudioFormat format) throws LineUnavailableException; - + void open(AudioFormat format) throws LineUnavailableException; /** - * Reads audio data from the data line's input buffer. The requested - * number of bytes is read into the specified array, starting at - * the specified offset into the array in bytes. This method blocks until - * the requested amount of data has been read. However, if the data line - * is closed, stopped, drained, or flushed before the requested amount has - * been read, the method no longer blocks, but returns the number of bytes - * read thus far. + * Reads audio data from the data line's input buffer. The requested number + * of bytes is read into the specified array, starting at the specified + * offset into the array in bytes. This method blocks until the requested + * amount of data has been read. However, if the data line is closed, + * stopped, drained, or flushed before the requested amount has been read, + * the method no longer blocks, but returns the number of bytes read thus + * far. *

    * The number of bytes that can be read without blocking can be ascertained - * using the {@link DataLine#available available} method of the - * DataLine interface. (While it is guaranteed that - * this number of bytes can be read without blocking, there is no guarantee - * that attempts to read additional data will block.) + * using the {@link DataLine#available available} method of the + * {@code DataLine} interface. (While it is guaranteed that this number of + * bytes can be read without blocking, there is no guarantee that attempts + * to read additional data will block.) *

    * The number of bytes to be read must represent an integral number of * sample frames, such that: *
    - *

    [ bytes read ] % [frame size in bytes ] == 0
    + *
    {@code [ bytes read ] % [frame size in bytes ] == 0}
    *
    - * The return value will always meet this requirement. A request to read a - * number of bytes representing a non-integral number of sample frames cannot - * be fulfilled and may result in an IllegalArgumentException. + * The return value will always meet this requirement. A request to read a + * number of bytes representing a non-integral number of sample frames + * cannot be fulfilled and may result in an IllegalArgumentException. * - * @param b a byte array that will contain the requested input data when - * this method returns - * @param off the offset from the beginning of the array, in bytes - * @param len the requested number of bytes to read + * @param b a byte array that will contain the requested input data when + * this method returns + * @param off the offset from the beginning of the array, in bytes + * @param len the requested number of bytes to read * @return the number of bytes actually read * @throws IllegalArgumentException if the requested number of bytes does - * not represent an integral number of sample frames. - * or if len is negative. - * @throws ArrayIndexOutOfBoundsException if off is negative, - * or off+len is greater than the length of the array - * b. + * not represent an integral number of sample frames, or if + * {@code len} is negative + * @throws ArrayIndexOutOfBoundsException if {@code off} is negative, or + * {@code off+len} is greater than the length of the array {@code b} * * @see SourceDataLine#write * @see DataLine#available */ - public int read(byte[] b, int off, int len); + int read(byte[] b, int off, int len); /** * Obtains the number of sample frames of audio data that can be read from - * the target data line without blocking. Note that the return value + * the target data line without blocking. Note that the return value * measures sample frames, not bytes. + * * @return the number of sample frames currently available for reading * @see SourceDataLine#availableWrite */ diff --git a/jdk/src/share/classes/javax/sound/sampled/UnsupportedAudioFileException.java b/jdk/src/share/classes/javax/sound/sampled/UnsupportedAudioFileException.java index 45acd480f35..31d68160995 100644 --- a/jdk/src/share/classes/javax/sound/sampled/UnsupportedAudioFileException.java +++ b/jdk/src/share/classes/javax/sound/sampled/UnsupportedAudioFileException.java @@ -26,33 +26,32 @@ package javax.sound.sampled; /** - * An UnsupportedAudioFileException is an exception indicating that an - * operation failed because a file did not contain valid data of a recognized file - * type and format. + * An {@code UnsupportedAudioFileException} is an exception indicating that an + * operation failed because a file did not contain valid data of a recognized + * file type and format. * * @author Kara Kytle * @since 1.3 */ public class UnsupportedAudioFileException extends Exception { + private static final long serialVersionUID = -139127412623160368L; /** - * Constructs a UnsupportedAudioFileException that has - * null as its error detail message. + * Constructs a {@code UnsupportedAudioFileException} that has {@code null} + * as its error detail message. */ public UnsupportedAudioFileException() { - super(); } /** - * Constructs a UnsupportedAudioFileException that has - * the specified detail message. + * Constructs a {@code UnsupportedAudioFileException} that has the specified + * detail message. * - * @param message a string containing the error detail message + * @param message a string containing the error detail message */ - public UnsupportedAudioFileException(String message) { - + public UnsupportedAudioFileException(final String message) { super(message); } } diff --git a/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java b/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java index cc476452126..daa75556785 100644 --- a/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java +++ b/jdk/src/share/classes/javax/sound/sampled/spi/AudioFileReader.java @@ -108,7 +108,7 @@ public abstract class AudioFileReader { * @param stream the input stream from which the {@code AudioInputStream} * should be constructed * @return an {@code AudioInputStream} object based on the audio file data - * contained in the input stream. + * contained in the input stream * @throws UnsupportedAudioFileException if the stream does not point to * valid audio file data recognized by the system * @throws IOException if an I/O exception occurs diff --git a/jdk/src/share/classes/javax/sound/sampled/spi/FormatConversionProvider.java b/jdk/src/share/classes/javax/sound/sampled/spi/FormatConversionProvider.java index 7693087c9d9..8cb7fb68d5f 100644 --- a/jdk/src/share/classes/javax/sound/sampled/spi/FormatConversionProvider.java +++ b/jdk/src/share/classes/javax/sound/sampled/spi/FormatConversionProvider.java @@ -117,7 +117,7 @@ public abstract class FormatConversionProvider { * are supported for this source format, an array of length 0 is returned. * * @param sourceFormat format of the incoming data - * @return array of supported target format encodings. + * @return array of supported target format encodings */ public abstract Encoding[] getTargetEncodings(AudioFormat sourceFormat); @@ -150,7 +150,7 @@ public abstract class FormatConversionProvider { * * @param targetEncoding desired encoding of the stream after processing * @param sourceFormat format of the incoming data - * @return array of supported target formats. + * @return array of supported target formats */ public abstract AudioFormat[] getTargetFormats(Encoding targetEncoding, AudioFormat sourceFormat); @@ -187,7 +187,7 @@ public abstract class FormatConversionProvider { * @return stream from which processed data with the specified target * encoding may be read * @throws IllegalArgumentException if the format combination supplied is - * not supported. + * not supported */ public abstract AudioInputStream getAudioInputStream( Encoding targetEncoding, AudioInputStream sourceStream); @@ -202,7 +202,7 @@ public abstract class FormatConversionProvider { * @return stream from which processed data with the specified format may be * read * @throws IllegalArgumentException if the format combination supplied is - * not supported. + * not supported */ public abstract AudioInputStream getAudioInputStream( AudioFormat targetFormat, AudioInputStream sourceStream); diff --git a/jdk/src/share/classes/javax/swing/AbstractAction.java b/jdk/src/share/classes/javax/swing/AbstractAction.java index f8f15f4f992..1f0ef990243 100644 --- a/jdk/src/share/classes/javax/swing/AbstractAction.java +++ b/jdk/src/share/classes/javax/swing/AbstractAction.java @@ -55,6 +55,7 @@ import sun.security.action.GetPropertyAction; * * @author Georges Saab * @see Action + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public abstract class AbstractAction implements Action, Cloneable, Serializable diff --git a/jdk/src/share/classes/javax/swing/AbstractButton.java b/jdk/src/share/classes/javax/swing/AbstractButton.java index 02ddcfe729c..58f9e943c9f 100644 --- a/jdk/src/share/classes/javax/swing/AbstractButton.java +++ b/jdk/src/share/classes/javax/swing/AbstractButton.java @@ -71,6 +71,7 @@ import java.util.*; * Please see {@link java.beans.XMLEncoder}. * * @author Jeff Dinkins + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public abstract class AbstractButton extends JComponent implements ItemSelectable, SwingConstants { diff --git a/jdk/src/share/classes/javax/swing/AbstractListModel.java b/jdk/src/share/classes/javax/swing/AbstractListModel.java index 33145a51e8e..cc3003dc132 100644 --- a/jdk/src/share/classes/javax/swing/AbstractListModel.java +++ b/jdk/src/share/classes/javax/swing/AbstractListModel.java @@ -45,6 +45,7 @@ import java.util.EventListener; * @param the type of the elements of this model * * @author Hans Muller + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public abstract class AbstractListModel implements ListModel, Serializable diff --git a/jdk/src/share/classes/javax/swing/Action.java b/jdk/src/share/classes/javax/swing/Action.java index b803b37d96f..b1ebbec40a8 100644 --- a/jdk/src/share/classes/javax/swing/Action.java +++ b/jdk/src/share/classes/javax/swing/Action.java @@ -210,6 +210,7 @@ import java.beans.*; * * @author Georges Saab * @see AbstractAction + * @since 1.2 */ public interface Action extends ActionListener { /** diff --git a/jdk/src/share/classes/javax/swing/BorderFactory.java b/jdk/src/share/classes/javax/swing/BorderFactory.java index f821e76f8cc..9f2393cb91d 100644 --- a/jdk/src/share/classes/javax/swing/BorderFactory.java +++ b/jdk/src/share/classes/javax/swing/BorderFactory.java @@ -40,6 +40,7 @@ import javax.swing.border.*; * a section in The Java Tutorial. * * @author David Kloba + * @since 1.2 */ public class BorderFactory { diff --git a/jdk/src/share/classes/javax/swing/BoundedRangeModel.java b/jdk/src/share/classes/javax/swing/BoundedRangeModel.java index ea0a41119e2..bc6a84ac891 100644 --- a/jdk/src/share/classes/javax/swing/BoundedRangeModel.java +++ b/jdk/src/share/classes/javax/swing/BoundedRangeModel.java @@ -76,6 +76,7 @@ import javax.swing.event.*; * * @author Hans Muller * @see DefaultBoundedRangeModel + * @since 1.2 */ public interface BoundedRangeModel { diff --git a/jdk/src/share/classes/javax/swing/Box.java b/jdk/src/share/classes/javax/swing/Box.java index 9bf5474c746..d332214a3c5 100644 --- a/jdk/src/share/classes/javax/swing/Box.java +++ b/jdk/src/share/classes/javax/swing/Box.java @@ -75,6 +75,7 @@ import javax.accessibility.*; * @see BoxLayout * * @author Timothy Prinzing + * @since 1.2 */ @SuppressWarnings("serial") public class Box extends JComponent implements Accessible { diff --git a/jdk/src/share/classes/javax/swing/BoxLayout.java b/jdk/src/share/classes/javax/swing/BoxLayout.java index 8723a15f048..c3565fb1741 100644 --- a/jdk/src/share/classes/javax/swing/BoxLayout.java +++ b/jdk/src/share/classes/javax/swing/BoxLayout.java @@ -134,6 +134,7 @@ import java.io.PrintStream; * @see JComponent#getAlignmentY * * @author Timothy Prinzing + * @since 1.2 */ @SuppressWarnings("serial") public class BoxLayout implements LayoutManager2, Serializable { diff --git a/jdk/src/share/classes/javax/swing/ButtonGroup.java b/jdk/src/share/classes/javax/swing/ButtonGroup.java index 64f5b641774..21c13a49cbb 100644 --- a/jdk/src/share/classes/javax/swing/ButtonGroup.java +++ b/jdk/src/share/classes/javax/swing/ButtonGroup.java @@ -64,6 +64,7 @@ import java.io.Serializable; * Please see {@link java.beans.XMLEncoder}. * * @author Jeff Dinkins + * @since 1.2 */ @SuppressWarnings("serial") public class ButtonGroup implements Serializable { diff --git a/jdk/src/share/classes/javax/swing/ButtonModel.java b/jdk/src/share/classes/javax/swing/ButtonModel.java index 1668c673b56..85ba48f6ba2 100644 --- a/jdk/src/share/classes/javax/swing/ButtonModel.java +++ b/jdk/src/share/classes/javax/swing/ButtonModel.java @@ -72,6 +72,7 @@ import javax.swing.event.*; * ActionEvent to be fired. * * @author Jeff Dinkins + * @since 1.2 */ public interface ButtonModel extends ItemSelectable { diff --git a/jdk/src/share/classes/javax/swing/CellEditor.java b/jdk/src/share/classes/javax/swing/CellEditor.java index 3211a788cb9..f1b625b7969 100644 --- a/jdk/src/share/classes/javax/swing/CellEditor.java +++ b/jdk/src/share/classes/javax/swing/CellEditor.java @@ -57,6 +57,7 @@ import javax.swing.event.*; * @see javax.swing.event.CellEditorListener * * @author Alan Chung + * @since 1.2 */ public interface CellEditor { diff --git a/jdk/src/share/classes/javax/swing/CellRendererPane.java b/jdk/src/share/classes/javax/swing/CellRendererPane.java index 33539284e2d..70ba2afa04c 100644 --- a/jdk/src/share/classes/javax/swing/CellRendererPane.java +++ b/jdk/src/share/classes/javax/swing/CellRendererPane.java @@ -62,6 +62,7 @@ import javax.accessibility.*; * Please see {@link java.beans.XMLEncoder}. * * @author Hans Muller + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class CellRendererPane extends Container implements Accessible diff --git a/jdk/src/share/classes/javax/swing/ComboBoxEditor.java b/jdk/src/share/classes/javax/swing/ComboBoxEditor.java index de191d1bcf9..f7dd950471c 100644 --- a/jdk/src/share/classes/javax/swing/ComboBoxEditor.java +++ b/jdk/src/share/classes/javax/swing/ComboBoxEditor.java @@ -31,6 +31,7 @@ import java.awt.event.*; * The editor component used for JComboBox components. * * @author Arnaud Weber + * @since 1.2 */ public interface ComboBoxEditor { diff --git a/jdk/src/share/classes/javax/swing/ComboBoxModel.java b/jdk/src/share/classes/javax/swing/ComboBoxModel.java index e7c3be9811b..50bd87d66f0 100644 --- a/jdk/src/share/classes/javax/swing/ComboBoxModel.java +++ b/jdk/src/share/classes/javax/swing/ComboBoxModel.java @@ -36,6 +36,7 @@ package javax.swing; * @param the type of the elements of this model * * @author Arnaud Weber + * @since 1.2 */ public interface ComboBoxModel extends ListModel { diff --git a/jdk/src/share/classes/javax/swing/DebugGraphics.java b/jdk/src/share/classes/javax/swing/DebugGraphics.java index a41e9c62f55..53219b74c33 100644 --- a/jdk/src/share/classes/javax/swing/DebugGraphics.java +++ b/jdk/src/share/classes/javax/swing/DebugGraphics.java @@ -45,6 +45,7 @@ import java.text.AttributedCharacterIterator; * @see RepaintManager#setDoubleBufferingEnabled * * @author Dave Karlton + * @since 1.2 */ public class DebugGraphics extends Graphics { Graphics graphics; diff --git a/jdk/src/share/classes/javax/swing/DefaultBoundedRangeModel.java b/jdk/src/share/classes/javax/swing/DefaultBoundedRangeModel.java index 8d316ce28ac..b7b989e07fa 100644 --- a/jdk/src/share/classes/javax/swing/DefaultBoundedRangeModel.java +++ b/jdk/src/share/classes/javax/swing/DefaultBoundedRangeModel.java @@ -44,6 +44,7 @@ import java.util.EventListener; * @author David Kloba * @author Hans Muller * @see BoundedRangeModel + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class DefaultBoundedRangeModel implements BoundedRangeModel, Serializable diff --git a/jdk/src/share/classes/javax/swing/DefaultButtonModel.java b/jdk/src/share/classes/javax/swing/DefaultButtonModel.java index 8fba596f3fe..fe2ddd143cd 100644 --- a/jdk/src/share/classes/javax/swing/DefaultButtonModel.java +++ b/jdk/src/share/classes/javax/swing/DefaultButtonModel.java @@ -44,6 +44,7 @@ import javax.swing.event.*; * Please see {@link java.beans.XMLEncoder}. * * @author Jeff Dinkins + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class DefaultButtonModel implements ButtonModel, Serializable { diff --git a/jdk/src/share/classes/javax/swing/DefaultCellEditor.java b/jdk/src/share/classes/javax/swing/DefaultCellEditor.java index 1eea9e1fb3f..ba8942c5b21 100644 --- a/jdk/src/share/classes/javax/swing/DefaultCellEditor.java +++ b/jdk/src/share/classes/javax/swing/DefaultCellEditor.java @@ -49,6 +49,7 @@ import java.io.Serializable; * * @author Alan Chung * @author Philip Milne + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class DefaultCellEditor extends AbstractCellEditor diff --git a/jdk/src/share/classes/javax/swing/DefaultComboBoxModel.java b/jdk/src/share/classes/javax/swing/DefaultComboBoxModel.java index b42dc109b50..813ebd39ef1 100644 --- a/jdk/src/share/classes/javax/swing/DefaultComboBoxModel.java +++ b/jdk/src/share/classes/javax/swing/DefaultComboBoxModel.java @@ -35,6 +35,7 @@ import java.io.Serializable; * * @author Arnaud Weber * @author Tom Santos + * @since 1.2 */ @SuppressWarnings("serial") // Superclass is not serializable across versions public class DefaultComboBoxModel extends AbstractListModel implements MutableComboBoxModel, Serializable { diff --git a/jdk/src/share/classes/javax/swing/DefaultDesktopManager.java b/jdk/src/share/classes/javax/swing/DefaultDesktopManager.java index d140e98c5d7..6c66c8d6cce 100644 --- a/jdk/src/share/classes/javax/swing/DefaultDesktopManager.java +++ b/jdk/src/share/classes/javax/swing/DefaultDesktopManager.java @@ -46,6 +46,7 @@ import java.beans.PropertyVetoException; * @see JInternalFrame * @author David Kloba * @author Steve Wilson + * @since 1.2 */ @SuppressWarnings("serial") // No Interesting Non-Transient State public class DefaultDesktopManager implements DesktopManager, java.io.Serializable { diff --git a/jdk/src/share/classes/javax/swing/DefaultFocusManager.java b/jdk/src/share/classes/javax/swing/DefaultFocusManager.java index 31240737791..502fc6c7f42 100644 --- a/jdk/src/share/classes/javax/swing/DefaultFocusManager.java +++ b/jdk/src/share/classes/javax/swing/DefaultFocusManager.java @@ -45,6 +45,7 @@ import java.util.Comparator; * * @author Arnaud Weber * @author David Mendenhall + * @since 1.2 */ @SuppressWarnings("serial") // Obsolete class public class DefaultFocusManager extends FocusManager { diff --git a/jdk/src/share/classes/javax/swing/DefaultListCellRenderer.java b/jdk/src/share/classes/javax/swing/DefaultListCellRenderer.java index e4968364cc0..3cc567480c1 100644 --- a/jdk/src/share/classes/javax/swing/DefaultListCellRenderer.java +++ b/jdk/src/share/classes/javax/swing/DefaultListCellRenderer.java @@ -69,6 +69,7 @@ import sun.swing.DefaultLookup; * * @author Philip Milne * @author Hans Muller + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class DefaultListCellRenderer extends JLabel diff --git a/jdk/src/share/classes/javax/swing/DefaultListModel.java b/jdk/src/share/classes/javax/swing/DefaultListModel.java index 063c18e2716..2b10f45ad47 100644 --- a/jdk/src/share/classes/javax/swing/DefaultListModel.java +++ b/jdk/src/share/classes/javax/swing/DefaultListModel.java @@ -51,6 +51,7 @@ import javax.swing.event.*; * @param the type of the elements of this model * * @author Hans Muller + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class DefaultListModel extends AbstractListModel diff --git a/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java b/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java index f7b00bee086..a1cb79f8ea6 100644 --- a/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java +++ b/jdk/src/share/classes/javax/swing/DefaultListSelectionModel.java @@ -48,6 +48,7 @@ import javax.swing.event.*; * @author Philip Milne * @author Hans Muller * @see ListSelectionModel + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class DefaultListSelectionModel implements ListSelectionModel, Cloneable, Serializable diff --git a/jdk/src/share/classes/javax/swing/DefaultSingleSelectionModel.java b/jdk/src/share/classes/javax/swing/DefaultSingleSelectionModel.java index d5e5ab81e1d..75c522e79c9 100644 --- a/jdk/src/share/classes/javax/swing/DefaultSingleSelectionModel.java +++ b/jdk/src/share/classes/javax/swing/DefaultSingleSelectionModel.java @@ -42,6 +42,7 @@ import java.util.EventListener; * Please see {@link java.beans.XMLEncoder}. * * @author Dave Moore + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class DefaultSingleSelectionModel implements SingleSelectionModel, diff --git a/jdk/src/share/classes/javax/swing/DesktopManager.java b/jdk/src/share/classes/javax/swing/DesktopManager.java index 07e40a07b21..edcfaf4fabb 100644 --- a/jdk/src/share/classes/javax/swing/DesktopManager.java +++ b/jdk/src/share/classes/javax/swing/DesktopManager.java @@ -43,6 +43,7 @@ package javax.swing; * @see JInternalFrame.JDesktopIcon * * @author David Kloba + * @since 1.2 */ public interface DesktopManager { diff --git a/jdk/src/share/classes/javax/swing/FocusManager.java b/jdk/src/share/classes/javax/swing/FocusManager.java index 9fa9b5666eb..45fc6b6e5b9 100644 --- a/jdk/src/share/classes/javax/swing/FocusManager.java +++ b/jdk/src/share/classes/javax/swing/FocusManager.java @@ -44,6 +44,7 @@ import java.awt.*; * * @author Arnaud Weber * @author David Mendenhall + * @since 1.2 */ public abstract class FocusManager extends DefaultKeyboardFocusManager { diff --git a/jdk/src/share/classes/javax/swing/GrayFilter.java b/jdk/src/share/classes/javax/swing/GrayFilter.java index d53f5d39c76..573edbedb63 100644 --- a/jdk/src/share/classes/javax/swing/GrayFilter.java +++ b/jdk/src/share/classes/javax/swing/GrayFilter.java @@ -36,6 +36,7 @@ import java.awt.image.*; * @author Jeff Dinkins * @author Tom Ball * @author Jim Graham + * @since 1.2 */ public class GrayFilter extends RGBImageFilter { private boolean brighter; diff --git a/jdk/src/share/classes/javax/swing/Icon.java b/jdk/src/share/classes/javax/swing/Icon.java index f4e68840ab9..87c53684711 100644 --- a/jdk/src/share/classes/javax/swing/Icon.java +++ b/jdk/src/share/classes/javax/swing/Icon.java @@ -32,6 +32,7 @@ import java.awt.Component; * A small fixed size picture, typically used to decorate components. * * @see ImageIcon + * @since 1.2 */ public interface Icon diff --git a/jdk/src/share/classes/javax/swing/ImageIcon.java b/jdk/src/share/classes/javax/swing/ImageIcon.java index e286e936f11..8f7812e5919 100644 --- a/jdk/src/share/classes/javax/swing/ImageIcon.java +++ b/jdk/src/share/classes/javax/swing/ImageIcon.java @@ -65,6 +65,7 @@ import java.security.*; * * @author Jeff Dinkins * @author Lynn Monsanto + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class ImageIcon implements Icon, Serializable, Accessible { diff --git a/jdk/src/share/classes/javax/swing/JApplet.java b/jdk/src/share/classes/javax/swing/JApplet.java index 539458979d4..651d004660d 100644 --- a/jdk/src/share/classes/javax/swing/JApplet.java +++ b/jdk/src/share/classes/javax/swing/JApplet.java @@ -89,6 +89,7 @@ import javax.accessibility.*; * description: Swing's Applet subclass. * * @author Arnaud Weber + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JApplet extends Applet implements Accessible, diff --git a/jdk/src/share/classes/javax/swing/JButton.java b/jdk/src/share/classes/javax/swing/JButton.java index 5823cf1bffa..937de3adad6 100644 --- a/jdk/src/share/classes/javax/swing/JButton.java +++ b/jdk/src/share/classes/javax/swing/JButton.java @@ -74,6 +74,7 @@ import java.io.IOException; * description: An implementation of a \"push\" button. * * @author Jeff Dinkins + * @since 1.2 */ @SuppressWarnings("serial") public class JButton extends AbstractButton implements Accessible { diff --git a/jdk/src/share/classes/javax/swing/JCheckBox.java b/jdk/src/share/classes/javax/swing/JCheckBox.java index 53502645c72..c912a383cae 100644 --- a/jdk/src/share/classes/javax/swing/JCheckBox.java +++ b/jdk/src/share/classes/javax/swing/JCheckBox.java @@ -74,6 +74,7 @@ import java.io.IOException; * description: A component which can be selected or deselected. * * @author Jeff Dinkins + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JCheckBox extends JToggleButton implements Accessible { diff --git a/jdk/src/share/classes/javax/swing/JCheckBoxMenuItem.java b/jdk/src/share/classes/javax/swing/JCheckBoxMenuItem.java index 08eb53864c4..962ef73f3c0 100644 --- a/jdk/src/share/classes/javax/swing/JCheckBoxMenuItem.java +++ b/jdk/src/share/classes/javax/swing/JCheckBoxMenuItem.java @@ -87,6 +87,7 @@ import javax.accessibility.*; * * @author Georges Saab * @author David Karlton + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JCheckBoxMenuItem extends JMenuItem implements SwingConstants, diff --git a/jdk/src/share/classes/javax/swing/JColorChooser.java b/jdk/src/share/classes/javax/swing/JColorChooser.java index 9420f499c41..a2aa8146c6b 100644 --- a/jdk/src/share/classes/javax/swing/JColorChooser.java +++ b/jdk/src/share/classes/javax/swing/JColorChooser.java @@ -82,6 +82,7 @@ import sun.swing.SwingUtilities2; * @author James Gosling * @author Amy Fowler * @author Steve Wilson + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JColorChooser extends JComponent implements Accessible { diff --git a/jdk/src/share/classes/javax/swing/JComboBox.java b/jdk/src/share/classes/javax/swing/JComboBox.java index c2fcd40a186..4bab4916931 100644 --- a/jdk/src/share/classes/javax/swing/JComboBox.java +++ b/jdk/src/share/classes/javax/swing/JComboBox.java @@ -77,6 +77,7 @@ import javax.accessibility.*; * * @author Arnaud Weber * @author Mark Davidson + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JComboBox extends JComponent @@ -1318,13 +1319,15 @@ implements ItemSelectable,ListDataListener,ActionListener, Accessible { * do not call or override. */ public void actionPerformed(ActionEvent e) { - Object newItem = getEditor().getItem(); - setPopupVisible(false); - getModel().setSelectedItem(newItem); - String oldCommand = getActionCommand(); - setActionCommand("comboBoxEdited"); - fireActionEvent(); - setActionCommand(oldCommand); + ComboBoxEditor editor = getEditor(); + if ((editor != null) && (e != null) && (editor == e.getSource())) { + setPopupVisible(false); + getModel().setSelectedItem(editor.getItem()); + String oldCommand = getActionCommand(); + setActionCommand("comboBoxEdited"); + fireActionEvent(); + setActionCommand(oldCommand); + } } /** diff --git a/jdk/src/share/classes/javax/swing/JComponent.java b/jdk/src/share/classes/javax/swing/JComponent.java index 2d2745957e7..41dc5e54497 100644 --- a/jdk/src/share/classes/javax/swing/JComponent.java +++ b/jdk/src/share/classes/javax/swing/JComponent.java @@ -63,6 +63,7 @@ import javax.swing.plaf.*; import static javax.swing.ClientPropertyKey.*; import javax.accessibility.*; +import sun.awt.SunToolkit; import sun.swing.SwingUtilities2; import sun.swing.UIClientPropertyKey; @@ -178,6 +179,7 @@ import sun.swing.UIClientPropertyKey; * * @author Hans Muller * @author Arnaud Weber + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public abstract class JComponent extends Container implements Serializable, @@ -3678,8 +3680,8 @@ public abstract class JComponent extends Container implements Serializable, private volatile transient int propertyListenersCount = 0; /** - * This field duplicates the one in java.awt.Component.AccessibleAWTComponent, - * so it has been deprecated. + * This field duplicates the function of the accessibleAWTFocusHandler field + * in java.awt.Component.AccessibleAWTComponent, so it has been deprecated. */ @Deprecated protected FocusListener accessibleFocusHandler = null; @@ -3737,14 +3739,10 @@ public abstract class JComponent extends Container implements Serializable, * @param listener the PropertyChangeListener to be added */ public void addPropertyChangeListener(PropertyChangeListener listener) { - if (accessibleFocusHandler == null) { - accessibleFocusHandler = new AccessibleFocusHandler(); - } if (accessibleContainerHandler == null) { accessibleContainerHandler = new AccessibleContainerHandler(); } if (propertyListenersCount++ == 0) { - JComponent.this.addFocusListener(accessibleFocusHandler); JComponent.this.addContainerListener(accessibleContainerHandler); } super.addPropertyChangeListener(listener); @@ -3759,7 +3757,6 @@ public abstract class JComponent extends Container implements Serializable, */ public void removePropertyChangeListener(PropertyChangeListener listener) { if (--propertyListenersCount == 0) { - JComponent.this.removeFocusListener(accessibleFocusHandler); JComponent.this.removeContainerListener(accessibleContainerHandler); } super.removePropertyChangeListener(listener); @@ -4802,7 +4799,8 @@ public abstract class JComponent extends Container implements Serializable, * @see RepaintManager#addDirtyRegion */ public void repaint(long tm, int x, int y, int width, int height) { - RepaintManager.currentManager(this).addDirtyRegion(this, x, y, width, height); + RepaintManager.currentManager(SunToolkit.targetToAppContext(this)) + .addDirtyRegion(this, x, y, width, height); } @@ -4856,7 +4854,7 @@ public abstract class JComponent extends Container implements Serializable, // which was causing some people grief. return; } - if (SwingUtilities.isEventDispatchThread()) { + if (SunToolkit.isDispatchThreadForAppContext(this)) { invalidate(); RepaintManager.currentManager(this).addInvalidComponent(this); } @@ -4870,15 +4868,12 @@ public abstract class JComponent extends Container implements Serializable, } setFlag(REVALIDATE_RUNNABLE_SCHEDULED, true); } - Runnable callRevalidate = new Runnable() { - public void run() { - synchronized(JComponent.this) { - setFlag(REVALIDATE_RUNNABLE_SCHEDULED, false); - } - revalidate(); + SunToolkit.executeOnEventHandlerThread(this, () -> { + synchronized(JComponent.this) { + setFlag(REVALIDATE_RUNNABLE_SCHEDULED, false); } - }; - SwingUtilities.invokeLater(callRevalidate); + revalidate(); + }); } } diff --git a/jdk/src/share/classes/javax/swing/JDesktopPane.java b/jdk/src/share/classes/javax/swing/JDesktopPane.java index 94f7db248e1..35d53d2d918 100644 --- a/jdk/src/share/classes/javax/swing/JDesktopPane.java +++ b/jdk/src/share/classes/javax/swing/JDesktopPane.java @@ -85,6 +85,7 @@ import java.util.TreeSet; * @see DesktopManager * * @author David Kloba + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JDesktopPane extends JLayeredPane implements Accessible diff --git a/jdk/src/share/classes/javax/swing/JDialog.java b/jdk/src/share/classes/javax/swing/JDialog.java index 12b978dbf46..ae0a3519e93 100644 --- a/jdk/src/share/classes/javax/swing/JDialog.java +++ b/jdk/src/share/classes/javax/swing/JDialog.java @@ -94,6 +94,7 @@ import javax.accessibility.*; * @author David Kloba * @author James Gosling * @author Scott Violet + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JDialog extends Dialog implements WindowConstants, @@ -647,6 +648,7 @@ public class JDialog extends Dialog implements WindowConstants, enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK); setLocale( JComponent.getDefaultLocale() ); setRootPane(createRootPane()); + setBackground(UIManager.getColor("control")); setRootPaneCheckingEnabled(true); if (JDialog.isDefaultLookAndFeelDecorated()) { boolean supportsWindowDecorations = diff --git a/jdk/src/share/classes/javax/swing/JEditorPane.java b/jdk/src/share/classes/javax/swing/JEditorPane.java index c1382125237..d650c4816e8 100644 --- a/jdk/src/share/classes/javax/swing/JEditorPane.java +++ b/jdk/src/share/classes/javax/swing/JEditorPane.java @@ -188,6 +188,7 @@ import javax.accessibility.*; * description: A text component to edit various types of content. * * @author Timothy Prinzing + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JEditorPane extends JTextComponent { @@ -679,8 +680,8 @@ public class JEditorPane extends JTextComponent { } }); } - return (pageLoaded ? page : old); } + return (pageLoaded ? page : old); } /** @@ -965,7 +966,7 @@ public class JEditorPane extends JTextComponent { // The type could have optional info is part of it, // for example some charset info. We need to strip that // of and save it. - int parm = type.indexOf(";"); + int parm = type.indexOf(';'); if (parm > -1) { // Save the paramList. String paramList = type.substring(parm); diff --git a/jdk/src/share/classes/javax/swing/JFileChooser.java b/jdk/src/share/classes/javax/swing/JFileChooser.java index ac6374c2a40..336f57c438b 100644 --- a/jdk/src/share/classes/javax/swing/JFileChooser.java +++ b/jdk/src/share/classes/javax/swing/JFileChooser.java @@ -86,7 +86,7 @@ import java.lang.ref.WeakReference; * description: A component which allows for the interactive selection of a file. * * @author Jeff Dinkins - * + * @since 1.2 */ @SuppressWarnings("serial") // Superclass is not serializable across versions public class JFileChooser extends JComponent implements Accessible { diff --git a/jdk/src/share/classes/javax/swing/JFrame.java b/jdk/src/share/classes/javax/swing/JFrame.java index c773a3b66a8..e4a5efef662 100644 --- a/jdk/src/share/classes/javax/swing/JFrame.java +++ b/jdk/src/share/classes/javax/swing/JFrame.java @@ -111,6 +111,7 @@ import javax.accessibility.*; * @author Jeff Dinkins * @author Georges Saab * @author David Kloba + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JFrame extends Frame implements WindowConstants, diff --git a/jdk/src/share/classes/javax/swing/JInternalFrame.java b/jdk/src/share/classes/javax/swing/JInternalFrame.java index e94854f9f12..3ecb82450d2 100644 --- a/jdk/src/share/classes/javax/swing/JInternalFrame.java +++ b/jdk/src/share/classes/javax/swing/JInternalFrame.java @@ -104,6 +104,7 @@ import sun.swing.SwingUtilities2; * * @author David Kloba * @author Rich Schiavi + * @since 1.2 * @beaninfo * attribute: isContainer true * attribute: containerDelegate getContentPane diff --git a/jdk/src/share/classes/javax/swing/JLabel.java b/jdk/src/share/classes/javax/swing/JLabel.java index af080be9564..2b0be80b1c7 100644 --- a/jdk/src/share/classes/javax/swing/JLabel.java +++ b/jdk/src/share/classes/javax/swing/JLabel.java @@ -103,6 +103,7 @@ import java.util.*; * description: A component that displays a short string and an icon. * * @author Hans Muller + * @since 1.2 */ @SuppressWarnings("serial") public class JLabel extends JComponent implements SwingConstants, Accessible diff --git a/jdk/src/share/classes/javax/swing/JLayeredPane.java b/jdk/src/share/classes/javax/swing/JLayeredPane.java index 56685df9e66..ecb40a60bf5 100644 --- a/jdk/src/share/classes/javax/swing/JLayeredPane.java +++ b/jdk/src/share/classes/javax/swing/JLayeredPane.java @@ -153,6 +153,7 @@ import javax.accessibility.*; * Please see {@link java.beans.XMLEncoder}. * * @author David Kloba + * @since 1.2 */ @SuppressWarnings("serial") public class JLayeredPane extends JComponent implements Accessible { diff --git a/jdk/src/share/classes/javax/swing/JList.java b/jdk/src/share/classes/javax/swing/JList.java index 8088396fcc3..808f9780c3f 100644 --- a/jdk/src/share/classes/javax/swing/JList.java +++ b/jdk/src/share/classes/javax/swing/JList.java @@ -276,6 +276,7 @@ import static sun.swing.SwingUtilities2.Section.*; * description: A component which allows for the selection of one or more objects from a list. * * @author Hans Muller + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JList extends JComponent implements Scrollable, Accessible diff --git a/jdk/src/share/classes/javax/swing/JMenu.java b/jdk/src/share/classes/javax/swing/JMenu.java index a9cec084d7e..ea3b1b970d3 100644 --- a/jdk/src/share/classes/javax/swing/JMenu.java +++ b/jdk/src/share/classes/javax/swing/JMenu.java @@ -108,6 +108,7 @@ import java.lang.ref.WeakReference; * @see JSeparator * @see JMenuBar * @see JPopupMenu + * @since 1.2 */ @SuppressWarnings("serial") public class JMenu extends JMenuItem implements Accessible,MenuElement diff --git a/jdk/src/share/classes/javax/swing/JMenuBar.java b/jdk/src/share/classes/javax/swing/JMenuBar.java index 7c7cc541be9..4b4f6f91643 100644 --- a/jdk/src/share/classes/javax/swing/JMenuBar.java +++ b/jdk/src/share/classes/javax/swing/JMenuBar.java @@ -88,6 +88,7 @@ import javax.accessibility.*; * @see JMenu * @see JPopupMenu * @see JMenuItem + * @since 1.2 */ @SuppressWarnings("serial") public class JMenuBar extends JComponent implements Accessible,MenuElement diff --git a/jdk/src/share/classes/javax/swing/JMenuItem.java b/jdk/src/share/classes/javax/swing/JMenuItem.java index 4ee5b67bc43..f63dd709a3e 100644 --- a/jdk/src/share/classes/javax/swing/JMenuItem.java +++ b/jdk/src/share/classes/javax/swing/JMenuItem.java @@ -86,6 +86,7 @@ import javax.accessibility.*; * @see JMenu * @see JCheckBoxMenuItem * @see JRadioButtonMenuItem + * @since 1.2 */ @SuppressWarnings("serial") public class JMenuItem extends AbstractButton implements Accessible,MenuElement { diff --git a/jdk/src/share/classes/javax/swing/JOptionPane.java b/jdk/src/share/classes/javax/swing/JOptionPane.java index 34bbdd2b320..77fab724208 100644 --- a/jdk/src/share/classes/javax/swing/JOptionPane.java +++ b/jdk/src/share/classes/javax/swing/JOptionPane.java @@ -310,6 +310,7 @@ import sun.awt.AWTAccessor; * * @author James Gosling * @author Scott Violet + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JOptionPane extends JComponent implements Accessible diff --git a/jdk/src/share/classes/javax/swing/JPanel.java b/jdk/src/share/classes/javax/swing/JPanel.java index 6211c8bcd29..293ca2237df 100644 --- a/jdk/src/share/classes/javax/swing/JPanel.java +++ b/jdk/src/share/classes/javax/swing/JPanel.java @@ -61,6 +61,7 @@ import java.io.IOException; * * @author Arnaud Weber * @author Steve Wilson + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JPanel extends JComponent implements Accessible diff --git a/jdk/src/share/classes/javax/swing/JPasswordField.java b/jdk/src/share/classes/javax/swing/JPasswordField.java index a869d80c1f0..82b6457e8ec 100644 --- a/jdk/src/share/classes/javax/swing/JPasswordField.java +++ b/jdk/src/share/classes/javax/swing/JPasswordField.java @@ -73,6 +73,7 @@ import java.util.Arrays; * description: Allows the editing of a line of text but doesn't show the characters. * * @author Timothy Prinzing + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JPasswordField extends JTextField { diff --git a/jdk/src/share/classes/javax/swing/JPopupMenu.java b/jdk/src/share/classes/javax/swing/JPopupMenu.java index 4112de64db0..3f2a57323a5 100644 --- a/jdk/src/share/classes/javax/swing/JPopupMenu.java +++ b/jdk/src/share/classes/javax/swing/JPopupMenu.java @@ -82,6 +82,7 @@ import java.applet.Applet; * @author Georges Saab * @author David Karlton * @author Arnaud Weber + * @since 1.2 */ @SuppressWarnings("serial") public class JPopupMenu extends JComponent implements Accessible,MenuElement { diff --git a/jdk/src/share/classes/javax/swing/JProgressBar.java b/jdk/src/share/classes/javax/swing/JProgressBar.java index d8010e7b60b..5a3611131b8 100644 --- a/jdk/src/share/classes/javax/swing/JProgressBar.java +++ b/jdk/src/share/classes/javax/swing/JProgressBar.java @@ -128,6 +128,7 @@ import javax.swing.plaf.ProgressBarUI; * * @author Michael C. Albers * @author Kathy Walrath + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JProgressBar extends JComponent implements SwingConstants, Accessible diff --git a/jdk/src/share/classes/javax/swing/JRadioButton.java b/jdk/src/share/classes/javax/swing/JRadioButton.java index cdc0329b55e..c5eaf6813bd 100644 --- a/jdk/src/share/classes/javax/swing/JRadioButton.java +++ b/jdk/src/share/classes/javax/swing/JRadioButton.java @@ -85,6 +85,7 @@ import java.io.IOException; * @see ButtonGroup * @see JCheckBox * @author Jeff Dinkins + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JRadioButton extends JToggleButton implements Accessible { diff --git a/jdk/src/share/classes/javax/swing/JRadioButtonMenuItem.java b/jdk/src/share/classes/javax/swing/JRadioButtonMenuItem.java index c7acf05b847..e1c219b4037 100644 --- a/jdk/src/share/classes/javax/swing/JRadioButtonMenuItem.java +++ b/jdk/src/share/classes/javax/swing/JRadioButtonMenuItem.java @@ -82,6 +82,7 @@ import javax.accessibility.*; * @author Georges Saab * @author David Karlton * @see ButtonGroup + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JRadioButtonMenuItem extends JMenuItem implements Accessible { diff --git a/jdk/src/share/classes/javax/swing/JRootPane.java b/jdk/src/share/classes/javax/swing/JRootPane.java index 8cab327305b..f9dea90da3e 100644 --- a/jdk/src/share/classes/javax/swing/JRootPane.java +++ b/jdk/src/share/classes/javax/swing/JRootPane.java @@ -197,6 +197,7 @@ import sun.security.action.GetBooleanAction; * Mixing Heavy and Light Components * * @author David Kloba + * @since 1.2 */ /// PENDING(klobad) Who should be opaque in this component? @SuppressWarnings("serial") diff --git a/jdk/src/share/classes/javax/swing/JScrollBar.java b/jdk/src/share/classes/javax/swing/JScrollBar.java index f3001c017e5..230ba8081c7 100644 --- a/jdk/src/share/classes/javax/swing/JScrollBar.java +++ b/jdk/src/share/classes/javax/swing/JScrollBar.java @@ -77,6 +77,7 @@ import java.io.IOException; * description: A component that helps determine the visible content range of an area. * * @author David Kloba + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JScrollBar extends JComponent implements Adjustable, Accessible diff --git a/jdk/src/share/classes/javax/swing/JScrollPane.java b/jdk/src/share/classes/javax/swing/JScrollPane.java index 444a1c22526..373523e936e 100644 --- a/jdk/src/share/classes/javax/swing/JScrollPane.java +++ b/jdk/src/share/classes/javax/swing/JScrollPane.java @@ -167,6 +167,7 @@ import java.beans.Transient; * description: A specialized container that manages a viewport, optional scrollbars and headers * * @author Hans Muller + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JScrollPane extends JComponent implements ScrollPaneConstants, Accessible diff --git a/jdk/src/share/classes/javax/swing/JSeparator.java b/jdk/src/share/classes/javax/swing/JSeparator.java index 179c7fe91af..2614096679b 100644 --- a/jdk/src/share/classes/javax/swing/JSeparator.java +++ b/jdk/src/share/classes/javax/swing/JSeparator.java @@ -70,6 +70,7 @@ import java.io.IOException; * * @author Georges Saab * @author Jeff Shapiro + * @since 1.2 */ @SuppressWarnings("serial") public class JSeparator extends JComponent implements SwingConstants, Accessible diff --git a/jdk/src/share/classes/javax/swing/JSlider.java b/jdk/src/share/classes/javax/swing/JSlider.java index d75e1030634..09129a479f0 100644 --- a/jdk/src/share/classes/javax/swing/JSlider.java +++ b/jdk/src/share/classes/javax/swing/JSlider.java @@ -77,6 +77,7 @@ import java.beans.*; * description: A component that supports selecting a integer value from a range. * * @author David Kloba + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JSlider extends JComponent implements SwingConstants, Accessible { diff --git a/jdk/src/share/classes/javax/swing/JSplitPane.java b/jdk/src/share/classes/javax/swing/JSplitPane.java index 533d9a971af..072fefd8d3a 100644 --- a/jdk/src/share/classes/javax/swing/JSplitPane.java +++ b/jdk/src/share/classes/javax/swing/JSplitPane.java @@ -97,6 +97,7 @@ import java.io.IOException; * @see #resetToPreferredSizes * * @author Scott Violet + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JSplitPane extends JComponent implements Accessible diff --git a/jdk/src/share/classes/javax/swing/JTabbedPane.java b/jdk/src/share/classes/javax/swing/JTabbedPane.java index e5c303489c6..c3b135ac85e 100644 --- a/jdk/src/share/classes/javax/swing/JTabbedPane.java +++ b/jdk/src/share/classes/javax/swing/JTabbedPane.java @@ -105,6 +105,7 @@ import java.io.IOException; * @author Amy Fowler * * @see SingleSelectionModel + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JTabbedPane extends JComponent diff --git a/jdk/src/share/classes/javax/swing/JTable.java b/jdk/src/share/classes/javax/swing/JTable.java index 8d25315a03c..f4573926a95 100644 --- a/jdk/src/share/classes/javax/swing/JTable.java +++ b/jdk/src/share/classes/javax/swing/JTable.java @@ -212,6 +212,7 @@ import sun.swing.PrintingStatus; * @author Shannon Hickey (printing support) * @see javax.swing.table.DefaultTableModel * @see javax.swing.table.TableRowSorter + * @since 1.2 */ /* The first versions of the JTable, contained in Swing-0.1 through * Swing-0.4, were written by Alan Chung. diff --git a/jdk/src/share/classes/javax/swing/JTextArea.java b/jdk/src/share/classes/javax/swing/JTextArea.java index a6af9e241fa..96fb6b33e31 100644 --- a/jdk/src/share/classes/javax/swing/JTextArea.java +++ b/jdk/src/share/classes/javax/swing/JTextArea.java @@ -123,6 +123,7 @@ import java.io.IOException; * @author Timothy Prinzing * @see JTextPane * @see JEditorPane + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JTextArea extends JTextComponent { diff --git a/jdk/src/share/classes/javax/swing/JTextField.java b/jdk/src/share/classes/javax/swing/JTextField.java index f50f6aa9be9..0e39cdbc955 100644 --- a/jdk/src/share/classes/javax/swing/JTextField.java +++ b/jdk/src/share/classes/javax/swing/JTextField.java @@ -160,6 +160,7 @@ import java.io.Serializable; * @see #setActionCommand * @see JPasswordField * @see #addActionListener + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JTextField extends JTextComponent implements SwingConstants { diff --git a/jdk/src/share/classes/javax/swing/JTextPane.java b/jdk/src/share/classes/javax/swing/JTextPane.java index 017f897177c..f9c2de42a65 100644 --- a/jdk/src/share/classes/javax/swing/JTextPane.java +++ b/jdk/src/share/classes/javax/swing/JTextPane.java @@ -78,6 +78,7 @@ import javax.swing.plaf.*; * * @author Timothy Prinzing * @see javax.swing.text.StyledEditorKit + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JTextPane extends JEditorPane { diff --git a/jdk/src/share/classes/javax/swing/JToggleButton.java b/jdk/src/share/classes/javax/swing/JToggleButton.java index 60c6f0cdf48..08ec0be8659 100644 --- a/jdk/src/share/classes/javax/swing/JToggleButton.java +++ b/jdk/src/share/classes/javax/swing/JToggleButton.java @@ -75,6 +75,7 @@ import java.io.IOException; * @see JRadioButton * @see JCheckBox * @author Jeff Dinkins + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JToggleButton extends AbstractButton implements Accessible { diff --git a/jdk/src/share/classes/javax/swing/JToolBar.java b/jdk/src/share/classes/javax/swing/JToolBar.java index 8229f1891da..6fff218430f 100644 --- a/jdk/src/share/classes/javax/swing/JToolBar.java +++ b/jdk/src/share/classes/javax/swing/JToolBar.java @@ -85,6 +85,7 @@ import java.util.Hashtable; * @author Georges Saab * @author Jeff Shapiro * @see Action + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JToolBar extends JComponent implements SwingConstants, Accessible diff --git a/jdk/src/share/classes/javax/swing/JToolTip.java b/jdk/src/share/classes/javax/swing/JToolTip.java index e5409121421..dad092dc5fd 100644 --- a/jdk/src/share/classes/javax/swing/JToolTip.java +++ b/jdk/src/share/classes/javax/swing/JToolTip.java @@ -66,6 +66,7 @@ import java.util.Objects; * @see JComponent#createToolTip * @author Dave Moore * @author Rich Shiavi + * @since 1.2 */ @SuppressWarnings("serial") public class JToolTip extends JComponent implements Accessible { diff --git a/jdk/src/share/classes/javax/swing/JTree.java b/jdk/src/share/classes/javax/swing/JTree.java index f78fa5533b9..dcdf7a58946 100644 --- a/jdk/src/share/classes/javax/swing/JTree.java +++ b/jdk/src/share/classes/javax/swing/JTree.java @@ -141,6 +141,7 @@ import static sun.swing.SwingUtilities2.Section.*; * @author Rob Davis * @author Ray Ryan * @author Scott Violet + * @since 1.2 */ @SuppressWarnings("serial") public class JTree extends JComponent implements Scrollable, Accessible diff --git a/jdk/src/share/classes/javax/swing/JViewport.java b/jdk/src/share/classes/javax/swing/JViewport.java index 5b019699ee6..2875d95918d 100644 --- a/jdk/src/share/classes/javax/swing/JViewport.java +++ b/jdk/src/share/classes/javax/swing/JViewport.java @@ -97,6 +97,7 @@ import java.io.Serializable; * @author Hans Muller * @author Philip Milne * @see JScrollPane + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class JViewport extends JComponent implements Accessible diff --git a/jdk/src/share/classes/javax/swing/JWindow.java b/jdk/src/share/classes/javax/swing/JWindow.java index 4de51d23a5c..cf95a417fd5 100644 --- a/jdk/src/share/classes/javax/swing/JWindow.java +++ b/jdk/src/share/classes/javax/swing/JWindow.java @@ -89,6 +89,7 @@ import javax.accessibility.*; * description: A toplevel window which has no system border or controls. * * @author David Kloba + * @since 1.2 */ @SuppressWarnings("serial") public class JWindow extends Window implements Accessible, diff --git a/jdk/src/share/classes/javax/swing/KeyStroke.java b/jdk/src/share/classes/javax/swing/KeyStroke.java index e9f846c3d9c..24969f76aec 100644 --- a/jdk/src/share/classes/javax/swing/KeyStroke.java +++ b/jdk/src/share/classes/javax/swing/KeyStroke.java @@ -60,6 +60,7 @@ import java.awt.event.KeyEvent; * * @author Arnaud Weber * @author David Mendenhall + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class KeyStroke extends AWTKeyStroke { diff --git a/jdk/src/share/classes/javax/swing/ListCellRenderer.java b/jdk/src/share/classes/javax/swing/ListCellRenderer.java index 8f389412158..79cfa2ac348 100644 --- a/jdk/src/share/classes/javax/swing/ListCellRenderer.java +++ b/jdk/src/share/classes/javax/swing/ListCellRenderer.java @@ -85,6 +85,7 @@ import java.awt.Component; * @see DefaultListCellRenderer * * @author Hans Muller + * @since 1.2 */ public interface ListCellRenderer { diff --git a/jdk/src/share/classes/javax/swing/ListModel.java b/jdk/src/share/classes/javax/swing/ListModel.java index 84d4b9025b5..231fa10b121 100644 --- a/jdk/src/share/classes/javax/swing/ListModel.java +++ b/jdk/src/share/classes/javax/swing/ListModel.java @@ -39,6 +39,7 @@ import javax.swing.event.ListDataListener; * * @author Hans Muller * @see JList + * @since 1.2 */ public interface ListModel { diff --git a/jdk/src/share/classes/javax/swing/ListSelectionModel.java b/jdk/src/share/classes/javax/swing/ListSelectionModel.java index 82e1fe8499f..c4d91a4b50d 100644 --- a/jdk/src/share/classes/javax/swing/ListSelectionModel.java +++ b/jdk/src/share/classes/javax/swing/ListSelectionModel.java @@ -41,6 +41,7 @@ import javax.swing.event.*; * @author Hans Muller * @author Philip Milne * @see DefaultListSelectionModel + * @since 1.2 */ public interface ListSelectionModel diff --git a/jdk/src/share/classes/javax/swing/LookAndFeel.java b/jdk/src/share/classes/javax/swing/LookAndFeel.java index 16f4308f263..30c4c83dfc9 100644 --- a/jdk/src/share/classes/javax/swing/LookAndFeel.java +++ b/jdk/src/share/classes/javax/swing/LookAndFeel.java @@ -147,6 +147,7 @@ import java.util.StringTokenizer; * * @author Tom Ball * @author Hans Muller + * @since 1.2 */ public abstract class LookAndFeel { diff --git a/jdk/src/share/classes/javax/swing/MenuElement.java b/jdk/src/share/classes/javax/swing/MenuElement.java index 7141da85223..916811e08eb 100644 --- a/jdk/src/share/classes/javax/swing/MenuElement.java +++ b/jdk/src/share/classes/javax/swing/MenuElement.java @@ -33,6 +33,7 @@ import java.awt.event.*; * to handle selection and navigation in menu hierarchies. * * @author Arnaud Weber + * @since 1.2 */ public interface MenuElement { diff --git a/jdk/src/share/classes/javax/swing/MenuSelectionManager.java b/jdk/src/share/classes/javax/swing/MenuSelectionManager.java index 67e35dc918e..8a691c1b9cd 100644 --- a/jdk/src/share/classes/javax/swing/MenuSelectionManager.java +++ b/jdk/src/share/classes/javax/swing/MenuSelectionManager.java @@ -36,6 +36,7 @@ import sun.swing.SwingUtilities2; * A MenuSelectionManager owns the selection in menu hierarchy. * * @author Arnaud Weber + * @since 1.2 */ public class MenuSelectionManager { private Vector selection = new Vector(); diff --git a/jdk/src/share/classes/javax/swing/MutableComboBoxModel.java b/jdk/src/share/classes/javax/swing/MutableComboBoxModel.java index 09fb03713fb..a98dea117a5 100644 --- a/jdk/src/share/classes/javax/swing/MutableComboBoxModel.java +++ b/jdk/src/share/classes/javax/swing/MutableComboBoxModel.java @@ -30,6 +30,7 @@ package javax.swing; * @param the type of the elements of this model * * @author Tom Santos + * @since 1.2 */ public interface MutableComboBoxModel extends ComboBoxModel { diff --git a/jdk/src/share/classes/javax/swing/OverlayLayout.java b/jdk/src/share/classes/javax/swing/OverlayLayout.java index 6f3735cd50f..b62bb5faf17 100644 --- a/jdk/src/share/classes/javax/swing/OverlayLayout.java +++ b/jdk/src/share/classes/javax/swing/OverlayLayout.java @@ -50,6 +50,7 @@ import java.io.Serializable; * Please see {@link java.beans.XMLEncoder}. * * @author Timothy Prinzing + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class OverlayLayout implements LayoutManager2,Serializable { diff --git a/jdk/src/share/classes/javax/swing/Painter.java b/jdk/src/share/classes/javax/swing/Painter.java index bd1b5a19d31..946819313cb 100644 --- a/jdk/src/share/classes/javax/swing/Painter.java +++ b/jdk/src/share/classes/javax/swing/Painter.java @@ -59,6 +59,7 @@ import java.awt.Graphics2D; *

    This interface makes no guarantees of threadsafety.

    * * @author rbair + * @since 1.7 */ public interface Painter { /** diff --git a/jdk/src/share/classes/javax/swing/PopupFactory.java b/jdk/src/share/classes/javax/swing/PopupFactory.java index 20b21c7a274..840d7d14962 100644 --- a/jdk/src/share/classes/javax/swing/PopupFactory.java +++ b/jdk/src/share/classes/javax/swing/PopupFactory.java @@ -25,10 +25,15 @@ package javax.swing; +import sun.awt.EmbeddedFrame; +import sun.awt.OSInfo; +import sun.swing.SwingAccessor; + import java.applet.Applet; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; +import java.security.AccessController; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -56,6 +61,16 @@ import static javax.swing.ClientPropertyKey.PopupFactory_FORCE_HEAVYWEIGHT_POPUP * @since 1.4 */ public class PopupFactory { + + static { + SwingAccessor.setPopupFactoryAccessor(new SwingAccessor.PopupFactoryAccessor() { + @Override + public Popup getHeavyWeightPopup(PopupFactory factory, Component owner, + Component contents, int ownerX, int ownerY) { + return factory.getPopup(owner, contents, ownerX, ownerY, HEAVY_WEIGHT_POPUP); + } + }); + } /** * The shared instanceof PopupFactory is per * AppContext. This is the key used in the @@ -226,7 +241,12 @@ public class PopupFactory { case MEDIUM_WEIGHT_POPUP: return getMediumWeightPopup(owner, contents, ownerX, ownerY); case HEAVY_WEIGHT_POPUP: - return getHeavyWeightPopup(owner, contents, ownerX, ownerY); + Popup popup = getHeavyWeightPopup(owner, contents, ownerX, ownerY); + if ((AccessController.doPrivileged(OSInfo.getOSTypeAction()) == + OSInfo.OSType.MACOSX) && (EmbeddedFrame.getAppletIfAncestorOf(owner) != null)) { + ((HeavyWeightPopup)popup).setCacheEnabled(false); + } + return popup; } return null; } @@ -294,6 +314,8 @@ public class PopupFactory { private static final Object heavyWeightPopupCacheKey = new StringBuffer("PopupFactory.heavyWeightPopupCache"); + private volatile boolean isCacheEnabled = true; + /** * Returns either a new or recycled Popup containing * the specified children. @@ -448,12 +470,23 @@ public class PopupFactory { } } + /** + * Enables or disables cache for current object. + */ + void setCacheEnabled(boolean enable) { + isCacheEnabled = enable; + } + // // Popup methods // public void hide() { super.hide(); - recycleHeavyWeightPopup(this); + if (isCacheEnabled) { + recycleHeavyWeightPopup(this); + } else { + this._dispose(); + } } /** diff --git a/jdk/src/share/classes/javax/swing/ProgressMonitor.java b/jdk/src/share/classes/javax/swing/ProgressMonitor.java index 889f30d734a..506b443b4f5 100644 --- a/jdk/src/share/classes/javax/swing/ProgressMonitor.java +++ b/jdk/src/share/classes/javax/swing/ProgressMonitor.java @@ -77,6 +77,7 @@ import javax.swing.text.*; * @see ProgressMonitorInputStream * @author James Gosling * @author Lynn Monsanto (accessibility) + * @since 1.2 */ public class ProgressMonitor implements Accessible { diff --git a/jdk/src/share/classes/javax/swing/ProgressMonitorInputStream.java b/jdk/src/share/classes/javax/swing/ProgressMonitorInputStream.java index 67fc068d15e..3edb0e1f35b 100644 --- a/jdk/src/share/classes/javax/swing/ProgressMonitorInputStream.java +++ b/jdk/src/share/classes/javax/swing/ProgressMonitorInputStream.java @@ -60,6 +60,7 @@ import java.awt.Component; * @see ProgressMonitor * @see JOptionPane * @author James Gosling + * @since 1.2 */ public class ProgressMonitorInputStream extends FilterInputStream { diff --git a/jdk/src/share/classes/javax/swing/Renderer.java b/jdk/src/share/classes/javax/swing/Renderer.java index e0c3d78305e..41203f29493 100644 --- a/jdk/src/share/classes/javax/swing/Renderer.java +++ b/jdk/src/share/classes/javax/swing/Renderer.java @@ -32,6 +32,7 @@ import java.awt.Component; * "rendering" (displaying) a value. * * @author Arnaud Weber + * @since 1.2 */ public interface Renderer { /** diff --git a/jdk/src/share/classes/javax/swing/RepaintManager.java b/jdk/src/share/classes/javax/swing/RepaintManager.java index 6e3def5ae99..c1340d17c5b 100644 --- a/jdk/src/share/classes/javax/swing/RepaintManager.java +++ b/jdk/src/share/classes/javax/swing/RepaintManager.java @@ -60,6 +60,7 @@ import sun.swing.SwingUtilities2.RepaintListener; * appropriate addDirtyRegion method. * * @author Arnaud Weber + * @since 1.2 */ public class RepaintManager { diff --git a/jdk/src/share/classes/javax/swing/RootPaneContainer.java b/jdk/src/share/classes/javax/swing/RootPaneContainer.java index cd000b07ef2..76dc2286f87 100644 --- a/jdk/src/share/classes/javax/swing/RootPaneContainer.java +++ b/jdk/src/share/classes/javax/swing/RootPaneContainer.java @@ -77,6 +77,7 @@ import java.awt.Container; * @see JInternalFrame * * @author Hans Muller + * @since 1.2 */ public interface RootPaneContainer { diff --git a/jdk/src/share/classes/javax/swing/ScrollPaneConstants.java b/jdk/src/share/classes/javax/swing/ScrollPaneConstants.java index 6fef77a1b4b..4f8c66f4ec6 100644 --- a/jdk/src/share/classes/javax/swing/ScrollPaneConstants.java +++ b/jdk/src/share/classes/javax/swing/ScrollPaneConstants.java @@ -30,6 +30,7 @@ package javax.swing; * Constants used with the JScrollPane component. * * @author Hans Muller + * @since 1.2 */ public interface ScrollPaneConstants { diff --git a/jdk/src/share/classes/javax/swing/ScrollPaneLayout.java b/jdk/src/share/classes/javax/swing/ScrollPaneLayout.java index 69b103f7c42..4d353253a3c 100644 --- a/jdk/src/share/classes/javax/swing/ScrollPaneLayout.java +++ b/jdk/src/share/classes/javax/swing/ScrollPaneLayout.java @@ -56,6 +56,7 @@ import java.io.Serializable; * @see JViewport * * @author Hans Muller + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class ScrollPaneLayout diff --git a/jdk/src/share/classes/javax/swing/Scrollable.java b/jdk/src/share/classes/javax/swing/Scrollable.java index cf2214bdbd2..c5956367fe6 100644 --- a/jdk/src/share/classes/javax/swing/Scrollable.java +++ b/jdk/src/share/classes/javax/swing/Scrollable.java @@ -39,6 +39,7 @@ import java.awt.Rectangle; * @see JScrollPane * @see JScrollBar * @author Hans Muller + * @since 1.2 */ public interface Scrollable { diff --git a/jdk/src/share/classes/javax/swing/SingleSelectionModel.java b/jdk/src/share/classes/javax/swing/SingleSelectionModel.java index becefe7c029..251b7c1d7e2 100644 --- a/jdk/src/share/classes/javax/swing/SingleSelectionModel.java +++ b/jdk/src/share/classes/javax/swing/SingleSelectionModel.java @@ -31,6 +31,7 @@ import javax.swing.event.*; * A model that supports at most one indexed selection. * * @author Dave Moore + * @since 1.2 */ public interface SingleSelectionModel { /** diff --git a/jdk/src/share/classes/javax/swing/SizeRequirements.java b/jdk/src/share/classes/javax/swing/SizeRequirements.java index d4a590bfd0f..a592ef6b563 100644 --- a/jdk/src/share/classes/javax/swing/SizeRequirements.java +++ b/jdk/src/share/classes/javax/swing/SizeRequirements.java @@ -92,6 +92,7 @@ import java.io.Serializable; * @see Component#getAlignmentY * * @author Timothy Prinzing + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class SizeRequirements implements Serializable { diff --git a/jdk/src/share/classes/javax/swing/SwingConstants.java b/jdk/src/share/classes/javax/swing/SwingConstants.java index 1865fec54bf..390d2e6b828 100644 --- a/jdk/src/share/classes/javax/swing/SwingConstants.java +++ b/jdk/src/share/classes/javax/swing/SwingConstants.java @@ -31,6 +31,7 @@ package javax.swing; * * @author Jeff Dinkins * @author Ralph Kar (orientation support) + * @since 1.2 */ public interface SwingConstants { diff --git a/jdk/src/share/classes/javax/swing/SwingUtilities.java b/jdk/src/share/classes/javax/swing/SwingUtilities.java index 99c4d8b0d67..fb7b2820fd2 100644 --- a/jdk/src/share/classes/javax/swing/SwingUtilities.java +++ b/jdk/src/share/classes/javax/swing/SwingUtilities.java @@ -49,6 +49,7 @@ import sun.awt.AppContext; * A collection of utility methods for Swing. * * @author unknown + * @since 1.2 */ public class SwingUtilities implements SwingConstants { diff --git a/jdk/src/share/classes/javax/swing/Timer.java b/jdk/src/share/classes/javax/swing/Timer.java index 5ef34add10e..2c25598b88c 100644 --- a/jdk/src/share/classes/javax/swing/Timer.java +++ b/jdk/src/share/classes/javax/swing/Timer.java @@ -145,6 +145,7 @@ import javax.swing.event.EventListenerList; * * * @author Dave Moore + * @since 1.2 */ @SuppressWarnings("serial") public class Timer implements Serializable diff --git a/jdk/src/share/classes/javax/swing/ToolTipManager.java b/jdk/src/share/classes/javax/swing/ToolTipManager.java index 6a3954f7ecc..b127284be09 100644 --- a/jdk/src/share/classes/javax/swing/ToolTipManager.java +++ b/jdk/src/share/classes/javax/swing/ToolTipManager.java @@ -49,6 +49,7 @@ import java.awt.*; * @see JComponent#createToolTip * @author Dave Moore * @author Rich Schiavi + * @since 1.2 */ public class ToolTipManager extends MouseAdapter implements MouseMotionListener { Timer enterTimer, exitTimer, insideTimer; diff --git a/jdk/src/share/classes/javax/swing/UIDefaults.java b/jdk/src/share/classes/javax/swing/UIDefaults.java index b6797bd232f..257c5e71a22 100644 --- a/jdk/src/share/classes/javax/swing/UIDefaults.java +++ b/jdk/src/share/classes/javax/swing/UIDefaults.java @@ -71,6 +71,7 @@ import sun.util.CoreResourceBundleControl; * * @see UIManager * @author Hans Muller + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class UIDefaults extends Hashtable diff --git a/jdk/src/share/classes/javax/swing/UIManager.java b/jdk/src/share/classes/javax/swing/UIManager.java index 026f8a7b80f..951d0f6c239 100644 --- a/jdk/src/share/classes/javax/swing/UIManager.java +++ b/jdk/src/share/classes/javax/swing/UIManager.java @@ -173,6 +173,7 @@ import sun.awt.AWTAccessor; * * @author Thomas Ball * @author Hans Muller + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class UIManager implements Serializable diff --git a/jdk/src/share/classes/javax/swing/UnsupportedLookAndFeelException.java b/jdk/src/share/classes/javax/swing/UnsupportedLookAndFeelException.java index 07b8e18c6ff..e28166cd2db 100644 --- a/jdk/src/share/classes/javax/swing/UnsupportedLookAndFeelException.java +++ b/jdk/src/share/classes/javax/swing/UnsupportedLookAndFeelException.java @@ -38,6 +38,7 @@ package javax.swing; * Please see {@link java.beans.XMLEncoder}. * * @author unattributed + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class UnsupportedLookAndFeelException extends Exception diff --git a/jdk/src/share/classes/javax/swing/ViewportLayout.java b/jdk/src/share/classes/javax/swing/ViewportLayout.java index 2aa83bede3e..f2a01f0771b 100644 --- a/jdk/src/share/classes/javax/swing/ViewportLayout.java +++ b/jdk/src/share/classes/javax/swing/ViewportLayout.java @@ -55,6 +55,7 @@ import java.io.Serializable; * Please see {@link java.beans.XMLEncoder}. * * @author Hans Muller + * @since 1.2 */ @SuppressWarnings("serial") // Same-version serialization only public class ViewportLayout implements LayoutManager, Serializable diff --git a/jdk/src/share/classes/javax/swing/WindowConstants.java b/jdk/src/share/classes/javax/swing/WindowConstants.java index 6b1fdb3c15b..9ed3eb84628 100644 --- a/jdk/src/share/classes/javax/swing/WindowConstants.java +++ b/jdk/src/share/classes/javax/swing/WindowConstants.java @@ -44,6 +44,7 @@ package javax.swing; * * * @author Amy Fowler + * @since 1.2 */ public interface WindowConstants { diff --git a/jdk/src/share/classes/javax/swing/event/AncestorEvent.java b/jdk/src/share/classes/javax/swing/event/AncestorEvent.java index a113ebe4c0b..d6f7ab08c28 100644 --- a/jdk/src/share/classes/javax/swing/event/AncestorEvent.java +++ b/jdk/src/share/classes/javax/swing/event/AncestorEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -81,6 +81,8 @@ public class AncestorEvent extends AWTEvent { /** * Returns the ancestor that the event actually occurred on. + * + * @return the {@code Container} object specifying the ancestor component */ public Container getAncestor() { return ancestor; @@ -90,6 +92,8 @@ public class AncestorEvent extends AWTEvent { * Returns the parent of the ancestor the event actually occurred on. * This is most interesting in an ANCESTOR_REMOVED event, as * the ancestor may no longer be in the component hierarchy. + * + * @return the {@code Container} object specifying the ancestor's parent */ public Container getAncestorParent() { return ancestorParent; @@ -97,6 +101,8 @@ public class AncestorEvent extends AWTEvent { /** * Returns the component that the listener was added to. + * + * @return the {@code JComponent} on which the event occurred */ public JComponent getComponent() { return (JComponent)getSource(); diff --git a/jdk/src/share/classes/javax/swing/event/AncestorListener.java b/jdk/src/share/classes/javax/swing/event/AncestorListener.java index d0b07bdbfea..30dd3cfc4f1 100644 --- a/jdk/src/share/classes/javax/swing/event/AncestorListener.java +++ b/jdk/src/share/classes/javax/swing/event/AncestorListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -48,6 +48,9 @@ public interface AncestorListener extends EventListener { * if the source has actually become visible. For this to be true * all its parents must be visible and it must be in a hierarchy * rooted at a Window + * + * @param event an {@code AncestorEvent} signifying a change in an + * ancestor-component's display-status */ public void ancestorAdded(AncestorEvent event); @@ -58,11 +61,17 @@ public interface AncestorListener extends EventListener { * if the source has actually become invisible. For this to be true * at least one of its parents must by invisible or it is not in * a hierarchy rooted at a Window + * + * @param event an {@code AncestorEvent} signifying a change in an + * ancestor-component's display-status */ public void ancestorRemoved(AncestorEvent event); /** * Called when either the source or one of its ancestors is moved. + * + * @param event an {@code AncestorEvent} signifying a change in an + * ancestor-component's display-status */ public void ancestorMoved(AncestorEvent event); diff --git a/jdk/src/share/classes/javax/swing/event/CellEditorListener.java b/jdk/src/share/classes/javax/swing/event/CellEditorListener.java index fabeca11f62..817e6ea2441 100644 --- a/jdk/src/share/classes/javax/swing/event/CellEditorListener.java +++ b/jdk/src/share/classes/javax/swing/event/CellEditorListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,9 +37,17 @@ import java.util.EventListener; public interface CellEditorListener extends java.util.EventListener { - /** This tells the listeners the editor has ended editing */ + /** + * This tells the listeners the editor has ended editing + * + * @param e the {@code ChangeEvent} containing the source of the event + */ public void editingStopped(ChangeEvent e); - /** This tells the listeners the editor has canceled editing */ + /** + * This tells the listeners the editor has canceled editing + * + * @param e the {@code ChangeEvent} containing the source of the event + */ public void editingCanceled(ChangeEvent e); } diff --git a/jdk/src/share/classes/javax/swing/event/EventListenerList.java b/jdk/src/share/classes/javax/swing/event/EventListenerList.java index 9e145daa251..ccde0bfef76 100644 --- a/jdk/src/share/classes/javax/swing/event/EventListenerList.java +++ b/jdk/src/share/classes/javax/swing/event/EventListenerList.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -120,6 +120,8 @@ public class EventListenerList implements Serializable { * any such manipulation is necessary, it should be done * on a copy of the array returned rather than the array * itself. + * + * @return array of ListenerType-listener pairs */ public Object[] getListenerList() { return listenerList; @@ -127,6 +129,9 @@ public class EventListenerList implements Serializable { /** * Return an array of all the listeners of the given type. + * + * @param the type of {@code EventListener} to search for + * @param t the type of {@code EventListener} classes to be returned * @return all of the listeners of the specified type. * @exception ClassCastException if the supplied class * is not assignable to EventListener @@ -148,6 +153,8 @@ public class EventListenerList implements Serializable { /** * Returns the total number of listeners for this listener list. + * + * @return an integer count of total number of listeners */ public int getListenerCount() { return listenerList.length/2; @@ -156,6 +163,9 @@ public class EventListenerList implements Serializable { /** * Returns the total number of listeners of the supplied type * for this listener list. + * + * @param t the type of listeners to count + * @return the number of listeners of type {@code t} */ public int getListenerCount(Class t) { Object[] lList = listenerList; @@ -173,7 +183,9 @@ public class EventListenerList implements Serializable { /** * Adds the listener as a listener of the specified type. - * @param t the type of the listener to be added + * + * @param the type of {@code EventListener} to add + * @param t the type of the {@code EventListener} class to add * @param l the listener to be added */ public synchronized void add(Class t, T l) { @@ -206,6 +218,8 @@ public class EventListenerList implements Serializable { /** * Removes the listener as a listener of the specified type. + * + * @param the type of {@code EventListener} * @param t the type of the listener to be removed * @param l the listener to be removed */ diff --git a/jdk/src/share/classes/javax/swing/event/HyperlinkEvent.java b/jdk/src/share/classes/javax/swing/event/HyperlinkEvent.java index 848910188e9..bcd7ea60063 100644 --- a/jdk/src/share/classes/javax/swing/event/HyperlinkEvent.java +++ b/jdk/src/share/classes/javax/swing/event/HyperlinkEvent.java @@ -142,6 +142,8 @@ public class HyperlinkEvent extends EventObject { * This may be useful if a URL can't be formed * from the description, in which case the associated * URL would be null. + * + * @return the description of this link as a {@code String} */ public String getDescription() { return desc; diff --git a/jdk/src/share/classes/javax/swing/event/InternalFrameListener.java b/jdk/src/share/classes/javax/swing/event/InternalFrameListener.java index 151c4978630..433f20e6227 100644 --- a/jdk/src/share/classes/javax/swing/event/InternalFrameListener.java +++ b/jdk/src/share/classes/javax/swing/event/InternalFrameListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,6 +42,9 @@ import java.util.EventListener; public interface InternalFrameListener extends EventListener { /** * Invoked when a internal frame has been opened. + * + * @param e an {@code InternalFrameEvent} with information about the + * {@code JInteralFrame} that originated the event * @see javax.swing.JInternalFrame#show */ public void internalFrameOpened(InternalFrameEvent e); @@ -49,36 +52,54 @@ public interface InternalFrameListener extends EventListener { /** * Invoked when an internal frame is in the process of being closed. * The close operation can be overridden at this point. + * + * @param e an {@code InternalFrameEvent} with information about the + * {@code JInteralFrame} that originated the event * @see javax.swing.JInternalFrame#setDefaultCloseOperation */ public void internalFrameClosing(InternalFrameEvent e); /** * Invoked when an internal frame has been closed. + * + * @param e an {@code InternalFrameEvent} with information about the + * {@code JInteralFrame} that originated the event * @see javax.swing.JInternalFrame#setClosed */ public void internalFrameClosed(InternalFrameEvent e); /** * Invoked when an internal frame is iconified. + * + * @param e an {@code InternalFrameEvent} with information about the + * {@code JInteralFrame} that originated the event * @see javax.swing.JInternalFrame#setIcon */ public void internalFrameIconified(InternalFrameEvent e); /** * Invoked when an internal frame is de-iconified. + * + * @param e an {@code InternalFrameEvent} with information about the + * {@code JInteralFrame} that originated the event * @see javax.swing.JInternalFrame#setIcon */ public void internalFrameDeiconified(InternalFrameEvent e); /** * Invoked when an internal frame is activated. + * + * @param e an {@code InternalFrameEvent} with information about the + * {@code JInteralFrame} that originated the event * @see javax.swing.JInternalFrame#setSelected */ public void internalFrameActivated(InternalFrameEvent e); /** * Invoked when an internal frame is de-activated. + * + * @param e an {@code InternalFrameEvent} with information about the + * {@code JInteralFrame} that originated the event * @see javax.swing.JInternalFrame#setSelected */ public void internalFrameDeactivated(InternalFrameEvent e); diff --git a/jdk/src/share/classes/javax/swing/event/ListSelectionEvent.java b/jdk/src/share/classes/javax/swing/event/ListSelectionEvent.java index a5128f1e47c..735b5797088 100644 --- a/jdk/src/share/classes/javax/swing/event/ListSelectionEvent.java +++ b/jdk/src/share/classes/javax/swing/event/ListSelectionEvent.java @@ -63,6 +63,7 @@ public class ListSelectionEvent extends EventObject * {@code lastIndex}. The selection of at least one index within the range will * have changed. * + * @param source the {@code Object} on which the event initially occurred * @param firstIndex the first index in the range, <= lastIndex * @param lastIndex the last index in the range, >= firstIndex * @param isAdjusting whether or not this is one in a series of diff --git a/jdk/src/share/classes/javax/swing/event/MenuKeyListener.java b/jdk/src/share/classes/javax/swing/event/MenuKeyListener.java index 7caaf2a609f..3abcced7815 100644 --- a/jdk/src/share/classes/javax/swing/event/MenuKeyListener.java +++ b/jdk/src/share/classes/javax/swing/event/MenuKeyListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,16 +37,22 @@ public interface MenuKeyListener extends EventListener { /** * Invoked when a key has been typed. * This event occurs when a key press is followed by a key release. + * + * @param e a {@code MenuKeyEvent} */ void menuKeyTyped(MenuKeyEvent e); /** * Invoked when a key has been pressed. + * + * @param e a {@code MenuKeyEvent} */ void menuKeyPressed(MenuKeyEvent e); /** * Invoked when a key has been released. + * + * @param e a {@code MenuKeyEvent} */ void menuKeyReleased(MenuKeyEvent e); } diff --git a/jdk/src/share/classes/javax/swing/event/PopupMenuEvent.java b/jdk/src/share/classes/javax/swing/event/PopupMenuEvent.java index 0668371939f..4431dcc0642 100644 --- a/jdk/src/share/classes/javax/swing/event/PopupMenuEvent.java +++ b/jdk/src/share/classes/javax/swing/event/PopupMenuEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,7 @@ package javax.swing.event; import java.util.EventObject; /** - * PopupMenuEvent only contains the source of the event which is the JPoupMenu + * PopupMenuEvent only contains the source of the event which is the JPopupMenu * sending the event *

    * Warning: diff --git a/jdk/src/share/classes/javax/swing/event/PopupMenuListener.java b/jdk/src/share/classes/javax/swing/event/PopupMenuListener.java index 4f8b5223664..6f498733f27 100644 --- a/jdk/src/share/classes/javax/swing/event/PopupMenuListener.java +++ b/jdk/src/share/classes/javax/swing/event/PopupMenuListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,17 +35,23 @@ public interface PopupMenuListener extends EventListener { /** * This method is called before the popup menu becomes visible + * + * @param e a {@code PopupMenuEvent} containing the source of the event */ void popupMenuWillBecomeVisible(PopupMenuEvent e); /** * This method is called before the popup menu becomes invisible * Note that a JPopupMenu can become invisible any time + * + * @param e a {@code PopupMenuEvent} containing the source of the event */ void popupMenuWillBecomeInvisible(PopupMenuEvent e); /** * This method is called when the popup menu is canceled + * + * @param e a {@code PopupMenuEvent} containing the source of the event */ void popupMenuCanceled(PopupMenuEvent e); } diff --git a/jdk/src/share/classes/javax/swing/event/TableColumnModelEvent.java b/jdk/src/share/classes/javax/swing/event/TableColumnModelEvent.java index 1958ded5e39..7293238671b 100644 --- a/jdk/src/share/classes/javax/swing/event/TableColumnModelEvent.java +++ b/jdk/src/share/classes/javax/swing/event/TableColumnModelEvent.java @@ -83,9 +83,17 @@ public class TableColumnModelEvent extends java.util.EventObject // Querying Methods // - /** Returns the fromIndex. Valid for removed or moved events */ + /** + * Returns the fromIndex. Valid for removed or moved events + * + * @return int value for index from which the column was moved or removed + */ public int getFromIndex() { return fromIndex; }; - /** Returns the toIndex. Valid for add and moved events */ + /** + * Returns the toIndex. Valid for add and moved events + * + * @return int value of column's new index + */ public int getToIndex() { return toIndex; }; } diff --git a/jdk/src/share/classes/javax/swing/event/TableColumnModelListener.java b/jdk/src/share/classes/javax/swing/event/TableColumnModelListener.java index ccd6e5dd88d..deabfe7e8ba 100644 --- a/jdk/src/share/classes/javax/swing/event/TableColumnModelListener.java +++ b/jdk/src/share/classes/javax/swing/event/TableColumnModelListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,21 +39,39 @@ import java.util.EventListener; public interface TableColumnModelListener extends java.util.EventListener { - /** Tells listeners that a column was added to the model. */ + /** + * Tells listeners that a column was added to the model. + * + * @param e a {@code TableColumnModelEvent} + */ public void columnAdded(TableColumnModelEvent e); - /** Tells listeners that a column was removed from the model. */ + /** + * Tells listeners that a column was removed from the model. + * + * @param e a {@code TableColumnModelEvent} + */ public void columnRemoved(TableColumnModelEvent e); - /** Tells listeners that a column was repositioned. */ + /** + * Tells listeners that a column was repositioned. + * + * @param e a {@code TableColumnModelEvent} + */ public void columnMoved(TableColumnModelEvent e); - /** Tells listeners that a column was moved due to a margin change. */ + /** + * Tells listeners that a column was moved due to a margin change. + * + * @param e a {@code ChangeEvent} + */ public void columnMarginChanged(ChangeEvent e); /** * Tells listeners that the selection model of the * TableColumnModel changed. + * + * @param e a {@code ListSelectionEvent} */ public void columnSelectionChanged(ListSelectionEvent e); } diff --git a/jdk/src/share/classes/javax/swing/event/TableModelEvent.java b/jdk/src/share/classes/javax/swing/event/TableModelEvent.java index 0247f992a4d..bf6555c4aac 100644 --- a/jdk/src/share/classes/javax/swing/event/TableModelEvent.java +++ b/jdk/src/share/classes/javax/swing/event/TableModelEvent.java @@ -95,13 +95,15 @@ public class TableModelEvent extends java.util.EventObject // /** - * All row data in the table has changed, listeners should discard any state - * that was based on the rows and requery the TableModel - * to get the new row count and all the appropriate values. - * The JTable will repaint the entire visible region on - * receiving this event, querying the model for the cell values that are visible. - * The structure of the table ie, the column names, types and order - * have not changed. + * All row data in the table has changed, listeners should discard any state + * that was based on the rows and requery the TableModel + * to get the new row count and all the appropriate values. + * The JTable will repaint the entire visible region on + * receiving this event, querying the model for the cell values that are visible. + * The structure of the table ie, the column names, types and order + * have not changed. + * + * @param source the {@code TableModel} affected by this event */ public TableModelEvent(TableModel source) { // Use Integer.MAX_VALUE instead of getRowCount() in case rows were deleted. @@ -109,21 +111,28 @@ public class TableModelEvent extends java.util.EventObject } /** - * This row of data has been updated. - * To denote the arrival of a completely new table with a different structure - * use HEADER_ROW as the value for the row. - * When the JTable receives this event and its - * autoCreateColumnsFromModel - * flag is set it discards any TableColumns that it had and reallocates - * default ones in the order they appear in the model. This is the - * same as calling setModel(TableModel) on the JTable. + * This row of data has been updated. + * To denote the arrival of a completely new table with a different structure + * use HEADER_ROW as the value for the row. + * When the JTable receives this event and its + * autoCreateColumnsFromModel + * flag is set it discards any TableColumns that it had and reallocates + * default ones in the order they appear in the model. This is the + * same as calling setModel(TableModel) on the JTable. + * + * @param source the {@code TableModel} affected by this event + * @param row the row which has been updated */ public TableModelEvent(TableModel source, int row) { this(source, row, row, ALL_COLUMNS, UPDATE); } /** - * The data in rows [firstRow, lastRow] have been updated. + * The data in rows [firstRow, lastRow] have been updated. + * + * @param source the {@code TableModel} affected by this event + * @param firstRow the first row affected by this event + * @param lastRow the last row affected by this event */ public TableModelEvent(TableModel source, int firstRow, int lastRow) { this(source, firstRow, lastRow, ALL_COLUMNS, UPDATE); @@ -132,18 +141,32 @@ public class TableModelEvent extends java.util.EventObject /** * The cells in column column in the range * [firstRow, lastRow] have been updated. + * + * @param source the {@code TableModel} affected by this event + * @param firstRow the first row affected by this event + * @param lastRow the last row affected by this event + * @param column the column index of cells changed; {@code ALL_COLUMNS} + * signifies all cells in the specified range of rows are changed. */ public TableModelEvent(TableModel source, int firstRow, int lastRow, int column) { this(source, firstRow, lastRow, column, UPDATE); } /** - * The cells from (firstRow, column) to (lastRow, column) have been changed. - * The column refers to the column index of the cell in the model's - * co-ordinate system. When column is ALL_COLUMNS, all cells in the - * specified range of rows are considered changed. - *

    - * The type should be one of: INSERT, UPDATE and DELETE. + * The cells from (firstRow, column) to (lastRow, column) have been changed. + * The column refers to the column index of the cell in the model's + * co-ordinate system. When column is ALL_COLUMNS, all cells in the + * specified range of rows are considered changed. + *

    + * The type should be one of: INSERT, UPDATE and DELETE. + * + * @param source the {@code TableModel} affected by this event + * @param firstRow the first row affected by this event + * @param lastRow the last row affected by this event + * @param column the column index of cells changed; {@code ALL_COLUMNS} + * signifies all cells in the specified range of rows are changed. + * @param type the type of change signified by this even, @code INSERT}, + * {@code DELETE } or {@code UPDATE} */ public TableModelEvent(TableModel source, int firstRow, int lastRow, int column, int type) { super(source); @@ -157,23 +180,36 @@ public class TableModelEvent extends java.util.EventObject // Querying Methods // - /** Returns the first row that changed. HEADER_ROW means the meta data, + /** + * Returns the first row that changed. HEADER_ROW means the meta data, * ie. names, types and order of the columns. + * + * @return an integer signifying the first row changed */ public int getFirstRow() { return firstRow; }; - /** Returns the last row that changed. */ + /** + * Returns the last row that changed. + * + * @return an integer signifying the last row changed + */ public int getLastRow() { return lastRow; }; /** * Returns the column for the event. If the return * value is ALL_COLUMNS; it means every column in the specified * rows changed. + * + * @return an integer signifying which column is affected by this event */ public int getColumn() { return column; }; /** * Returns the type of event - one of: INSERT, UPDATE and DELETE. + * + * @return the type of change to a table model, an {@code INSERT} or + * {@code DELETE } of row(s) or column(s) or {@code UPDATE} + * to data */ public int getType() { return type; } } diff --git a/jdk/src/share/classes/javax/swing/event/TableModelListener.java b/jdk/src/share/classes/javax/swing/event/TableModelListener.java index 9dce6700238..e32c2ef84f5 100644 --- a/jdk/src/share/classes/javax/swing/event/TableModelListener.java +++ b/jdk/src/share/classes/javax/swing/event/TableModelListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,6 +40,9 @@ public interface TableModelListener extends java.util.EventListener /** * This fine grain notification tells listeners the exact range * of cells, rows, or columns that changed. + * + * @param e a {@code TableModelEvent} to notify listener that a table model + * has changed */ public void tableChanged(TableModelEvent e); } diff --git a/jdk/src/share/classes/javax/swing/event/TreeExpansionEvent.java b/jdk/src/share/classes/javax/swing/event/TreeExpansionEvent.java index 1e70200b2e7..7f8f37a1d5d 100644 --- a/jdk/src/share/classes/javax/swing/event/TreeExpansionEvent.java +++ b/jdk/src/share/classes/javax/swing/event/TreeExpansionEvent.java @@ -54,7 +54,7 @@ public class TreeExpansionEvent extends EventObject /** * Path to the value this event represents. */ - protected TreePath path; + protected TreePath path; /** * Constructs a TreeExpansionEvent object. @@ -71,6 +71,8 @@ public class TreeExpansionEvent extends EventObject /** * Returns the path to the value that has been expanded/collapsed. + * + * @return this event's {@code TreePath} object */ public TreePath getPath() { return path; } } diff --git a/jdk/src/share/classes/javax/swing/event/TreeExpansionListener.java b/jdk/src/share/classes/javax/swing/event/TreeExpansionListener.java index 915dcf942f9..a71ac4045c0 100644 --- a/jdk/src/share/classes/javax/swing/event/TreeExpansionListener.java +++ b/jdk/src/share/classes/javax/swing/event/TreeExpansionListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,12 +41,18 @@ import java.util.EventListener; public interface TreeExpansionListener extends EventListener { /** - * Called whenever an item in the tree has been expanded. - */ + * Called whenever an item in the tree has been expanded. + * + * @param event a {@code TreeExpansionEvent} containing a {@code TreePath} + * object for the expanded node + */ public void treeExpanded(TreeExpansionEvent event); /** - * Called whenever an item in the tree has been collapsed. - */ + * Called whenever an item in the tree has been collapsed. + * + * @param event a {@code TreeExpansionEvent} containing a {@code TreePath} + * object for the collapsed node + */ public void treeCollapsed(TreeExpansionEvent event); } diff --git a/jdk/src/share/classes/javax/swing/event/TreeModelListener.java b/jdk/src/share/classes/javax/swing/event/TreeModelListener.java index d89c2a39ef0..22712810fda 100644 --- a/jdk/src/share/classes/javax/swing/event/TreeModelListener.java +++ b/jdk/src/share/classes/javax/swing/event/TreeModelListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,25 +46,26 @@ public interface TreeModelListener extends EventListener { * altered their children arrays, but other attributes have * changed and may affect presentation. Example: the name of a * file has changed, but it is in the same location in the file - * system.

    - *

    To indicate the root has changed, childIndices and children - * will be null.

    + * system. * - *

    Use e.getPath() - * to get the parent of the changed node(s). - * e.getChildIndices() - * returns the index(es) of the changed node(s).

    + *

    To indicate the root has changed, childIndices and children + * will be null. + * + *

    Use {@code e.getPath()} to get the parent of the changed node(s). + * {@code e.getChildIndices()} returns the index(es) of the changed node(s). + * + * @param e a {@code TreeModelEvent} describing changes to a tree model */ void treeNodesChanged(TreeModelEvent e); /** *

    Invoked after nodes have been inserted into the tree.

    * - *

    Use e.getPath() - * to get the parent of the new node(s). - * e.getChildIndices() - * returns the index(es) of the new node(s) - * in ascending order.

    + *

    Use {@code e.getPath()} to get the parent of the new node(s). + * {@code e.getChildIndices()} returns the index(es) of the new node(s) + * in ascending order. + * + * @param e a {@code TreeModelEvent} describing changes to a tree model */ void treeNodesInserted(TreeModelEvent e); @@ -74,11 +75,11 @@ public interface TreeModelListener extends EventListener { * invoked once for the root of the removed subtree, not once for * each individual set of siblings removed.

    * - *

    Use e.getPath() - * to get the former parent of the deleted node(s). - * e.getChildIndices() - * returns, in ascending order, the index(es) - * the node(s) had before being deleted.

    + *

    Use {@code e.getPath()} to get the former parent of the deleted + * node(s). {@code e.getChildIndices()} returns, in ascending order, the + * index(es) the node(s) had before being deleted. + * + * @param e a {@code TreeModelEvent} describing changes to a tree model */ void treeNodesRemoved(TreeModelEvent e); @@ -88,10 +89,10 @@ public interface TreeModelListener extends EventListener { * one and the first element does not identify the current root node * the first element should become the new root of the tree. * - *

    Use e.getPath() - * to get the path to the node. - * e.getChildIndices() - * returns null.

    + *

    Use {@code e.getPath()} to get the path to the node. + * {@code e.getChildIndices()} returns null. + * + * @param e a {@code TreeModelEvent} describing changes to a tree model */ void treeStructureChanged(TreeModelEvent e); diff --git a/jdk/src/share/classes/javax/swing/event/TreeSelectionEvent.java b/jdk/src/share/classes/javax/swing/event/TreeSelectionEvent.java index 792ce190509..32de1e9f517 100644 --- a/jdk/src/share/classes/javax/swing/event/TreeSelectionEvent.java +++ b/jdk/src/share/classes/javax/swing/event/TreeSelectionEvent.java @@ -62,12 +62,16 @@ public class TreeSelectionEvent extends EventObject protected TreePath newLeadSelectionPath; /** - * Represents a change in the selection of a TreeSelectionModel. - * paths identifies the paths that have been either added or + * Represents a change in the selection of a {@code TreeSelectionModel}. + * {@code paths} identifies the paths that have been either added or * removed from the selection. * * @param source source of event * @param paths the paths that have changed in the selection + * @param areNew a {@code boolean} array indicating whether the paths in + * {@code paths} are new to the selection + * @param oldLeadSelectionPath the previous lead selection path + * @param newLeadSelectionPath the new lead selection path */ public TreeSelectionEvent(Object source, TreePath[] paths, boolean[] areNew, TreePath oldLeadSelectionPath, @@ -81,14 +85,16 @@ public class TreeSelectionEvent extends EventObject } /** - * Represents a change in the selection of a TreeSelectionModel. - * path identifies the path that have been either added or + * Represents a change in the selection of a {@code TreeSelectionModel}. + * {@code path} identifies the path that has been either added or * removed from the selection. * * @param source source of event * @param path the path that has changed in the selection * @param isNew whether or not the path is new to the selection, false - * means path was removed from the selection. + * means path was removed from the selection. + * @param oldLeadSelectionPath the previous lead selection path + * @param newLeadSelectionPath the new lead selection path */ public TreeSelectionEvent(Object source, TreePath path, boolean isNew, TreePath oldLeadSelectionPath, @@ -104,8 +110,9 @@ public class TreeSelectionEvent extends EventObject } /** - * Returns the paths that have been added or removed from the - * selection. + * Returns the paths that have been added or removed from the selection. + * + * @return copy of the array of {@code TreePath} obects for this event. */ public TreePath[] getPaths() { @@ -120,6 +127,8 @@ public class TreeSelectionEvent extends EventObject /** * Returns the first path element. + * + * @return the first {@code TreePath} element represented by this event */ public TreePath getPath() { @@ -187,6 +196,8 @@ public class TreeSelectionEvent extends EventObject /** * Returns the path that was previously the lead path. + * + * @return a {@code TreePath} containing the old lead selection path */ public TreePath getOldLeadSelectionPath() { return oldLeadSelectionPath; @@ -194,6 +205,8 @@ public class TreeSelectionEvent extends EventObject /** * Returns the current lead path. + * + * @return a {@code TreePath} containing the new lead selection path */ public TreePath getNewLeadSelectionPath() { return newLeadSelectionPath; @@ -201,10 +214,14 @@ public class TreeSelectionEvent extends EventObject /** * Returns a copy of the receiver, but with the source being newSource. + * + * @param newSource source of event + * @return an {@code Object} which is a copy of this event with the source + * being the {@code newSource} provided */ public Object cloneWithSource(Object newSource) { // Fix for IE bug - crashing - return new TreeSelectionEvent(newSource, paths,areNew, + return new TreeSelectionEvent(newSource, paths, areNew, oldLeadSelectionPath, newLeadSelectionPath); } diff --git a/jdk/src/share/classes/javax/swing/event/TreeWillExpandListener.java b/jdk/src/share/classes/javax/swing/event/TreeWillExpandListener.java index 6fd170c862a..ad5691220ef 100644 --- a/jdk/src/share/classes/javax/swing/event/TreeWillExpandListener.java +++ b/jdk/src/share/classes/javax/swing/event/TreeWillExpandListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,11 +41,19 @@ import javax.swing.tree.ExpandVetoException; public interface TreeWillExpandListener extends EventListener { /** * Invoked whenever a node in the tree is about to be expanded. + * + * @param event a {@code TreeExpansionEvent} containing a {@code TreePath} + * object for the node + * @throws ExpandVetoException to signify expansion has been canceled */ public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException; /** * Invoked whenever a node in the tree is about to be collapsed. + * + * @param event a {@code TreeExpansionEvent} containing a {@code TreePath} + * object for the node + * @throws ExpandVetoException to signify collapse has been canceled */ public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException; } diff --git a/jdk/src/share/classes/javax/swing/event/UndoableEditListener.java b/jdk/src/share/classes/javax/swing/event/UndoableEditListener.java index ba95d93b980..9db6991eb1b 100644 --- a/jdk/src/share/classes/javax/swing/event/UndoableEditListener.java +++ b/jdk/src/share/classes/javax/swing/event/UndoableEditListener.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,6 +38,8 @@ public interface UndoableEditListener extends java.util.EventListener { /** * An undoable edit happened + * + * @param e an {@code UndoableEditEvent} object */ void undoableEditHappened(UndoableEditEvent e); } diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java index 33b38623425..3c4338fdc76 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicInternalFrameTitlePane.java @@ -380,15 +380,11 @@ public class BasicInternalFrameTitlePane extends JComponent InternalFrameEvent e = new InternalFrameEvent( frame, InternalFrameEvent.INTERNAL_FRAME_CLOSING); // Try posting event, unless there's a SecurityManager. - if (JInternalFrame.class.getClassLoader() == null) { - try { - Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(e); - return; - } catch (SecurityException se) { - // Use dispatchEvent instead. - } + try { + Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(e); + } catch (SecurityException se) { + frame.dispatchEvent(e); } - frame.dispatchEvent(e); } diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java index 6ed2265087e..8c1622a4f2a 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java @@ -458,7 +458,7 @@ public abstract class BasicLookAndFeel extends LookAndFeel implements Serializab Integer fiveHundred = new Integer(500); // *** Shared Longs - Long oneThousand = new Long(1000); + Long oneThousand = 1000L; LazyValue dialogPlain12 = t -> new FontUIResource(Font.DIALOG, Font.PLAIN, 12); diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalBorders.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalBorders.java index 8f1ee4fb4d3..a49a4a8bb48 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalBorders.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalBorders.java @@ -56,6 +56,9 @@ public class MetalBorders { static Object NO_BUTTON_ROLLOVER = new StringUIClientPropertyKey("NoButtonRollover"); + /** + * The class represents the 3D border. + */ @SuppressWarnings("serial") // Superclass is not serializable across versions public static class Flush3DBorder extends AbstractBorder implements UIResource{ public void paintBorder(Component c, Graphics g, int x, int y, @@ -73,9 +76,15 @@ public class MetalBorders { } } + /** + * The class represents the border of a {@code JButton}. + */ @SuppressWarnings("serial") // Superclass is not serializable across versions public static class ButtonBorder extends AbstractBorder implements UIResource { + /** + * The border insets. + */ protected static Insets borderInsets = new Insets( 3, 3, 3, 3 ); public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { @@ -188,6 +197,9 @@ public class MetalBorders { } } + /** + * The class represents the border of a {@code JInternalFrame}. + */ @SuppressWarnings("serial") // Superclass is not serializable across versions public static class InternalFrameBorder extends AbstractBorder implements UIResource { private static final int corner = 14; @@ -470,6 +482,9 @@ public class MetalBorders { } } + /** + * The class represents the border of an option dialog. + */ @SuppressWarnings("serial") // Superclass is not serializable across versions public static class OptionDialogBorder extends AbstractBorder implements UIResource { int titleHeight = 0; @@ -532,8 +547,15 @@ public class MetalBorders { } } + /** + * The class represents the border of a {@code JMenuBar}. + */ @SuppressWarnings("serial") // Superclass is not serializable across versions public static class MenuBarBorder extends AbstractBorder implements UIResource { + + /** + * The border insets. + */ protected static Insets borderInsets = new Insets( 1, 0, 1, 0 ); public void paintBorder( Component c, Graphics g, int x, int y, int w, int h ) { @@ -569,8 +591,15 @@ public class MetalBorders { } } + /** + * The class represents the border of a {@code JMenuItem}. + */ @SuppressWarnings("serial") // Superclass is not serializable across versions public static class MenuItemBorder extends AbstractBorder implements UIResource { + + /** + * The border insets. + */ protected static Insets borderInsets = new Insets( 2, 2, 2, 2 ); public void paintBorder( Component c, Graphics g, int x, int y, int w, int h ) { @@ -617,8 +646,15 @@ public class MetalBorders { } } + /** + * The class represents the border of a {@code JPopupMenu}. + */ @SuppressWarnings("serial") // Superclass is not serializable across versions public static class PopupMenuBorder extends AbstractBorder implements UIResource { + + /** + * The border insets. + */ protected static Insets borderInsets = new Insets( 3, 1, 2, 1 ); public void paintBorder( Component c, Graphics g, int x, int y, int w, int h ) { @@ -642,6 +678,9 @@ public class MetalBorders { } } + /** + * The class represents the border of a rollover {@code Button}. + */ @SuppressWarnings("serial") // Superclass is not serializable across versions public static class RolloverButtonBorder extends ButtonBorder { @@ -693,9 +732,15 @@ public class MetalBorders { } } + /** + * The class represents the border of a {@code JToolBar}. + */ @SuppressWarnings("serial") // Superclass is not serializable across versions public static class ToolBarBorder extends AbstractBorder implements UIResource, SwingConstants { + /** + * The instance of {@code MetalBumps}. + */ protected MetalBumps bumps = new MetalBumps( 10, 10, MetalLookAndFeel.getControlHighlight(), MetalLookAndFeel.getControlDarkShadow(), @@ -779,7 +824,9 @@ public class MetalBorders { private static Border buttonBorder; /** - * Returns a border instance for a JButton + * Returns a border instance for a {@code JButton}. + * + * @return a border instance for a {@code JButton} * @since 1.3 */ public static Border getButtonBorder() { @@ -794,7 +841,9 @@ public class MetalBorders { private static Border textBorder; /** - * Returns a border instance for a text component + * Returns a border instance for a text component. + * + * @return a border instance for a text component * @since 1.3 */ public static Border getTextBorder() { @@ -809,7 +858,9 @@ public class MetalBorders { private static Border textFieldBorder; /** - * Returns a border instance for a JTextField + * Returns a border instance for a {@code JTextField}. + * + * @return a border instance for a {@code JTextField} * @since 1.3 */ public static Border getTextFieldBorder() { @@ -821,6 +872,9 @@ public class MetalBorders { return textFieldBorder; } + /** + * The class represents the border of a {@code JTestField}. + */ @SuppressWarnings("serial") // Superclass is not serializable across versions public static class TextFieldBorder extends Flush3DBorder { @@ -846,6 +900,9 @@ public class MetalBorders { } } + /** + * The class represents the border of a {@code JScrollPane}. + */ @SuppressWarnings("serial") // Superclass is not serializable across versions public static class ScrollPaneBorder extends AbstractBorder implements UIResource { public void paintBorder(Component c, Graphics g, int x, int y, @@ -892,7 +949,9 @@ public class MetalBorders { private static Border toggleButtonBorder; /** - * Returns a border instance for a JToggleButton + * Returns a border instance for a {@code JToggleButton}. + * + * @return a border instance for a {@code JToggleButton} * @since 1.3 */ public static Border getToggleButtonBorder() { @@ -942,6 +1001,10 @@ public class MetalBorders { */ @SuppressWarnings("serial") // Superclass is not serializable across versions public static class TableHeaderBorder extends javax.swing.border.AbstractBorder { + + /** + * The border insets. + */ protected Insets editorBorderInsets = new Insets( 2, 2, 2, 0 ); public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { @@ -964,7 +1027,9 @@ public class MetalBorders { } /** - * Returns a border instance for a Desktop Icon + * Returns a border instance for a Desktop Icon. + * + * @return a border instance for a Desktop Icon * @since 1.3 */ public static Border getDesktopIconBorder() { diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalButtonUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalButtonUI.java index 233949e3df1..db31cc126a9 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalButtonUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalButtonUI.java @@ -52,10 +52,22 @@ import javax.swing.plaf.*; */ @SuppressWarnings("serial") // Same-version serialization only public class MetalButtonUI extends BasicButtonUI { + // NOTE: These are not really needed, but at this point we can't pull // them. Their values are updated purely for historical reasons. + /** + * The color of the focused button. + */ protected Color focusColor; + + /** + * The color of the selected button. + */ protected Color selectColor; + + /** + * The color of the disabled color. + */ protected Color disabledTextColor; private static final Object METAL_BUTTON_UI_KEY = new Object(); @@ -63,6 +75,13 @@ public class MetalButtonUI extends BasicButtonUI { // ******************************** // Create PLAF // ******************************** + + /** + * Returns an instance of {@code MetalButtonUI}. + * + * @param c a component + * @return an instance of {@code MetalButtonUI} + */ public static ComponentUI createUI(JComponent c) { AppContext appContext = AppContext.getAppContext(); MetalButtonUI metalButtonUI = @@ -96,17 +115,33 @@ public class MetalButtonUI extends BasicButtonUI { // ******************************** // Default Accessors // ******************************** + + /** + * Returns the color of the selected button. + * + * @return the color of the selected button + */ protected Color getSelectColor() { selectColor = UIManager.getColor(getPropertyPrefix() + "select"); return selectColor; } + /** + * Returns the color of a disabled text. + * + * @return the color of a disabled text + */ protected Color getDisabledTextColor() { disabledTextColor = UIManager.getColor(getPropertyPrefix() + "disabledText"); return disabledTextColor; } + /** + * Returns the color of the focused button. + * + * @return the color of the focused button + */ protected Color getFocusColor() { focusColor = UIManager.getColor(getPropertyPrefix() + "focus"); return focusColor; diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalCheckBoxIcon.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalCheckBoxIcon.java index 0962c8e943a..c262f460fe7 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalCheckBoxIcon.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalCheckBoxIcon.java @@ -49,6 +49,11 @@ import javax.swing.plaf.*; @SuppressWarnings("serial") // Same-version serialization only public class MetalCheckBoxIcon implements Icon, UIResource, Serializable { + /** + * Returns the size of the control. + * + * @return the size of the control + */ protected int getControlSize() { return 13; } public void paintIcon(Component c, Graphics g, int x, int y) { @@ -91,6 +96,14 @@ public class MetalCheckBoxIcon implements Icon, UIResource, Serializable { } } + /** + * Paints {@code MetalCheckBoxIcon}. + * + * @param c a component + * @param g an instance of {@code Graphics} + * @param x an X coordinate + * @param y an Y coordinate + */ protected void drawCheck(Component c, Graphics g, int x, int y) { int controlSize = getControlSize(); g.fillRect( x+3, y+5, 2, controlSize-8 ); diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalCheckBoxUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalCheckBoxUI.java index b80ec636ac2..e18d44a37a0 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalCheckBoxUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalCheckBoxUI.java @@ -67,6 +67,13 @@ public class MetalCheckBoxUI extends MetalRadioButtonUI { // ******************************** // Create PlAF // ******************************** + + /** + * Returns an instance of {@code MetalCheckBoxUI}. + * + * @param b a component + * @return a new instance of {@code MetalCheckBoxUI} + */ public static ComponentUI createUI(JComponent b) { AppContext appContext = AppContext.getAppContext(); MetalCheckBoxUI checkboxUI = diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxButton.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxButton.java index 6a6d1ed860e..15b889e9d34 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxButton.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxButton.java @@ -50,19 +50,72 @@ import java.io.Serializable; */ @SuppressWarnings("serial") // Same-version serialization only public class MetalComboBoxButton extends JButton { + + /** + * The instance of {@code JComboBox}. + */ protected JComboBox comboBox; + + /** + * The instance of {@code JList}. + */ protected JList listBox; + + /** + * The instance of {@code CellRendererPane}. + */ protected CellRendererPane rendererPane; + + /** + * The icon. + */ protected Icon comboIcon; + + /** + * The {@code iconOnly} value. + */ protected boolean iconOnly = false; + /** + * Returns the {@code JComboBox}. + * + * @return the {@code JComboBox} + */ public final JComboBox getComboBox() { return comboBox;} + + /** + * Sets the {@code JComboBox}. + * + * @param cb the {@code JComboBox} + */ public final void setComboBox( JComboBox cb ) { comboBox = cb;} + /** + * Returns the icon of the {@code JComboBox}. + * + * @return the icon of the {@code JComboBox} + */ public final Icon getComboIcon() { return comboIcon;} + + /** + * Sets the icon of the {@code JComboBox}. + * + * @param i the icon of the {@code JComboBox} + */ public final void setComboIcon( Icon i ) { comboIcon = i;} + /** + * Returns the {@code isIconOnly} value. + * + * @return the {@code isIconOnly} value + */ public final boolean isIconOnly() { return iconOnly;} + + /** + * If {@code isIconOnly} is {@code true} then only icon is painted. + * + * @param isIconOnly if {@code true} then only icon is painted + */ public final void setIconOnly( boolean isIconOnly ) { iconOnly = isIconOnly;} MetalComboBoxButton() { @@ -75,6 +128,14 @@ public class MetalComboBoxButton extends JButton { setModel( model ); } + /** + * Constructs a new instance of {@code MetalComboBoxButton}. + * + * @param cb an instance of {@code JComboBox} + * @param i an icon + * @param pane an instance of {@code CellRendererPane} + * @param list an instance of {@code JList} + */ public MetalComboBoxButton( JComboBox cb, Icon i, CellRendererPane pane, JList list ) { this(); @@ -85,6 +146,15 @@ public class MetalComboBoxButton extends JButton { setEnabled( comboBox.isEnabled() ); } + /** + * Constructs a new instance of {@code MetalComboBoxButton}. + * + * @param cb an instance of {@code JComboBox} + * @param i an icon + * @param onlyIcon if {@code true} only icon is painted + * @param pane an instance of {@code CellRendererPane} + * @param list an instance of {@code JList} + */ public MetalComboBoxButton( JComboBox cb, Icon i, boolean onlyIcon, CellRendererPane pane, JList list ) { this( cb, i, pane, list ); diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxEditor.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxEditor.java index 4c95250013b..e9f4aeb4c9d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxEditor.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxEditor.java @@ -50,6 +50,9 @@ import javax.swing.plaf.basic.BasicComboBoxEditor; @SuppressWarnings("serial") // Same-version serialization only public class MetalComboBoxEditor extends BasicComboBoxEditor { + /** + * Constructs a new instance of {@code MetalComboBoxEditor}. + */ public MetalComboBoxEditor() { super(); //editor.removeFocusListener(this); diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxUI.java index eb9afb93439..c95e6b5c6ce 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalComboBoxUI.java @@ -54,6 +54,12 @@ import java.beans.*; @SuppressWarnings("serial") // Same-version serialization only public class MetalComboBoxUI extends BasicComboBoxUI { + /** + * Constructs an instance of {@code MetalComboBoxUI}. + * + * @param c a component + * @return an instance of {@code MetalComboBoxUI} + */ public static ComponentUI createUI(JComponent c) { return new MetalComboBoxUI(); } @@ -234,6 +240,7 @@ public class MetalComboBoxUI extends BasicComboBoxUI { * override. All the functionality of this method is in the * MetalPropertyChangeListener. * + * @param e an instance of {@code PropertyChangeEvent} * @deprecated As of Java 2 platform v1.4. */ @Deprecated @@ -251,11 +258,23 @@ public class MetalComboBoxUI extends BasicComboBoxUI { public void layoutContainer( Container parent ) { layoutComboBox( parent, this ); } + + /** + * Lays out the parent container. + * + * @param parent a container + */ public void superLayout( Container parent ) { super.layoutContainer( parent ); } } + /** + * Lays out the {@code JComboBox} in the {@code parent} container. + * + * @param parent a container + * @param manager an instance of {@code MetalComboBoxLayoutManager} + */ // This is here because of a bug in the compiler. // When a protected-inner-class-savvy compiler comes out we // should move this into MetalComboBoxLayoutManager. @@ -367,6 +386,11 @@ public class MetalComboBoxUI extends BasicComboBoxUI { @Deprecated public class MetalComboPopup extends BasicComboPopup { + /** + * Constructs a new instance of {@code MetalComboPopup}. + * + * @param cBox an instance of {@code JComboBox} + */ public MetalComboPopup( JComboBox cBox) { super( cBox ); } diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalDesktopIconUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalDesktopIconUI.java index 074a3b5eb79..ec3921b5671 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalDesktopIconUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalDesktopIconUI.java @@ -48,10 +48,19 @@ public class MetalDesktopIconUI extends BasicDesktopIconUI TitleListener titleListener; private int width; + /** + * Constructs a new instance of {@code MetalDesktopIconUI}. + * + * @param c a component + * @return a new instance of {@code MetalDesktopIconUI} + */ public static ComponentUI createUI(JComponent c) { return new MetalDesktopIconUI(); } + /** + * Constructs a new instance of {@code MetalDesktopIconUI}. + */ public MetalDesktopIconUI() { } diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java index dc15fe68498..06fb070113b 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalFileChooserUI.java @@ -138,13 +138,21 @@ public class MetalFileChooserUI extends BasicFileChooserUI { } } - // - // ComponentUI Interface Implementation methods - // + /** + * Constructs a new instance of {@code MetalFileChooserUI}. + * + * @param c a component + * @return a new instance of {@code MetalFileChooserUI} + */ public static ComponentUI createUI(JComponent c) { return new MetalFileChooserUI((JFileChooser) c); } + /** + * Constructs a new instance of {@code MetalFileChooserUI}. + * + * @param filechooser a {@code JFileChooser} + */ public MetalFileChooserUI(JFileChooser filechooser) { super(filechooser); } @@ -446,6 +454,11 @@ public class MetalFileChooserUI extends BasicFileChooserUI { groupLabels(new AlignedLabel[] { fileNameLabel, filesOfTypeLabel }); } + /** + * Returns the button panel. + * + * @return the button panel + */ protected JPanel getButtonPanel() { if (buttonPanel == null) { buttonPanel = new JPanel(); @@ -453,6 +466,11 @@ public class MetalFileChooserUI extends BasicFileChooserUI { return buttonPanel; } + /** + * Returns the bottom panel. + * + * @return the bottom panel + */ protected JPanel getBottomPanel() { if(bottomPanel == null) { bottomPanel = new JPanel(); @@ -503,20 +521,42 @@ public class MetalFileChooserUI extends BasicFileChooserUI { SwingUtilities.replaceUIActionMap(fc, actionMap); } + /** + * Returns an instance of {@code ActionMap}. + * + * @return an instance of {@code ActionMap} + */ protected ActionMap getActionMap() { return createActionMap(); } + /** + * Constructs an instance of {@code ActionMap}. + * + * @return an instance of {@code ActionMap} + */ protected ActionMap createActionMap() { ActionMap map = new ActionMapUIResource(); FilePane.addActionsToMap(map, filePane.getActions()); return map; } + /** + * Constructs a details view. + * + * @param fc a {@code JFileChooser} + * @return the list + */ protected JPanel createList(JFileChooser fc) { return filePane.createList(); } + /** + * Constructs a details view. + * + * @param fc a {@code JFileChooser} + * @return the details view + */ protected JPanel createDetailsView(JFileChooser fc) { return filePane.createDetailsView(); } @@ -533,7 +573,12 @@ public class MetalFileChooserUI extends BasicFileChooserUI { // Obsolete class, not used in this version. protected class SingleClickListener extends MouseAdapter { - public SingleClickListener(JList list) { + /** + * Constructs an instance of {@code SingleClickListener}. + * + * @param list an instance of {@code JList} + */ + public SingleClickListener(JList list) { } } @@ -788,11 +833,16 @@ public class MetalFileChooserUI extends BasicFileChooserUI { }; } - + /** + * Removes control buttons from bottom panel. + */ protected void removeControlButtons() { getBottomPanel().remove(getButtonPanel()); } + /** + * Adds control buttons to bottom panel. + */ protected void addControlButtons() { getBottomPanel().add(getButtonPanel()); } @@ -842,15 +892,31 @@ public class MetalFileChooserUI extends BasicFileChooserUI { } } + /** + * Returns the directory name. + * + * @return the directory name + */ public String getDirectoryName() { // PENDING(jeff) - get the name from the directory combobox return null; } + /** + * Sets the directory name. + * + * @param dirname the directory name + */ public void setDirectoryName(String dirname) { // PENDING(jeff) - set the name in the directory combobox } + /** + * Constructs a new instance of {@code DirectoryComboBoxRenderer}. + * + * @param fc a {@code JFileChooser} + * @return a new instance of {@code DirectoryComboBoxRenderer} + */ protected DirectoryComboBoxRenderer createDirectoryComboBoxRenderer(JFileChooser fc) { return new DirectoryComboBoxRenderer(); } @@ -906,9 +972,12 @@ public class MetalFileChooserUI extends BasicFileChooserUI { } - // - // DataModel for DirectoryComboxbox - // + /** + * Constructs a new instance of {@code DataModel} for {@code DirectoryComboBox}. + * + * @param fc a {@code JFileChooser} + * @return a new instance of {@code DataModel} for {@code DirectoryComboBox} + */ protected DirectoryComboBoxModel createDirectoryComboBoxModel(JFileChooser fc) { return new DirectoryComboBoxModel(); } @@ -924,6 +993,9 @@ public class MetalFileChooserUI extends BasicFileChooserUI { JFileChooser chooser = getFileChooser(); FileSystemView fsv = chooser.getFileSystemView(); + /** + * Constructs an instance of {@code DirectoryComboBoxModel}. + */ public DirectoryComboBoxModel() { // Add the current directory to the model, and make it the // selectedDirectory @@ -1017,6 +1089,12 @@ public class MetalFileChooserUI extends BasicFileChooserUI { } } + /** + * Returns the depth of {@code i}-th file. + * + * @param i an index + * @return the depth of {@code i}-th file + */ public int getDepth(int i) { return (depths != null && i >= 0 && i < depths.length) ? depths[i] : 0; } @@ -1039,9 +1117,11 @@ public class MetalFileChooserUI extends BasicFileChooserUI { } } - // - // Renderer for Types ComboBox - // + /** + * Constructs a {@code Renderer} for types {@code ComboBox}. + * + * @return a {@code Renderer} for types {@code ComboBox} + */ protected FilterComboBoxRenderer createFilterComboBoxRenderer() { return new FilterComboBoxRenderer(); } @@ -1065,9 +1145,11 @@ public class MetalFileChooserUI extends BasicFileChooserUI { } } - // - // DataModel for Types Comboxbox - // + /** + * Constructs a {@code DataModel} for types {@code ComboBox}. + * + * @return a {@code DataModel} for types {@code ComboBox} + */ protected FilterComboBoxModel createFilterComboBoxModel() { return new FilterComboBoxModel(); } @@ -1077,7 +1159,15 @@ public class MetalFileChooserUI extends BasicFileChooserUI { */ @SuppressWarnings("serial") // Same-version serialization only protected class FilterComboBoxModel extends AbstractListModel implements ComboBoxModel, PropertyChangeListener { + + /** + * An array of file filters. + */ protected FileFilter[] filters; + + /** + * Constructs an instance of {@code FilterComboBoxModel}. + */ protected FilterComboBoxModel() { super(); filters = getFileChooser().getChoosableFileFilters(); @@ -1142,6 +1232,11 @@ public class MetalFileChooserUI extends BasicFileChooserUI { } } + /** + * Invokes when {@code ListSelectionEvent} occurs. + * + * @param e an instance of {@code ListSelectionEvent} + */ public void valueChanged(ListSelectionEvent e) { JFileChooser fc = getFileChooser(); File f = fc.getSelectedFile(); @@ -1155,6 +1250,10 @@ public class MetalFileChooserUI extends BasicFileChooserUI { */ @SuppressWarnings("serial") // Superclass is not serializable across versions protected class DirectoryComboBoxAction extends AbstractAction { + + /** + * Constructs a new instance of {@code DirectoryComboBoxAction}. + */ protected DirectoryComboBoxAction() { super("DirectoryComboBoxAction"); } diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java index e74882523d0..8cd0bd04ace 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalIconFactory.java @@ -90,10 +90,22 @@ public class MetalIconFactory implements Serializable { private static Icon oceanVerticalSliderThumb; // Constants + /** + * {@code DARK} is used for the property {@code Tree.expandedIcon}. + */ public static final boolean DARK = false; + + /** + * {@code LIGHT} is used for the property {@code Tree.collapsedIcon}. + */ public static final boolean LIGHT = true; // Accessor functions for Icons. Does the caching work. + /** + * Returns the instance of {@code FileChooserDetailViewIcon}. + * + * @return the instance of {@code FileChooserDetailViewIcon} + */ public static Icon getFileChooserDetailViewIcon() { if (fileChooserDetailViewIcon == null) { fileChooserDetailViewIcon = new FileChooserDetailViewIcon(); @@ -101,6 +113,11 @@ public class MetalIconFactory implements Serializable { return fileChooserDetailViewIcon; } + /** + * Returns the instance of {@code FileChooserHomeFolderIcon}. + * + * @return the instance of {@code FileChooserHomeFolderIcon} + */ public static Icon getFileChooserHomeFolderIcon() { if (fileChooserHomeFolderIcon == null) { fileChooserHomeFolderIcon = new FileChooserHomeFolderIcon(); @@ -108,6 +125,11 @@ public class MetalIconFactory implements Serializable { return fileChooserHomeFolderIcon; } + /** + * Returns the instance of {@code FileChooserListViewIcon}. + * + * @return the instance of {@code FileChooserListViewIcon} + */ public static Icon getFileChooserListViewIcon() { if (fileChooserListViewIcon == null) { fileChooserListViewIcon = new FileChooserListViewIcon(); @@ -115,6 +137,11 @@ public class MetalIconFactory implements Serializable { return fileChooserListViewIcon; } + /** + * Returns the instance of {@code FileChooserNewFolderIcon}. + * + * @return the instance of {@code FileChooserNewFolderIcon} + */ public static Icon getFileChooserNewFolderIcon() { if (fileChooserNewFolderIcon == null) { fileChooserNewFolderIcon = new FileChooserNewFolderIcon(); @@ -122,6 +149,11 @@ public class MetalIconFactory implements Serializable { return fileChooserNewFolderIcon; } + /** + * Returns the instance of {@code FileChooserUpFolderIcon}. + * + * @return the instance of {@code FileChooserUpFolderIcon} + */ public static Icon getFileChooserUpFolderIcon() { if (fileChooserUpFolderIcon == null) { fileChooserUpFolderIcon = new FileChooserUpFolderIcon(); @@ -129,14 +161,31 @@ public class MetalIconFactory implements Serializable { return fileChooserUpFolderIcon; } + /** + * Constructs a new instance of {@code InternalFrameAltMaximizeIcon}. + * + * @param size the size of the icon + * @return a new instance of {@code InternalFrameAltMaximizeIcon} + */ public static Icon getInternalFrameAltMaximizeIcon(int size) { return new InternalFrameAltMaximizeIcon(size); } + /** + * Constructs a new instance of {@code InternalFrameCloseIcon}. + * + * @param size the size of the icon + * @return a new instance of {@code InternalFrameCloseIcon} + */ public static Icon getInternalFrameCloseIcon(int size) { return new InternalFrameCloseIcon(size); } + /** + * Returns the instance of {@code InternalFrameDefaultMenuIcon}. + * + * @return the instance of {@code InternalFrameDefaultMenuIcon} + */ public static Icon getInternalFrameDefaultMenuIcon() { if (internalFrameDefaultMenuIcon == null) { internalFrameDefaultMenuIcon = new InternalFrameDefaultMenuIcon(); @@ -144,14 +193,31 @@ public class MetalIconFactory implements Serializable { return internalFrameDefaultMenuIcon; } + /** + * Constructs a new instance of {@code InternalFrameMaximizeIcon}. + * + * @param size the size of the icon + * @return a new instance of {@code InternalFrameMaximizeIcon} + */ public static Icon getInternalFrameMaximizeIcon(int size) { return new InternalFrameMaximizeIcon(size); } + /** + * Constructs a new instance of {@code InternalFrameMinimizeIcon}. + * + * @param size the size of the icon + * @return a new instance of {@code InternalFrameMinimizeIcon} + */ public static Icon getInternalFrameMinimizeIcon(int size) { return new InternalFrameMinimizeIcon(size); } + /** + * Returns the instance of {@code RadioButtonIcon}. + * + * @return the instance of {@code RadioButtonIcon} + */ public static Icon getRadioButtonIcon() { if (radioButtonIcon == null) { radioButtonIcon = new RadioButtonIcon(); @@ -161,6 +227,8 @@ public class MetalIconFactory implements Serializable { /** * Returns a checkbox icon. + * + * @return a checkbox icon * @since 1.3 */ public static Icon getCheckBoxIcon() { @@ -170,6 +238,11 @@ public class MetalIconFactory implements Serializable { return checkBoxIcon; } + /** + * Returns the instance of {@code TreeComputerIcon}. + * + * @return the instance of {@code TreeComputerIcon} + */ public static Icon getTreeComputerIcon() { if ( treeComputerIcon == null ) { treeComputerIcon = new TreeComputerIcon(); @@ -177,6 +250,11 @@ public class MetalIconFactory implements Serializable { return treeComputerIcon; } + /** + * Returns the instance of {@code TreeFloppyDriveIcon}. + * + * @return the instance of {@code TreeFloppyDriveIcon} + */ public static Icon getTreeFloppyDriveIcon() { if ( treeFloppyDriveIcon == null ) { treeFloppyDriveIcon = new TreeFloppyDriveIcon(); @@ -184,10 +262,20 @@ public class MetalIconFactory implements Serializable { return treeFloppyDriveIcon; } + /** + * Constructs a new instance of {@code TreeFolderIcon}. + * + * @return a new instance of {@code TreeFolderIcon} + */ public static Icon getTreeFolderIcon() { return new TreeFolderIcon(); } + /** + * Returns the instance of {@code TreeHardDriveIcon}. + * + * @return the instance of {@code TreeHardDriveIcon} + */ public static Icon getTreeHardDriveIcon() { if ( treeHardDriveIcon == null ) { treeHardDriveIcon = new TreeHardDriveIcon(); @@ -195,14 +283,30 @@ public class MetalIconFactory implements Serializable { return treeHardDriveIcon; } + /** + * Constructs a new instance of {@code TreeLeafIcon}. + * + * @return a new instance of {@code TreeLeafIcon} + */ public static Icon getTreeLeafIcon() { return new TreeLeafIcon(); } + /** + * Constructs a new instance of {@code TreeControlIcon}. + * + * @param isCollapsed if {@code true} the icon is collapsed + * @return a new instance of {@code TreeControlIcon} + */ public static Icon getTreeControlIcon( boolean isCollapsed ) { return new TreeControlIcon( isCollapsed ); } + /** + * Returns an icon to be used by {@code JMenu}. + * + * @return an icon to be used by {@code JMenu} + */ public static Icon getMenuArrowIcon() { if (menuArrowIcon == null) { menuArrowIcon = new MenuArrowIcon(); @@ -220,6 +324,11 @@ public class MetalIconFactory implements Serializable { return null; } + /** + * Returns an icon to be used by {@code JMenuItem}. + * + * @return an icon to be used by {@code JMenuItem} + */ public static Icon getMenuItemArrowIcon() { if (menuItemArrowIcon == null) { menuItemArrowIcon = new MenuItemArrowIcon(); @@ -227,6 +336,11 @@ public class MetalIconFactory implements Serializable { return menuItemArrowIcon; } + /** + * Returns an icon to be used by {@code JCheckBoxMenuItem}. + * + * @return an icon to be used by {@code JCheckBoxMenuItem} + */ public static Icon getCheckBoxMenuItemIcon() { if (checkBoxMenuItemIcon == null) { checkBoxMenuItemIcon = new CheckBoxMenuItemIcon(); @@ -234,6 +348,11 @@ public class MetalIconFactory implements Serializable { return checkBoxMenuItemIcon; } + /** + * Returns an icon to be used by {@code JRadioButtonMenuItem}. + * + * @return an icon to be used by {@code JRadioButtonMenuItem} + */ public static Icon getRadioButtonMenuItemIcon() { if (radioButtonMenuItemIcon == null) { radioButtonMenuItemIcon = new RadioButtonMenuItemIcon(); @@ -241,6 +360,11 @@ public class MetalIconFactory implements Serializable { return radioButtonMenuItemIcon; } + /** + * Returns a thumb icon to be used by horizontal slider. + * + * @return a thumb icon to be used by horizontal slider + */ public static Icon getHorizontalSliderThumbIcon() { if (MetalLookAndFeel.usingOcean()) { if (oceanHorizontalSliderThumb == null) { @@ -253,6 +377,11 @@ public class MetalIconFactory implements Serializable { return new HorizontalSliderThumbIcon(); } + /** + * Returns a thumb icon to be used by vertical slider. + * + * @return a thumb icon to be used by vertical slider + */ public static Icon getVerticalSliderThumbIcon() { if (MetalLookAndFeel.usingOcean()) { if (oceanVerticalSliderThumb == null) { @@ -1251,8 +1380,10 @@ public class MetalIconFactory implements Serializable { g.translate(x, y); // fill interior - g.setColor(interiorColor); - g.fillRect(2,2, 9,9); + if (c.isOpaque()) { + g.setColor(interiorColor); + g.fillRect(2, 2, 9, 9); + } // draw Dark Circle (start at top, go clockwise) g.setColor(darkCircle); @@ -1619,7 +1750,18 @@ public class MetalIconFactory implements Serializable { } + /** + * Returns a shift of the icon. + * + * @return a shift of the icon + */ public int getShift() { return 0; } + + /** + * Returns an additional height of the icon. + * + * @return an additional height of the icon + */ public int getAdditionalHeight() { return 0; } public int getIconWidth() { return folderIcon16Size.width; } @@ -1717,7 +1859,18 @@ public class MetalIconFactory implements Serializable { } + /** + * Returns a shift of the icon. + * + * @return a shift of the icon + */ public int getShift() { return 0; } + + /** + * Returns an additional height of the icon. + * + * @return an additional height of the icon + */ public int getAdditionalHeight() { return 0; } public int getIconWidth() { return fileIcon16Size.width; } @@ -1725,6 +1878,9 @@ public class MetalIconFactory implements Serializable { } + /** + * The class represents a tree leaf icon. + */ public static class TreeLeafIcon extends FileIcon16 { public int getShift() { return 2; } public int getAdditionalHeight() { return 4; } @@ -1746,12 +1902,20 @@ public class MetalIconFactory implements Serializable { */ @SuppressWarnings("serial") // Same-version serialization only public static class TreeControlIcon implements Icon, Serializable { - // This data member should not have been exposed. It's called - // isLight, but now it really means isCollapsed. Since we can't change - // any APIs... that's life. + + /** + * if {@code true} the icon is collapsed. + * NOTE: This data member should not have been exposed. It's called + * {@code isLight}, but now it really means {@code isCollapsed}. + * Since we can't change any APIs... that's life. + */ protected boolean isLight; - + /** + * Constructs an instance of {@code TreeControlIcon}. + * + * @param isCollapsed if {@code true} the icon is collapsed + */ public TreeControlIcon( boolean isCollapsed ) { isLight = isCollapsed; } @@ -1809,6 +1973,14 @@ public class MetalIconFactory implements Serializable { } } + /** + * Paints the {@code TreeControlIcon}. + * + * @param c a component + * @param g an instance of {@code Graphics} + * @param x an X coordinate + * @param y an Y coordinate + */ public void paintMe(Component c, Graphics g, int x, int y) { g.setColor( MetalLookAndFeel.getPrimaryControlInfo() ); @@ -1821,7 +1993,7 @@ public class MetalIconFactory implements Serializable { g.drawLine( xoff + 6, 4, xoff + 9, 4 ); // top g.drawLine( xoff + 10, 5, xoff + 10, 5 ); // top right dot g.drawLine( xoff + 11, 6, xoff + 11, 9 ); // right - g.drawLine( xoff + 10, 10, xoff + 10, 10 ); // botom right dot + g.drawLine( xoff + 10, 10, xoff + 10, 10 ); // bottom right dot g.drawLine( xoff + 6, 11, xoff + 9, 11 ); // bottom g.drawLine( xoff + 5, 10, xoff + 5, 10 ); // bottom left dot diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameTitlePane.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameTitlePane.java index bcf1abbcedc..b517b4ad3c8 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameTitlePane.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameTitlePane.java @@ -46,8 +46,19 @@ import javax.swing.plaf.basic.BasicInternalFrameTitlePane; @SuppressWarnings("serial") // Superclass is not serializable across versions public class MetalInternalFrameTitlePane extends BasicInternalFrameTitlePane { + /** + * The value {@code isPalette} + */ protected boolean isPalette = false; + + /** + * The palette close icon. + */ protected Icon paletteCloseIcon; + + /** + * The height of the palette title. + */ protected int paletteTitleHeight; private static final Border handyEmptyBorder = new EmptyBorder(0,0,0,0); @@ -94,6 +105,11 @@ public class MetalInternalFrameTitlePane extends BasicInternalFrameTitlePane { private Color activeBumpsShadow = MetalLookAndFeel. getPrimaryControlDarkShadow(); + /** + * Constructs a new instance of {@code MetalInternalFrameTitlePane} + * + * @param f an instance of {@code JInternalFrame} + */ public MetalInternalFrameTitlePane(JInternalFrame f) { super( f ); } @@ -307,6 +323,11 @@ public class MetalInternalFrameTitlePane extends BasicInternalFrameTitlePane { } } + /** + * Paints palette. + * + * @param g a instance of {@code Graphics} + */ public void paintPalette(Graphics g) { boolean leftToRight = MetalUtils.isLeftToRight(frame); @@ -471,6 +492,11 @@ public class MetalInternalFrameTitlePane extends BasicInternalFrameTitlePane { bumps.paintIcon(this, g, bumpXOffset, bumpYOffset); } + /** + * If {@code b} is {@code true}, sets palette icons. + * + * @param b if {@code true}, sets palette icons + */ public void setPalette(boolean b) { isPalette = b; diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameUI.java index c8b75e88ac8..94daa93f3b0 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameUI.java @@ -47,6 +47,9 @@ public class MetalInternalFrameUI extends BasicInternalFrameUI { private static final Border handyEmptyBorder = new EmptyBorder(0,0,0,0); + /** + * The property {@code JInternalFrame.isPalette}. + */ protected static String IS_PALETTE = "JInternalFrame.isPalette"; private static String IS_PALETTE_KEY = "JInternalFrame.isPalette"; private static String FRAME_TYPE = "JInternalFrame.frameType"; @@ -54,10 +57,22 @@ public class MetalInternalFrameUI extends BasicInternalFrameUI { private static String PALETTE_FRAME = "palette"; private static String OPTION_DIALOG = "optionDialog"; + + /** + * Constructs a new {@code MetalInternalFrameUI} instance. + * + * @param b an internal frame + */ public MetalInternalFrameUI(JInternalFrame b) { super(b); } + /** + * Constructs a new {@code MetalInternalFrameUI} instance. + * + * @param c a component + * @return a new {@code MetalInternalFrameUI} instance + */ public static ComponentUI createUI(JComponent c) { return new MetalInternalFrameUI( (JInternalFrame) c); } @@ -152,6 +167,11 @@ public class MetalInternalFrameUI extends BasicInternalFrameUI { } } + /** + * If {@code isPalette} is {@code true}, sets palette border and title + * + * @param isPalette if {@code true}, sets palette border and title + */ // this should be deprecated - jcs public void setPalette(boolean isPalette) { if (isPalette) { diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalLabelUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalLabelUI.java index 6d62d1d640e..977b0789df6 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalLabelUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalLabelUI.java @@ -56,6 +56,12 @@ public class MetalLabelUI extends BasicLabelUI private static final Object METAL_LABEL_UI_KEY = new Object(); + /** + * Returns an instance of {@code MetalLabelUI}. + * + * @param c a component + * @return an instance of {@code MetalLabelUI} + */ public static ComponentUI createUI(JComponent c) { if (System.getSecurityManager() != null) { AppContext appContext = AppContext.getAppContext(); diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalPopupMenuSeparatorUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalPopupMenuSeparatorUI.java index c32d2679f9c..7a22550febc 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalPopupMenuSeparatorUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalPopupMenuSeparatorUI.java @@ -43,6 +43,12 @@ import javax.swing.plaf.*; public class MetalPopupMenuSeparatorUI extends MetalSeparatorUI { + /** + * Constructs a new {@code MetalPopupMenuSeparatorUI} instance. + * + * @param c a component + * @return a new {@code MetalPopupMenuSeparatorUI} instance + */ public static ComponentUI createUI( JComponent c ) { return new MetalPopupMenuSeparatorUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalProgressBarUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalProgressBarUI.java index aedede36688..42b0b3719a2 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalProgressBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalProgressBarUI.java @@ -50,6 +50,12 @@ public class MetalProgressBarUI extends BasicProgressBarUI { private Rectangle innards; private Rectangle box; + /** + * Constructs an instance of {@code MetalProgressBarUI}. + * + * @param c a component + * @return an instance of {@code MetalProgressBarUI} + */ public static ComponentUI createUI(JComponent c) { return new MetalProgressBarUI(); } diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java index 9b7beeacf98..660bfa84c8b 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalRadioButtonUI.java @@ -58,8 +58,19 @@ public class MetalRadioButtonUI extends BasicRadioButtonUI { private static final Object METAL_RADIO_BUTTON_UI_KEY = new Object(); + /** + * The color of the focused radio button. + */ protected Color focusColor; + + /** + * The color of the selected radio button. + */ protected Color selectColor; + + /** + * The color of a disabled text. + */ protected Color disabledTextColor; private boolean defaults_initialized = false; @@ -67,6 +78,13 @@ public class MetalRadioButtonUI extends BasicRadioButtonUI { // ******************************** // Create PlAF // ******************************** + + /** + * Returns an instance of {@code MetalRadioButtonUI}. + * + * @param c a component + * @return an instance of {@code MetalRadioButtonUI} + */ public static ComponentUI createUI(JComponent c) { AppContext appContext = AppContext.getAppContext(); MetalRadioButtonUI metalRadioButtonUI = @@ -100,14 +118,30 @@ public class MetalRadioButtonUI extends BasicRadioButtonUI { // ******************************** // Default Accessors // ******************************** + + /** + * Returns the color of the selected {@code JRadioButton}. + * + * @return the color of the selected {@code JRadioButton} + */ protected Color getSelectColor() { return selectColor; } + /** + * Returns the color of the disabled text. + * + * @return the color of the disabled text + */ protected Color getDisabledTextColor() { return disabledTextColor; } + /** + * Returns the color of the focused {@code JRadioButton}. + * + * @return the color of the focused {@code JRadioButton} + */ protected Color getFocusColor() { return focusColor; } diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalScrollBarUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalScrollBarUI.java index 6d410d88b71..cb4fbd72590 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalScrollBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalScrollBarUI.java @@ -59,17 +59,42 @@ public class MetalScrollBarUI extends BasicScrollBarUI private static Color thumbShadow; private static Color thumbHighlightColor; - + /** + * The metal bumps. + */ protected MetalBumps bumps; + /** + * The increase button. + */ protected MetalScrollButton increaseButton; + + /** + * The decrease button. + */ protected MetalScrollButton decreaseButton; + /** + * The width of the scroll bar. + */ protected int scrollBarWidth; + /** + * The property {@code JScrollBar.isFreeStanding}. + */ public static final String FREE_STANDING_PROP = "JScrollBar.isFreeStanding"; + + /** + * The value of the property {@code JScrollBar.isFreeStanding}. + */ protected boolean isFreeStanding = true; + /** + * Constructs a new {@code MetalScrollBarUI} instance. + * + * @param c a component + * @return a new {@code MetalScrollBarUI} instance + */ public static ComponentUI createUI( JComponent c ) { return new MetalScrollBarUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalScrollButton.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalScrollButton.java index edd40950ec4..31a874326b1 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalScrollButton.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalScrollButton.java @@ -59,6 +59,13 @@ public class MetalScrollButton extends BasicArrowButton private int buttonWidth; + /** + * Constructs an instance of {@code MetalScrollButton}. + * + * @param direction the direction + * @param width the width + * @param freeStanding the free standing value + */ public MetalScrollButton( int direction, int width, boolean freeStanding ) { super( direction ); @@ -70,6 +77,11 @@ public class MetalScrollButton extends BasicArrowButton isFreeStanding = freeStanding; } + /** + * Sets the free standing value. + * + * @param freeStanding the free standing value + */ public void setFreeStanding( boolean freeStanding ) { isFreeStanding = freeStanding; @@ -115,14 +127,10 @@ public class MetalScrollButton extends BasicArrowButton g.setColor( arrowColor ); int startY = ((h+1) - arrowHeight) / 2; int startX = (w / 2); - // System.out.println( "startX :" + startX + " startY :"+startY); + for (int line = 0; line < arrowHeight; line++) { g.drawLine( startX-line, startY+line, startX +line+1, startY+line); } - /* g.drawLine( 7, 6, 8, 6 ); - g.drawLine( 6, 7, 9, 7 ); - g.drawLine( 5, 8, 10, 8 ); - g.drawLine( 4, 9, 11, 9 );*/ if (isEnabled) { g.setColor( highlightColor ); @@ -167,17 +175,10 @@ public class MetalScrollButton extends BasicArrowButton int startY = (((h+1) - arrowHeight) / 2)+ arrowHeight-1; int startX = (w / 2); - // System.out.println( "startX2 :" + startX + " startY2 :"+startY); - for (int line = 0; line < arrowHeight; line++) { g.drawLine( startX-line, startY-line, startX +line+1, startY-line); } - /* g.drawLine( 4, 5, 11, 5 ); - g.drawLine( 5, 6, 10, 6 ); - g.drawLine( 6, 7, 9, 7 ); - g.drawLine( 7, 8, 8, 8 ); */ - if (isEnabled) { g.setColor( highlightColor ); @@ -219,18 +220,10 @@ public class MetalScrollButton extends BasicArrowButton int startX = (((w+1) - arrowHeight) / 2) + arrowHeight-1; int startY = (h / 2); - //System.out.println( "startX2 :" + startX + " startY2 :"+startY); - for (int line = 0; line < arrowHeight; line++) { g.drawLine( startX-line, startY-line, startX -line, startY+line+1); } - -/* g.drawLine( 5, 4, 5, 11 ); - g.drawLine( 6, 5, 6, 10 ); - g.drawLine( 7, 6, 7, 9 ); - g.drawLine( 8, 7, 8, 8 );*/ - if (isEnabled) { g.setColor( highlightColor ); @@ -274,11 +267,6 @@ public class MetalScrollButton extends BasicArrowButton g.drawLine( startX+line, startY-line, startX +line, startY+line+1); } - /* g.drawLine( 6, 7, 6, 8 ); - g.drawLine( 7, 6, 7, 9 ); - g.drawLine( 8, 5, 8, 10 ); - g.drawLine( 9, 4, 9, 11 );*/ - if (isEnabled) { g.setColor( highlightColor ); @@ -341,6 +329,11 @@ public class MetalScrollButton extends BasicArrowButton return new Dimension( Integer.MAX_VALUE, Integer.MAX_VALUE ); } + /** + * Returns the width of the button. + * + * @return the width of the button + */ public int getButtonWidth() { return buttonWidth; } diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalScrollPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalScrollPaneUI.java index ffc5fc4df1c..c65eb52a657 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalScrollPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalScrollPaneUI.java @@ -56,6 +56,12 @@ public class MetalScrollPaneUI extends BasicScrollPaneUI private PropertyChangeListener scrollBarSwapListener; + /** + * Constructs a new {@code MetalScrollPaneUI}. + * + * @param x a component + * @return a new {@code MetalScrollPaneUI} + */ public static ComponentUI createUI(JComponent x) { return new MetalScrollPaneUI(); } @@ -97,6 +103,7 @@ public class MetalScrollPaneUI extends BasicScrollPaneUI } /** + * @param scrollPane an instance of the {@code JScrollPane} * @deprecated - Replaced by {@link #uninstallListeners(JComponent)} */ @Deprecated @@ -136,6 +143,11 @@ public class MetalScrollPaneUI extends BasicScrollPaneUI } } + /** + * Returns a new {@code PropertyChangeListener} for scroll bar swap events. + * + * @return a new {@code PropertyChangeListener} for scroll bar swap events. + */ protected PropertyChangeListener createScrollBarSwapListener() { return new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalSeparatorUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalSeparatorUI.java index 9de133b902d..58b6e69e6fb 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalSeparatorUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalSeparatorUI.java @@ -53,6 +53,12 @@ import javax.swing.plaf.basic.BasicSeparatorUI; @SuppressWarnings("serial") // Same-version serialization only public class MetalSeparatorUI extends BasicSeparatorUI { + /** + * Constructs a new {@code MetalSeparatorUI} instance. + * + * @param c a component + * @return a new {@code MetalSeparatorUI} instance. + */ public static ComponentUI createUI( JComponent c ) { return new MetalSeparatorUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java index 6e629938a65..bc21c7a5094 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalSliderUI.java @@ -53,13 +53,42 @@ import javax.swing.plaf.*; @SuppressWarnings("serial") // Same-version serialization only public class MetalSliderUI extends BasicSliderUI { + /** + * The buffer of a tick. + */ protected final int TICK_BUFFER = 4; + + /** + * The value of the property {@code JSlider.isFilled}. + * By default, {@code false} if the property is not set, + * {@code true} for Ocean theme. + */ protected boolean filledSlider = false; + // NOTE: these next five variables are currently unused. + /** + * The color of a thumb + */ protected static Color thumbColor; + + /** + * The color of highlighting. + */ protected static Color highlightColor; + + /** + * The color of dark shadow. + */ protected static Color darkShadowColor; + + /** + * The width of a track. + */ protected static int trackWidth; + + /** + * The length of a tick. + */ protected static int tickLength; private int safeLength; @@ -80,13 +109,24 @@ public class MetalSliderUI extends BasicSliderUI { private static Icon SAFE_HORIZ_THUMB_ICON; private static Icon SAFE_VERT_THUMB_ICON; - + /** + * Property for {@code JSlider.isFilled}. + */ protected final String SLIDER_FILL = "JSlider.isFilled"; + /** + * Constructs a {@code MetalSliderUI} instance. + * + * @param c a component + * @return a {@code MetalSliderUI} instance + */ public static ComponentUI createUI(JComponent c) { return new MetalSliderUI(); } + /** + * Constructs a {@code MetalSliderUI} instance. + */ public MetalSliderUI() { super( null ); } @@ -126,10 +166,19 @@ public class MetalSliderUI extends BasicSliderUI { prepareFilledSliderField(); } + /** + * Constructs {@code MetalPropertyListener}. + * + * @param slider a {@code JSlider} + * @return the {@code MetalPropertyListener} + */ protected PropertyChangeListener createPropertyChangeListener( JSlider slider ) { return new MetalPropertyListener(); } + /** + * {@code PropertyListener} for {@code JSlider.isFilled}. + */ protected class MetalPropertyListener extends BasicSliderUI.PropertyChangeHandler { public void propertyChange( PropertyChangeEvent e ) { // listen for slider fill super.propertyChange( e ); @@ -485,6 +534,8 @@ public class MetalSliderUI extends BasicSliderUI { /** * Returns the shorter dimension of the track. + * + * @return the shorter dimension of the track */ protected int getTrackWidth() { // This strange calculation is here to keep the @@ -504,6 +555,8 @@ public class MetalSliderUI extends BasicSliderUI { /** * Returns the longer dimension of the slide bar. (The slide bar is only the * part that runs directly under the thumb) + * + * @return the longer dimension of the slide bar */ protected int getTrackLength() { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { @@ -514,6 +567,8 @@ public class MetalSliderUI extends BasicSliderUI { /** * Returns the amount that the thumb goes past the slide bar. + * + * @return the amount that the thumb goes past the slide bar */ protected int getThumbOverhang() { return (int)(getThumbSize().getHeight()-getTrackWidth())/2; diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalSplitPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalSplitPaneUI.java index d27ea2e4828..8d183126780 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalSplitPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalSplitPaneUI.java @@ -49,15 +49,20 @@ public class MetalSplitPaneUI extends BasicSplitPaneUI /** - * Creates a new MetalSplitPaneUI instance - */ + * Creates a new {@code MetalSplitPaneUI} instance + * + * @param x a component + * @return a new {@code MetalSplitPaneUI} instance + */ public static ComponentUI createUI(JComponent x) { return new MetalSplitPaneUI(); } /** - * Creates the default divider. - */ + * Creates the default divider. + * + * @return the default divider + */ public BasicSplitPaneDivider createDefaultDivider() { return new MetalSplitPaneDivider(this); } diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalTabbedPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalTabbedPaneUI.java index 75dc959ca3d..76451154127 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalTabbedPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalTabbedPaneUI.java @@ -50,12 +50,27 @@ import javax.swing.plaf.basic.BasicTabbedPaneUI; @SuppressWarnings("serial") // Same-version serialization only public class MetalTabbedPaneUI extends BasicTabbedPaneUI { + /** + * The minimum width of a pane. + */ protected int minTabWidth = 40; // Background color for unselected tabs that don't have an explicitly // set color. private Color unselectedBackground; + + /** + * The color of tab's background. + */ protected Color tabAreaBackground; + + /** + * The color of the selected pane. + */ protected Color selectColor; + + /** + * The color of the highlight. + */ protected Color selectHighlight; private boolean tabsOpaque = true; @@ -65,6 +80,12 @@ public class MetalTabbedPaneUI extends BasicTabbedPaneUI { // Selected border color for ocean. private Color oceanSelectedBorderColor; + /** + * Constructs {@code MetalTabbedPaneUI}. + * + * @param x a component + * @return an instance of {@code MetalTabbedPaneUI} + */ public static ComponentUI createUI( JComponent x ) { return new MetalTabbedPaneUI(); } @@ -116,6 +137,19 @@ public class MetalTabbedPaneUI extends BasicTabbedPaneUI { } + /** + * Paints the top tab border. + * + * @param tabIndex a tab index + * @param g an instance of {@code Graphics} + * @param x an X coordinate + * @param y an Y coordinate + * @param w a width + * @param h a height + * @param btm bottom + * @param rght right + * @param isSelected a selection + */ protected void paintTopTabBorder( int tabIndex, Graphics g, int x, int y, int w, int h, int btm, int rght, @@ -286,6 +320,15 @@ public class MetalTabbedPaneUI extends BasicTabbedPaneUI { g.translate( -x, -y ); } + /** + * Returns {@code true} if the gap should be filled. + * + * @param currentRun the current run + * @param tabIndex the tab index + * @param x an X coordinate + * @param y an Y coordinate + * @return {@code true} if the gap should be filled + */ protected boolean shouldFillGap( int currentRun, int tabIndex, int x, int y ) { boolean result = false; @@ -322,6 +365,14 @@ public class MetalTabbedPaneUI extends BasicTabbedPaneUI { return result; } + /** + * Returns the color of the gap. + * + * @param currentRun the current run + * @param x an X coordinate + * @param y an Y coordinate + * @return the color of the gap + */ protected Color getColorForGap( int currentRun, int x, int y ) { final int shadowWidth = 4; int selectedIndex = tabPane.getSelectedIndex(); @@ -349,6 +400,19 @@ public class MetalTabbedPaneUI extends BasicTabbedPaneUI { return tabPane.getBackground(); } + /** + * Paints the left tab border. + * + * @param tabIndex a tab index + * @param g an instance of {@code Graphics} + * @param x an X coordinate + * @param y an Y coordinate + * @param w a width + * @param h a height + * @param btm bottom + * @param rght right + * @param isSelected a selection + */ protected void paintLeftTabBorder( int tabIndex, Graphics g, int x, int y, int w, int h, int btm, int rght, @@ -466,6 +530,19 @@ public class MetalTabbedPaneUI extends BasicTabbedPaneUI { } + /** + * Paints the bottom tab border. + * + * @param tabIndex a tab index + * @param g an instance of {@code Graphics} + * @param x an X coordinate + * @param y an Y coordinate + * @param w a width + * @param h a height + * @param btm bottom + * @param rght right + * @param isSelected a selection + */ protected void paintBottomTabBorder( int tabIndex, Graphics g, int x, int y, int w, int h, int btm, int rght, @@ -623,6 +700,19 @@ public class MetalTabbedPaneUI extends BasicTabbedPaneUI { g.translate( -x, -y ); } + /** + * Paints the right tab border. + * + * @param tabIndex a tab index + * @param g an instance of {@code Graphics} + * @param x an X coordinate + * @param y an Y coordinate + * @param w a width + * @param h a height + * @param btm bottom + * @param rght right + * @param isSelected a selection + */ protected void paintRightTabBorder( int tabIndex, Graphics g, int x, int y, int w, int h, int btm, int rght, @@ -806,9 +896,8 @@ public class MetalTabbedPaneUI extends BasicTabbedPaneUI { // Paint the background for the tab area if ( tabPane.isOpaque() ) { - Color bg = UIManager.getColor("TabbedPane.tabAreaBackground"); - if (bg != null) { - g.setColor(bg); + if (!c.isBackgroundSet() && (tabAreaBackground != null)) { + g.setColor(tabAreaBackground); } else { g.setColor( c.getBackground() ); @@ -843,6 +932,9 @@ public class MetalTabbedPaneUI extends BasicTabbedPaneUI { super.paint( g, c ); } + /** + * Paints highlights below tab. + */ protected void paintHighlightBelowTab( ) { } @@ -1159,7 +1251,13 @@ public class MetalTabbedPaneUI extends BasicTabbedPaneUI { return 0; } - // Don't rotate runs! + /** + * Returns {@code true} if tab runs should be rotated. + * + * @param tabPlacement a tab placement + * @param selectedRun a selected run + * @return {@code true} if tab runs should be rotated. + */ protected boolean shouldRotateTabRuns( int tabPlacement, int selectedRun ) { return false; } @@ -1201,6 +1299,9 @@ public class MetalTabbedPaneUI extends BasicTabbedPaneUI { */ public class TabbedPaneLayout extends BasicTabbedPaneUI.TabbedPaneLayout { + /** + * Constructs {@code TabbedPaneLayout}. + */ public TabbedPaneLayout() { MetalTabbedPaneUI.this.super(); } diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalTextFieldUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalTextFieldUI.java index 1eca55ed7d2..70db1ee921b 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalTextFieldUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalTextFieldUI.java @@ -50,6 +50,12 @@ import javax.swing.plaf.basic.*; @SuppressWarnings("serial") // Same-version serialization only public class MetalTextFieldUI extends BasicTextFieldUI { + /** + * Constructs {@code MetalTextFieldUI}. + * + * @param c a component + * @return the instance of {@code MetalTextFieldUI} + */ public static ComponentUI createUI(JComponent c) { return new MetalTextFieldUI(); } diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalToggleButtonUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalToggleButtonUI.java index d0d902eecee..d8375cec460 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalToggleButtonUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalToggleButtonUI.java @@ -60,8 +60,19 @@ public class MetalToggleButtonUI extends BasicToggleButtonUI { private static final Object METAL_TOGGLE_BUTTON_UI_KEY = new Object(); + /** + * The color of a focused toggle button. + */ protected Color focusColor; + + /** + * The color of a selected button. + */ protected Color selectColor; + + /** + * The color of a disabled text. + */ protected Color disabledTextColor; private boolean defaults_initialized = false; @@ -69,6 +80,13 @@ public class MetalToggleButtonUI extends BasicToggleButtonUI { // ******************************** // Create PLAF // ******************************** + + /** + * Constructs the {@code MetalToogleButtonUI}. + * + * @param b a component + * @return the {@code MetalToogleButtonUI}. + */ public static ComponentUI createUI(JComponent b) { AppContext appContext = AppContext.getAppContext(); MetalToggleButtonUI metalToggleButtonUI = @@ -101,14 +119,29 @@ public class MetalToggleButtonUI extends BasicToggleButtonUI { // ******************************** // Default Accessors // ******************************** + /** + * Returns the color of a selected button. + * + * @return the color of a selected button + */ protected Color getSelectColor() { return selectColor; } + /** + * Returns the color of a disabled text. + * + * @return the color of a disabled text + */ protected Color getDisabledTextColor() { return disabledTextColor; } + /** + * Returns the color of a focused toggle button. + * + * @return the color of a focused toggle button + */ protected Color getFocusColor() { return focusColor; } diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolBarUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolBarUI.java index 6fe5250cc18..b9899a3d877 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolBarUI.java @@ -158,6 +158,12 @@ public class MetalToolBarUI extends BasicToolBarUI return false; } + /** + * Constructs an instance of {@code MetalToolBarUI}. + * + * @param c a component + * @return an instance of {@code MetalToolBarUI} + */ public static ComponentUI createUI( JComponent c ) { return new MetalToolBarUI(); @@ -269,6 +275,11 @@ public class MetalToolBarUI extends BasicToolBarUI return new MetalDockingListener( toolBar ); } + /** + * Sets the offset of the mouse cursor inside the DragWindow. + * + * @param p the offset + */ protected void setDragOffset(Point p) { if (!GraphicsEnvironment.isHeadless()) { if (dragWindow == null) { @@ -346,17 +357,29 @@ public class MetalToolBarUI extends BasicToolBarUI } } - // No longer used. Cannot remove for compatibility reasons + /** + * No longer used. The class cannot be removed for compatibility reasons. + */ protected class MetalContainerListener extends BasicToolBarUI.ToolBarContListener {} - // No longer used. Cannot remove for compatibility reasons + /** + * No longer used. The class cannot be removed for compatibility reasons. + */ protected class MetalRolloverListener extends BasicToolBarUI.PropertyListener {} + /** + * {@code DockingListener} for {@code MetalToolBarUI}. + */ protected class MetalDockingListener extends DockingListener { private boolean pressedInBumps = false; + /** + * Constructs the {@code MetalDockingListener}. + * + * @param t an instance of {@code JToolBar} + */ public MetalDockingListener(JToolBar t) { super(t); } diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolTipUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolTipUI.java index 2a7a1b1e571..d851a162685 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolTipUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalToolTipUI.java @@ -58,13 +58,26 @@ public class MetalToolTipUI extends BasicToolTipUI { private Font smallFont; // Refer to note in getAcceleratorString about this field. private JToolTip tip; + + /** + * The space between strings. + */ public static final int padSpaceBetweenStrings = 12; private String acceleratorDelimiter; + /** + * Constructs an instance of the {@code MetalToolTipUI}. + */ public MetalToolTipUI() { super(); } + /** + * Returns an instance of the {@code MetalToolTipUI}. + * + * @param c a component + * @return an instance of the {@code MetalToolTipUI}. + */ public static ComponentUI createUI(JComponent c) { return sharedInstance; } @@ -148,6 +161,12 @@ public class MetalToolTipUI extends BasicToolTipUI { return d; } + /** + * If the accelerator is hidden, the method returns {@code true}, + * otherwise, returns {@code false}. + * + * @return {@code true} if the accelerator is hidden. + */ protected boolean isAcceleratorHidden() { Boolean b = (Boolean)UIManager.get("ToolTip.hideAccelerator"); return b != null && b.booleanValue(); @@ -162,6 +181,11 @@ public class MetalToolTipUI extends BasicToolTipUI { return retValue; } + /** + * Returns the accelerator string. + * + * @return the accelerator string. + */ // NOTE: This requires the tip field to be set before this is invoked. // As MetalToolTipUI is shared between all JToolTips the tip field is // set appropriately before this is invoked. Unfortunately this means diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalTreeUI.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalTreeUI.java index dee9e022f55..0e333ba630f 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalTreeUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalTreeUI.java @@ -93,20 +93,26 @@ public class MetalTreeUI extends BasicTreeUI { private int lineStyle = LEG_LINE_STYLE; private PropertyChangeListener lineStyleListener = new LineListener(); - // Boilerplate + /** + * Constructs the {@code MetalTreeUI}. + * + * @param x a component + * @return the instance of the {@code MetalTreeUI} + */ public static ComponentUI createUI(JComponent x) { return new MetalTreeUI(); } - public MetalTreeUI() - { + /** + * Constructs the {@code MetalTreeUI}. + */ + public MetalTreeUI() { super(); } - protected int getHorizontalLegBuffer() - { - return 3; - } + protected int getHorizontalLegBuffer() { + return 3; + } public void installUI( JComponent c ) { super.installUI( c ); @@ -123,24 +129,36 @@ public class MetalTreeUI extends BasicTreeUI { super.uninstallUI(c); } - /** this function converts between the string passed into the client property - * and the internal representation (currently and int) - * - */ + /** + * Converts between the string passed into the client property + * and the internal representation (currently and int) + * + * @param lineStyleFlag a flag + */ protected void decodeLineStyle(Object lineStyleFlag) { - if ( lineStyleFlag == null || - lineStyleFlag.equals(LEG_LINE_STYLE_STRING)){ - lineStyle = LEG_LINE_STYLE; // default case - } else { - if ( lineStyleFlag.equals(NO_STYLE_STRING) ) { - lineStyle = NO_LINE_STYLE; - } else if ( lineStyleFlag.equals(HORIZ_STYLE_STRING) ) { - lineStyle = HORIZ_LINE_STYLE; - } - } - + if ( lineStyleFlag == null || + lineStyleFlag.equals(LEG_LINE_STYLE_STRING)) { + lineStyle = LEG_LINE_STYLE; // default case + } else { + if ( lineStyleFlag.equals(NO_STYLE_STRING) ) { + lineStyle = NO_LINE_STYLE; + } else if ( lineStyleFlag.equals(HORIZ_STYLE_STRING) ) { + lineStyle = HORIZ_LINE_STYLE; + } + } } + /** + * Returns {@code true} if a point with X coordinate {@code mouseX} + * and Y coordinate {@code mouseY} is in expanded control. + * + * @param row a row + * @param rowLevel a row level + * @param mouseX X coordinate + * @param mouseY Y coordinate + * @return {@code true} if a point with X coordinate {@code mouseX} + * and Y coordinate {@code mouseY} is in expanded control. + */ protected boolean isLocationInExpandControl(int row, int rowLevel, int mouseX, int mouseY) { if(tree != null && !isLeaf(row)) { @@ -175,6 +193,12 @@ public class MetalTreeUI extends BasicTreeUI { } } + /** + * Paints the horizontal separators. + * + * @param g an instance of {@code Graphics} + * @param c a component + */ protected void paintHorizontalSeparators(Graphics g, JComponent c) { g.setColor( lineColor ); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiButtonUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiButtonUI.java index 77fbf3129ac..e8b81e25ec2 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiButtonUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiButtonUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiButtonUI extends ButtonUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiButtonUI extends ButtonUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiButtonUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiColorChooserUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiColorChooserUI.java index bd15686032e..8881abbc8ba 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiColorChooserUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiColorChooserUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiColorChooserUI extends ColorChooserUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiColorChooserUI extends ColorChooserUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiColorChooserUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiComboBoxUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiComboBoxUI.java index 4008fd02c74..ee3cc9848a6 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiComboBoxUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiComboBoxUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,6 +58,8 @@ public class MultiComboBoxUI extends ComboBoxUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -138,6 +140,9 @@ public class MultiComboBoxUI extends ComboBoxUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiComboBoxUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiDesktopIconUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiDesktopIconUI.java index ba78eb789b1..a41a72931a1 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiDesktopIconUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiDesktopIconUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiDesktopIconUI extends DesktopIconUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiDesktopIconUI extends DesktopIconUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiDesktopIconUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiDesktopPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiDesktopPaneUI.java index 53569defea5..7f99cfad12d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiDesktopPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiDesktopPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiDesktopPaneUI extends DesktopPaneUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiDesktopPaneUI extends DesktopPaneUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiDesktopPaneUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiFileChooserUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiFileChooserUI.java index b76a6a8ae6b..b2ce34e1b6d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiFileChooserUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiFileChooserUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -62,6 +62,8 @@ public class MultiFileChooserUI extends FileChooserUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -181,6 +183,9 @@ public class MultiFileChooserUI extends FileChooserUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiFileChooserUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiInternalFrameUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiInternalFrameUI.java index dd4509c550a..9b9085522ea 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiInternalFrameUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiInternalFrameUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiInternalFrameUI extends InternalFrameUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiInternalFrameUI extends InternalFrameUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiInternalFrameUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiLabelUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiLabelUI.java index 222b2218563..844cc6d7969 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiLabelUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiLabelUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiLabelUI extends LabelUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiLabelUI extends LabelUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiLabelUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiListUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiListUI.java index 48a05ac2df5..aa541be2cfd 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiListUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiListUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -60,6 +60,8 @@ public class MultiListUI extends ListUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -146,6 +148,9 @@ public class MultiListUI extends ListUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiListUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiMenuBarUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiMenuBarUI.java index b15797ef518..70596af4a4f 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiMenuBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiMenuBarUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiMenuBarUI extends MenuBarUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiMenuBarUI extends MenuBarUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiMenuBarUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiMenuItemUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiMenuItemUI.java index e4c27e6878e..0b9458e4513 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiMenuItemUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiMenuItemUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,6 +58,8 @@ public class MultiMenuItemUI extends MenuItemUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -103,6 +105,9 @@ public class MultiMenuItemUI extends MenuItemUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiMenuItemUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiOptionPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiOptionPaneUI.java index 630b328c048..4e5408f5f04 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiOptionPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiOptionPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,6 +58,8 @@ public class MultiOptionPaneUI extends OptionPaneUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -123,6 +125,9 @@ public class MultiOptionPaneUI extends OptionPaneUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiOptionPaneUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiPanelUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiPanelUI.java index 4bdbe43b968..27799d9657a 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiPanelUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiPanelUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiPanelUI extends PanelUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiPanelUI extends PanelUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiPanelUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiPopupMenuUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiPopupMenuUI.java index 59002ea1566..d4c13051a91 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiPopupMenuUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiPopupMenuUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -60,6 +60,8 @@ public class MultiPopupMenuUI extends PopupMenuUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -133,6 +135,9 @@ public class MultiPopupMenuUI extends PopupMenuUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiPopupMenuUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiProgressBarUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiProgressBarUI.java index fd39d724a2b..6a1d01ec16b 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiProgressBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiProgressBarUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiProgressBarUI extends ProgressBarUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiProgressBarUI extends ProgressBarUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiProgressBarUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiRootPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiRootPaneUI.java index 601f21129d0..46e60d7e319 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiRootPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiRootPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,6 +58,8 @@ public class MultiRootPaneUI extends RootPaneUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -99,6 +101,9 @@ public class MultiRootPaneUI extends RootPaneUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiRootPaneUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiScrollBarUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiScrollBarUI.java index b372df70913..a7d5381435a 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiScrollBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiScrollBarUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiScrollBarUI extends ScrollBarUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiScrollBarUI extends ScrollBarUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiScrollBarUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiScrollPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiScrollPaneUI.java index 1894a6309c0..f7b7c44289a 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiScrollPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiScrollPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiScrollPaneUI extends ScrollPaneUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiScrollPaneUI extends ScrollPaneUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiScrollPaneUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiSeparatorUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiSeparatorUI.java index 29f6a7fae26..d67cc0407a0 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiSeparatorUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiSeparatorUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiSeparatorUI extends SeparatorUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiSeparatorUI extends SeparatorUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiSeparatorUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiSliderUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiSliderUI.java index 8bc53ee81c1..65da1c18358 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiSliderUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiSliderUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiSliderUI extends SliderUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -96,8 +98,11 @@ public class MultiSliderUI extends SliderUI { /** * Returns a multiplexing UI instance if any of the auxiliary - * LookAndFeels supports this UI. Otherwise, just returns the + * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiSliderUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java index be2c9c0a277..2c0ce087dc9 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiSpinnerUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,6 +58,8 @@ public class MultiSpinnerUI extends SpinnerUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -99,6 +101,9 @@ public class MultiSpinnerUI extends SpinnerUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiSpinnerUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiSplitPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiSplitPaneUI.java index 5b637f723f3..6c0eb44f3e7 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiSplitPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiSplitPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,6 +58,8 @@ public class MultiSplitPaneUI extends SplitPaneUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -171,6 +173,9 @@ public class MultiSplitPaneUI extends SplitPaneUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiSplitPaneUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTabbedPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTabbedPaneUI.java index 9624ccba1ce..c14f29125e2 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTabbedPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTabbedPaneUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -59,6 +59,8 @@ public class MultiTabbedPaneUI extends TabbedPaneUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -145,6 +147,9 @@ public class MultiTabbedPaneUI extends TabbedPaneUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiTabbedPaneUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTableHeaderUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTableHeaderUI.java index 9b1695168a7..417e5dcbcef 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTableHeaderUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTableHeaderUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiTableHeaderUI extends TableHeaderUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiTableHeaderUI extends TableHeaderUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiTableHeaderUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTableUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTableUI.java index a281626617e..7a059e33b13 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTableUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTableUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiTableUI extends TableUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiTableUI extends TableUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiTableUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTextUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTextUI.java index 7c704a5971e..30dae8fdb69 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTextUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTextUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -65,6 +65,8 @@ public class MultiTextUI extends TextUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -248,6 +250,9 @@ public class MultiTextUI extends TextUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiTextUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiToolBarUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiToolBarUI.java index 1922c2679d4..172524e9c94 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiToolBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiToolBarUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiToolBarUI extends ToolBarUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiToolBarUI extends ToolBarUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiToolBarUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiToolTipUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiToolTipUI.java index c2848af6858..e6062120733 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiToolTipUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiToolTipUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiToolTipUI extends ToolTipUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiToolTipUI extends ToolTipUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiToolTipUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTreeUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTreeUI.java index 8cc13957303..0828ded9e03 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiTreeUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiTreeUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -60,6 +60,8 @@ public class MultiTreeUI extends TreeUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -239,6 +241,9 @@ public class MultiTreeUI extends TreeUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiTreeUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/multi/MultiViewportUI.java b/jdk/src/share/classes/javax/swing/plaf/multi/MultiViewportUI.java index 7f6c162b72b..fff9e2eaa0f 100644 --- a/jdk/src/share/classes/javax/swing/plaf/multi/MultiViewportUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/multi/MultiViewportUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,8 @@ public class MultiViewportUI extends ViewportUI { * Returns the list of UIs associated with this multiplexing UI. This * allows processing of the UIs by an application aware of multiplexing * UIs on components. + * + * @return an array of the UI delegates */ public ComponentUI[] getUIs() { return MultiLookAndFeel.uisToArray(uis); @@ -98,6 +100,9 @@ public class MultiViewportUI extends ViewportUI { * Returns a multiplexing UI instance if any of the auxiliary * LookAndFeels supports this UI. Otherwise, just returns the * UI object obtained from the default LookAndFeel. + * + * @param a the component to create the UI for + * @return the UI delegate created */ public static ComponentUI createUI(JComponent a) { ComponentUI mui = new MultiViewportUI(); diff --git a/jdk/src/share/classes/javax/swing/plaf/nimbus/AbstractRegionPainter.java b/jdk/src/share/classes/javax/swing/plaf/nimbus/AbstractRegionPainter.java index f10dfd4298f..c41d9247138 100644 --- a/jdk/src/share/classes/javax/swing/plaf/nimbus/AbstractRegionPainter.java +++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/AbstractRegionPainter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,6 +31,7 @@ import javax.swing.*; import javax.swing.plaf.UIResource; import javax.swing.Painter; import java.awt.print.PrinterGraphics; +import sun.reflect.misc.MethodUtil; /** * Convenient base class for defining Painter instances for rendering a @@ -420,6 +421,13 @@ public abstract class AbstractRegionPainter implements Painter { * @param property The name of a bean style property or client property * @param defaultColor The color to return if no color was obtained from * the component. + * @param saturationOffset additively modifies the HSB saturation component + * of the color returned (ignored if default color is returned). + * @param brightnessOffset additively modifies the HSB brightness component + * of the color returned (ignored if default color is returned). + * @param alphaOffset additively modifies the ARGB alpha component of the + * color returned (ignored if default color is returned). + * * @return The color that was obtained from the component or defaultColor */ protected final Color getComponentColor(JComponent c, String property, @@ -445,8 +453,8 @@ public abstract class AbstractRegionPainter implements Painter { } else { String s = "get" + Character.toUpperCase(property.charAt(0)) + property.substring(1); try { - Method method = c.getClass().getMethod(s); - color = (Color) method.invoke(c); + Method method = MethodUtil.getMethod(c.getClass(), s, null); + color = (Color) MethodUtil.invoke(method, c, null); } catch (Exception e) { //don't do anything, it just didn't work, that's all. //This could be a normal occurance if you use a property diff --git a/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java b/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java index e38a0789e3c..bcdae78da79 100644 --- a/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java +++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java @@ -653,7 +653,7 @@ public final class NimbusStyle extends SynthStyle { // strip off the prefix, if there is one. String fullKey = key.toString(); - String partialKey = fullKey.substring(fullKey.indexOf(".") + 1); + String partialKey = fullKey.substring(fullKey.indexOf('.') + 1); Object obj = null; int xstate = getExtendedState(ctx, v); diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java index 74e13aaa900..4bfa159602c 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthButtonUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -138,9 +138,7 @@ public class SynthButtonUI extends BasicButtonUI implements } SynthContext getContext(JComponent c, int state) { - Region region = SynthLookAndFeel.getRegion(c); - return SynthContext.getContext(SynthContext.class, c, region, - style, state); + return SynthContext.getContext(c, style, state); } /** @@ -515,6 +513,13 @@ public class SynthButtonUI extends BasicButtonUI implements /** * Returns the Icon used in calculating the * preferred/minimum/maximum size. + * + * @param b specifies the {@code AbstractButton} + * used when calculating the preferred/minimum/maximum + * size. + * + * @return the Icon used in calculating the + * preferred/minimum/maximum size. */ protected Icon getSizingIcon(AbstractButton b) { Icon icon = getEnabledIcon(b, b.getIcon()); diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthColorChooserUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthColorChooserUI.java index 92566845636..72ab2b09a16 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthColorChooserUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthColorChooserUI.java @@ -128,8 +128,7 @@ public class SynthColorChooserUI extends BasicColorChooserUI implements } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java index b36b4cf4984..b50e0e4887d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthComboBoxUI.java @@ -208,8 +208,7 @@ public class SynthComboBoxUI extends BasicComboBoxUI implements } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java index 6d89a4a06c8..64b6e536f79 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthContext.java @@ -24,8 +24,9 @@ */ package javax.swing.plaf.synth; -import javax.swing.*; -import java.util.*; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import javax.swing.JComponent; /** * An immutable transient object containing contextual information about @@ -39,59 +40,32 @@ import java.util.*; * @author Scott Violet */ public class SynthContext { - private static final Map> contextMap; + private static final Queue queue = new ConcurrentLinkedQueue<>(); private JComponent component; private Region region; private SynthStyle style; private int state; - - static { - contextMap = new HashMap>(); + static SynthContext getContext(JComponent c, SynthStyle style, int state) { + return getContext(c, SynthLookAndFeel.getRegion(c), style, state); } - - static SynthContext getContext(Class type, JComponent component, + static SynthContext getContext(JComponent component, Region region, SynthStyle style, int state) { - SynthContext context = null; - - synchronized(contextMap) { - List instances = contextMap.get(type); - - if (instances != null) { - int size = instances.size(); - - if (size > 0) { - context = instances.remove(size - 1); - } - } - } + SynthContext context = queue.poll(); if (context == null) { - try { - context = (SynthContext)type.newInstance(); - } catch (IllegalAccessException iae) { - } catch (InstantiationException ie) { - } + context = new SynthContext(); } context.reset(component, region, style, state); return context; } static void releaseContext(SynthContext context) { - synchronized(contextMap) { - List instances = contextMap.get(context.getClass()); - - if (instances == null) { - instances = new ArrayList(5); - contextMap.put(context.getClass(), instances); - } - instances.add(context); - } + queue.offer(context); } - SynthContext() { } diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopIconUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopIconUI.java index e10014100d9..8da1fe0cf3b 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopIconUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopIconUI.java @@ -144,9 +144,7 @@ public class SynthDesktopIconUI extends BasicDesktopIconUI } private SynthContext getContext(JComponent c, int state) { - Region region = SynthLookAndFeel.getRegion(c); - return SynthContext.getContext(SynthContext.class, c, region, - style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopPaneUI.java index 40300565b9a..6259171317b 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopPaneUI.java @@ -432,8 +432,7 @@ public class SynthDesktopPaneUI extends BasicDesktopPaneUI implements } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java index 2ccf59268de..69489197d6a 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthEditorPaneUI.java @@ -139,8 +139,7 @@ public class SynthEditorPaneUI extends BasicEditorPaneUI implements SynthUI { } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java index 9f68e956a48..8464dd25e49 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthGraphicsUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -137,6 +137,9 @@ public class SynthGraphicsUtils { * @param iconR Rectangle to place icon bounds in * @param textR Rectangle to place text in * @param iconTextGap gap between icon and text + * + * @return by reference, the location to + * place the icon and text. */ public String layoutText(SynthContext ss, FontMetrics fm, String text, Icon icon, int hAlign, @@ -166,6 +169,8 @@ public class SynthGraphicsUtils { * @param font Font to use * @param metrics FontMetrics, may be ignored * @param text Text to get size of. + * + * @return the size of the passed in string. */ public int computeStringWidth(SynthContext ss, Font font, FontMetrics metrics, String text) { @@ -187,6 +192,8 @@ public class SynthGraphicsUtils { * @param iconTextGap gap between icon and text * @param mnemonicIndex Index into text to render the mnemonic at, -1 * indicates no mnemonic. + * + * @return the minimum size needed to properly render an icon and text. */ public Dimension getMinimumSize(SynthContext ss, Font font, String text, Icon icon, int hAlign, int vAlign, int hTextPosition, @@ -218,6 +225,8 @@ public class SynthGraphicsUtils { * @param iconTextGap gap between icon and text * @param mnemonicIndex Index into text to render the mnemonic at, -1 * indicates no mnemonic. + * + * @return the maximum size needed to properly render an icon and text. */ public Dimension getMaximumSize(SynthContext ss, Font font, String text, Icon icon, int hAlign, int vAlign, int hTextPosition, @@ -263,6 +272,8 @@ public class SynthGraphicsUtils { * @param iconTextGap gap between icon and text * @param mnemonicIndex Index into text to render the mnemonic at, -1 * indicates no mnemonic. + * + * @return the preferred size needed to properly render an icon and text. */ public Dimension getPreferredSize(SynthContext ss, Font font, String text, Icon icon, int hAlign, int vAlign, int hTextPosition, diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java index abf490ce863..92ad059085d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameTitlePane.java @@ -68,8 +68,7 @@ class SynthInternalFrameTitlePane extends BasicInternalFrameTitlePane } public SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private Region getRegion(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameUI.java index 34c94cdbc8f..c5c1ef7fdad 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthInternalFrameUI.java @@ -141,8 +141,7 @@ public class SynthInternalFrameUI extends BasicInternalFrameUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthLabelUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthLabelUI.java index 45031e99188..22e57e5e4a8 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthLabelUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthLabelUI.java @@ -91,8 +91,7 @@ public class SynthLabelUI extends BasicLabelUI implements SynthUI { } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthListUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthListUI.java index 58a443acb44..6a36a58a14f 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthListUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthListUI.java @@ -188,8 +188,7 @@ public class SynthListUI extends BasicListUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuBarUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuBarUI.java index 9c1f9cba227..1f096646495 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuBarUI.java @@ -116,8 +116,7 @@ public class SynthMenuBarUI extends BasicMenuBarUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java index 19ac0a760b3..956f76f1fb3 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuItemUI.java @@ -170,8 +170,7 @@ public class SynthMenuItemUI extends BasicMenuItemUI implements } SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } SynthContext getContext(JComponent c, Region region) { @@ -179,8 +178,7 @@ public class SynthMenuItemUI extends BasicMenuItemUI implements } private SynthContext getContext(JComponent c, Region region, int state) { - return SynthContext.getContext(SynthContext.class, c, - region, accStyle, state); + return SynthContext.getContext(c, region, accStyle, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java index 3f53f461ecc..7bb66a25c93 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthMenuUI.java @@ -170,9 +170,7 @@ public class SynthMenuUI extends BasicMenuUI } SynthContext getContext(JComponent c, int state) { - Region region = SynthLookAndFeel.getRegion(c); - return SynthContext.getContext(SynthContext.class, c, region, - style, state); + return SynthContext.getContext(c, style, state); } SynthContext getContext(JComponent c, Region region) { @@ -180,8 +178,7 @@ public class SynthMenuUI extends BasicMenuUI } private SynthContext getContext(JComponent c, Region region, int state) { - return SynthContext.getContext(SynthContext.class, c, - region, accStyle, state); + return SynthContext.getContext(c, region, accStyle, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthOptionPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthOptionPaneUI.java index 42d454cf8d9..de6f2a7135e 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthOptionPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthOptionPaneUI.java @@ -140,8 +140,7 @@ public class SynthOptionPaneUI extends BasicOptionPaneUI implements } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthPanelUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthPanelUI.java index ddfff5c1597..73f37ff530b 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthPanelUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthPanelUI.java @@ -127,8 +127,7 @@ public class SynthPanelUI extends BasicPanelUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java index ef38ae11387..a15bb509e78 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthParser.java @@ -67,6 +67,7 @@ import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import com.sun.beans.decoder.DocumentHandler; +import sun.reflect.misc.ReflectUtil; class SynthParser extends DefaultHandler { // @@ -648,7 +649,7 @@ class SynthParser extends DefaultHandler { } else { try { - typeClass = Class.forName(typeName.substring( + typeClass = ReflectUtil.forName(typeName.substring( 0, classIndex)); } catch (ClassNotFoundException cnfe) { throw new SAXException("Unknown class: " + diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java index d228abab79a..cbb09f29212 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthPopupMenuUI.java @@ -123,8 +123,7 @@ public class SynthPopupMenuUI extends BasicPopupMenuUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthProgressBarUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthProgressBarUI.java index 1afc81bb1f4..c37ce490368 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthProgressBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthProgressBarUI.java @@ -138,8 +138,7 @@ public class SynthProgressBarUI extends BasicProgressBarUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthRootPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthRootPaneUI.java index 0d437de7613..1115fe35551 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthRootPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthRootPaneUI.java @@ -80,8 +80,7 @@ public class SynthRootPaneUI extends BasicRootPaneUI implements SynthUI { } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollBarUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollBarUI.java index d3e948d899c..498d69e1e86 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollBarUI.java @@ -185,8 +185,7 @@ public class SynthScrollBarUI extends BasicScrollBarUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private SynthContext getContext(JComponent c, Region region) { @@ -199,8 +198,7 @@ public class SynthScrollBarUI extends BasicScrollBarUI if (region == Region.SCROLL_BAR_THUMB) { style = thumbStyle; } - return SynthContext.getContext(SynthContext.class, c, region, style, - state); + return SynthContext.getContext(c, region, style, state); } private int getComponentState(JComponent c, Region region) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollPaneUI.java index 6b261546408..6b3e29602de 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthScrollPaneUI.java @@ -211,8 +211,7 @@ public class SynthScrollPaneUI extends BasicScrollPaneUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSeparatorUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSeparatorUI.java index 7e759d4e3be..a222a428080 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSeparatorUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSeparatorUI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -78,6 +78,9 @@ public class SynthSeparatorUI extends SeparatorUI /** * Installs default setting. This method is called when a * {@code LookAndFeel} is installed. + * + * @param c specifies the {@code JSeparator} for the installed + * {@code LookAndFeel}. */ public void installDefaults(JSeparator c) { updateStyle(c); @@ -109,6 +112,9 @@ public class SynthSeparatorUI extends SeparatorUI /** * Uninstalls default setting. This method is called when a * {@code LookAndFeel} is uninstalled. + * + * @param c specifies the {@code JSeparator} for the (un)installed + * {@code LookAndFeel}. */ public void uninstallDefaults(JSeparator c) { SynthContext context = getContext(c, ENABLED); @@ -121,6 +127,9 @@ public class SynthSeparatorUI extends SeparatorUI /** * Installs listeners. This method is called when a * {@code LookAndFeel} is installed. + * + * @param c specifies the {@code JSeparator} for the installed + * {@code LookAndFeel}. */ public void installListeners(JSeparator c) { c.addPropertyChangeListener(this); @@ -129,6 +138,9 @@ public class SynthSeparatorUI extends SeparatorUI /** * Uninstalls listeners. This method is called when a * {@code LookAndFeel} is uninstalled. + * + * @param c specifies the {@code JSeparator} for the (un)installed + * {@code LookAndFeel}. */ public void uninstallListeners(JSeparator c) { c.removePropertyChangeListener(this); @@ -248,8 +260,7 @@ public class SynthSeparatorUI extends SeparatorUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } public void propertyChange(PropertyChangeEvent evt) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSliderUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSliderUI.java index 65d461264dc..5cc7cd48606 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSliderUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSliderUI.java @@ -722,8 +722,7 @@ public class SynthSliderUI extends BasicSliderUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private SynthContext getContext(JComponent c, Region subregion) { @@ -732,14 +731,13 @@ public class SynthSliderUI extends BasicSliderUI private SynthContext getContext(JComponent c, Region subregion, int state) { SynthStyle style = null; - Class klass = SynthContext.class; if (subregion == Region.SLIDER_TRACK) { style = sliderTrackStyle; } else if (subregion == Region.SLIDER_THUMB) { style = sliderThumbStyle; } - return SynthContext.getContext(klass, c, subregion, style, state); + return SynthContext.getContext(c, subregion, style, state); } private int getComponentState(JComponent c, Region region) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSpinnerUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSpinnerUI.java index d8bc4feea52..a1293dfdadd 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSpinnerUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSpinnerUI.java @@ -278,8 +278,7 @@ public class SynthSpinnerUI extends BasicSpinnerUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } /** diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java index 2c5031c03d6..f82ccb37fab 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java @@ -209,8 +209,7 @@ public class SynthSplitPaneUI extends BasicSplitPaneUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } SynthContext getContext(JComponent c, Region region) { @@ -219,11 +218,9 @@ public class SynthSplitPaneUI extends BasicSplitPaneUI private SynthContext getContext(JComponent c, Region region, int state) { if (region == Region.SPLIT_PANE_DIVIDER) { - return SynthContext.getContext(SynthContext.class, c, region, - dividerStyle, state); + return SynthContext.getContext(c, region, dividerStyle, state); } - return SynthContext.getContext(SynthContext.class, c, region, - style, state); + return SynthContext.getContext(c, region, style, state); } private int getComponentState(JComponent c, Region subregion) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java index df09ba5fcfa..211e8a2c331 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTabbedPaneUI.java @@ -235,13 +235,11 @@ public class SynthTabbedPaneUI extends BasicTabbedPaneUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c),style, state); + return SynthContext.getContext(c, style, state); } private SynthContext getContext(JComponent c, Region subregion, int state){ SynthStyle style = null; - Class klass = SynthContext.class; if (subregion == Region.TABBED_PANE_TAB) { style = tabStyle; @@ -252,7 +250,7 @@ public class SynthTabbedPaneUI extends BasicTabbedPaneUI else if (subregion == Region.TABBED_PANE_CONTENT) { style = tabContentStyle; } - return SynthContext.getContext(klass, c, subregion, style, state); + return SynthContext.getContext(c, subregion, style, state); } /** diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableHeaderUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableHeaderUI.java index a988692a4aa..f09f86d6548 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableHeaderUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableHeaderUI.java @@ -193,8 +193,7 @@ public class SynthTableHeaderUI extends BasicTableHeaderUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } /** diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java index da49bddc4c2..194e9deee84 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTableUI.java @@ -246,8 +246,7 @@ public class SynthTableUI extends BasicTableUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } // diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java index 441698ce0a9..33214dad926 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextAreaUI.java @@ -119,8 +119,7 @@ public class SynthTextAreaUI extends BasicTextAreaUI implements SynthUI { } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } /** diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java index 7028a5a5999..6adb7538e88 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTextFieldUI.java @@ -157,8 +157,7 @@ public class SynthTextFieldUI extends BasicTextFieldUI implements SynthUI { } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } /** diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolBarUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolBarUI.java index f65fdd14dc1..51d2fefd17e 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolBarUI.java @@ -178,19 +178,17 @@ public class SynthToolBarUI extends BasicToolBarUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private SynthContext getContext(JComponent c, Region region, SynthStyle style) { - return SynthContext.getContext(SynthContext.class, c, region, + return SynthContext.getContext(c, region, style, getComponentState(c, region)); } private SynthContext getContext(JComponent c, Region region, SynthStyle style, int state) { - return SynthContext.getContext(SynthContext.class, c, region, - style, state); + return SynthContext.getContext(c, region, style, state); } private int getComponentState(JComponent c, Region region) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolTipUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolTipUI.java index afd49f4a7e5..dc42debba7d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolTipUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthToolTipUI.java @@ -107,8 +107,7 @@ public class SynthToolTipUI extends BasicToolTipUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private int getComponentState(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java index a214532ed56..d8107879254 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthTreeUI.java @@ -173,8 +173,7 @@ public class SynthTreeUI extends BasicTreeUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - SynthLookAndFeel.getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private SynthContext getContext(JComponent c, Region region) { @@ -182,8 +181,7 @@ public class SynthTreeUI extends BasicTreeUI } private SynthContext getContext(JComponent c, Region region, int state) { - return SynthContext.getContext(SynthContext.class, c, - region, cellStyle, state); + return SynthContext.getContext(c, region, cellStyle, state); } private int getComponentState(JComponent c, Region region) { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthViewportUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthViewportUI.java index 4c5a9b0cd88..dc3e6c6e1a1 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthViewportUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthViewportUI.java @@ -141,8 +141,7 @@ public class SynthViewportUI extends ViewportUI } private SynthContext getContext(JComponent c, int state) { - return SynthContext.getContext(SynthContext.class, c, - getRegion(c), style, state); + return SynthContext.getContext(c, style, state); } private Region getRegion(JComponent c) { diff --git a/jdk/src/share/classes/javax/swing/table/DefaultTableColumnModel.java b/jdk/src/share/classes/javax/swing/table/DefaultTableColumnModel.java index 96193cb35fd..7e02789f837 100644 --- a/jdk/src/share/classes/javax/swing/table/DefaultTableColumnModel.java +++ b/jdk/src/share/classes/javax/swing/table/DefaultTableColumnModel.java @@ -716,6 +716,8 @@ public class DefaultTableColumnModel implements TableColumnModel, /** * Creates a new default list selection model. + * + * @return a newly created default list selection model. */ protected ListSelectionModel createSelectionModel() { return new DefaultListSelectionModel(); diff --git a/jdk/src/share/classes/javax/swing/table/DefaultTableModel.java b/jdk/src/share/classes/javax/swing/table/DefaultTableModel.java index 74b88c1160d..251738ae40d 100644 --- a/jdk/src/share/classes/javax/swing/table/DefaultTableModel.java +++ b/jdk/src/share/classes/javax/swing/table/DefaultTableModel.java @@ -335,6 +335,8 @@ public class DefaultTableModel extends AbstractTableModel implements Serializabl * * @see #setColumnCount * @since 1.3 + * + * @param rowCount number of rows in the model */ public void setRowCount(int rowCount) { setNumRows(rowCount); @@ -577,6 +579,9 @@ public class DefaultTableModel extends AbstractTableModel implements Serializabl * element going to row 0, etc. This method will send a * tableChanged notification message to all the listeners. * + * @param columnName identifier of the newly created column + * @param columnData new data to be added to the column + * * @see #addColumn(Object, Vector) */ public void addColumn(Object columnName, Object[] columnData) { diff --git a/jdk/src/share/classes/javax/swing/table/JTableHeader.java b/jdk/src/share/classes/javax/swing/table/JTableHeader.java index 3995cccc288..5e923b1356d 100644 --- a/jdk/src/share/classes/javax/swing/table/JTableHeader.java +++ b/jdk/src/share/classes/javax/swing/table/JTableHeader.java @@ -336,6 +336,10 @@ public class JTableHeader extends JComponent implements TableColumnModelListener * Returns the index of the column that point lies in, or -1 if it * lies out of bounds. * + * @param point if this point lies within a column, the index of + * that column will be returned; otherwise it is out of bounds + * and -1 is returned + * * @return the index of the column that point lies in, or -1 if it * lies out of bounds */ @@ -352,6 +356,8 @@ public class JTableHeader extends JComponent implements TableColumnModelListener * When the column parameter is out of bounds this method uses the * same conventions as the JTable method getCellRect. * + * @param column index of the column + * * @return the rectangle containing the header tile at column * @see JTable#getCellRect */ @@ -883,6 +889,10 @@ public class JTableHeader extends JComponent implements TableColumnModelListener /** * Constructs an AccessiblJTableHeaaderEntry * @since 1.4 + * + * @param c the column index + * @param p the parent JTableHeader + * @param t the table JTable */ public AccessibleJTableHeaderEntry(int c, JTableHeader p, JTable t) { parent = p; diff --git a/jdk/src/share/classes/javax/swing/table/TableCellRenderer.java b/jdk/src/share/classes/javax/swing/table/TableCellRenderer.java index 892220bc47c..585d9221482 100644 --- a/jdk/src/share/classes/javax/swing/table/TableCellRenderer.java +++ b/jdk/src/share/classes/javax/swing/table/TableCellRenderer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -86,6 +86,9 @@ public interface TableCellRenderer { * drawing the header, the value of * row is -1 * @param column the column index of the cell being drawn + * + * @return the component used for drawing the cell. + * * @see javax.swing.JComponent#isPaintingForPrint() */ Component getTableCellRendererComponent(JTable table, Object value, diff --git a/jdk/src/share/classes/javax/swing/table/TableColumn.java b/jdk/src/share/classes/javax/swing/table/TableColumn.java index 713bf5483dc..1f116c47832 100644 --- a/jdk/src/share/classes/javax/swing/table/TableColumn.java +++ b/jdk/src/share/classes/javax/swing/table/TableColumn.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -201,6 +201,11 @@ public class TableColumn extends Object implements Serializable { * Cover method, using a default width of 75, a null * renderer and a null editor. * @see #TableColumn(int, int, TableCellRenderer, TableCellEditor) + * + * @param modelIndex the index of the column in the model + * that supplies the data for this column in the table; + * the model index remains the same even when columns + * are reordered in the view */ public TableColumn(int modelIndex) { this(modelIndex, 75, null, null); @@ -210,6 +215,12 @@ public class TableColumn extends Object implements Serializable { * Cover method, using a null renderer and a * null editor. * @see #TableColumn(int, int, TableCellRenderer, TableCellEditor) + * + * @param modelIndex the index of the column in the model + * that supplies the data for this column in the table; + * the model index remains the same even when columns + * are reordered in the view + * @param width this column's preferred width and initial width */ public TableColumn(int modelIndex, int width) { this(modelIndex, width, null, null); diff --git a/jdk/src/share/classes/javax/swing/table/TableColumnModel.java b/jdk/src/share/classes/javax/swing/table/TableColumnModel.java index b6c308c0ea7..eaaa8447ef7 100644 --- a/jdk/src/share/classes/javax/swing/table/TableColumnModel.java +++ b/jdk/src/share/classes/javax/swing/table/TableColumnModel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -162,6 +162,9 @@ public interface TableColumnModel * model. If the column index for a given X coordinate in 2D space is * required, JTable.columnAtPoint can be used instead. * + * @param xPosition width from the start of the first column in + * the model. + * * @return the index of the column; or -1 if no column is found * @see javax.swing.JTable#columnAtPoint */ diff --git a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java index a7a109f8c91..e42d549791a 100644 --- a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java +++ b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java @@ -1809,7 +1809,7 @@ public abstract class AbstractDocument implements Document, Serializable { if (getAttributeCount() > 0) { out.println(""); // dump the attributes - Enumeration names = attributes.getAttributeNames(); + Enumeration names = attributes.getAttributeNames(); while (names.hasMoreElements()) { Object name = names.nextElement(); indent(out, indentAmount + 1); @@ -2193,7 +2193,7 @@ public abstract class AbstractDocument implements Document, Serializable { * Enumeration. * @return the children of the receiver as an Enumeration */ - public abstract Enumeration children(); + public abstract Enumeration children(); // --- serialization --------------------------------------------- @@ -2456,7 +2456,7 @@ public abstract class AbstractDocument implements Document, Serializable { * Enumeration. * @return the children of the receiver */ - public Enumeration children() { + public Enumeration children() { if(nchildren == 0) return null; @@ -2610,7 +2610,7 @@ public abstract class AbstractDocument implements Document, Serializable { * Enumeration. * @return the children of the receiver */ - public Enumeration children() { + public Enumeration children() { return null; } diff --git a/jdk/src/share/classes/javax/swing/text/AbstractWriter.java b/jdk/src/share/classes/javax/swing/text/AbstractWriter.java index f2f7f746ee4..cfe619b801f 100644 --- a/jdk/src/share/classes/javax/swing/text/AbstractWriter.java +++ b/jdk/src/share/classes/javax/swing/text/AbstractWriter.java @@ -668,7 +668,7 @@ public abstract class AbstractWriter { */ protected void writeAttributes(AttributeSet attr) throws IOException { - Enumeration names = attr.getAttributeNames(); + Enumeration names = attr.getAttributeNames(); while (names.hasMoreElements()) { Object name = names.nextElement(); write(" " + name + "=" + attr.getAttribute(name)); diff --git a/jdk/src/share/classes/javax/swing/text/DateFormatter.java b/jdk/src/share/classes/javax/swing/text/DateFormatter.java index e935053bfc8..b82788fb6a2 100644 --- a/jdk/src/share/classes/javax/swing/text/DateFormatter.java +++ b/jdk/src/share/classes/javax/swing/text/DateFormatter.java @@ -108,8 +108,8 @@ public class DateFormatter extends InternationalFormatter { /** * Returns the field that will be adjusted by adjustValue. */ - Object getAdjustField(int start, Map attributes) { - Iterator attrs = attributes.keySet().iterator(); + Object getAdjustField(int start, Map attributes) { + Iterator attrs = attributes.keySet().iterator(); while (attrs.hasNext()) { Object key = attrs.next(); @@ -127,7 +127,7 @@ public class DateFormatter extends InternationalFormatter { * Adjusts the Date if FieldPosition identifies a known calendar * field. */ - Object adjustValue(Object value, Map attributes, Object key, + Object adjustValue(Object value, Map attributes, Object key, int direction) throws BadLocationException, ParseException { if (key != null) { diff --git a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java index 0a4df2c0a1d..ee9cda6e85f 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultFormatter.java @@ -246,12 +246,12 @@ public class DefaultFormatter extends JFormattedTextField.AbstractFormatter } } if (vc != null) { - Constructor cons; + Constructor cons; try { ReflectUtil.checkPackageAccess(vc); SwingUtilities2.checkAccess(vc.getModifiers()); - cons = vc.getConstructor(new Class[]{String.class}); + cons = vc.getConstructor(new Class[]{String.class}); } catch (NoSuchMethodException nsme) { cons = null; diff --git a/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java b/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java index a5ce0633f74..78788cbfad1 100644 --- a/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java +++ b/jdk/src/share/classes/javax/swing/text/DefaultStyledDocument.java @@ -1048,8 +1048,9 @@ public class DefaultStyledDocument extends AbstractDocument implements StyledDoc styleChangeListener = createStyleChangeListener(); } if (styleChangeListener != null && styles != null) { - Enumeration styleNames = styles.getStyleNames(); - Vector v = (Vector)listeningStyles.clone(); + Enumeration styleNames = styles.getStyleNames(); + @SuppressWarnings("unchecked") + Vector